iobroker.eos-admin 9.0.21 → 9.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NEXOWATT_EOS_BUILD_INFO.json +17 -11
- package/README.md +37 -9
- package/START_HIER_9.0.21.md +53 -0
- package/START_HIER_9.0.22.md +48 -0
- package/START_HIER_9.0.23.md +47 -0
- package/START_HIER_9.0.24.md +70 -0
- package/START_HIER_9.0.25.md +60 -0
- package/adminWww/.vite/manifest.json +55 -55
- package/adminWww/NEXOWATT_EOS_FRONTEND_MANIFEST.json +13760 -13760
- package/adminWww/assets/{AdapterUpdateDialog-Dxl_b7Op.js → AdapterUpdateDialog-CLDpmxDx.js} +1 -1
- package/adminWww/assets/{Adapters-CVKKhXmI.js → Adapters-BCGeX2v7.js} +1 -1
- package/adminWww/assets/{ConfigManager-Bf6nTAkL.js → ConfigManager-B_sJf5_w.js} +1 -1
- package/adminWww/assets/{Enums-CJHVJY7t.js → Enums-D3n1pOtc.js} +1 -1
- package/adminWww/assets/{Fields-DWHbZKvm.js → Fields-Bdx5gPoT.js} +1 -1
- package/adminWww/assets/{Files-a6owMTXA.js → Files-BPK84lYU.js} +1 -1
- package/adminWww/assets/{Hosts-LtEMeXpV.js → Hosts--Jr6oLf2.js} +1 -1
- package/adminWww/assets/{Instances-DhChziA1.js → Instances-DxTOzFus.js} +1 -1
- package/adminWww/assets/{Intro-Cyq9gVDC.js → Intro-CYBGeZtu.js} +1 -1
- package/adminWww/assets/{Logs-wcramXsg.js → Logs-CVNC-4S8.js} +1 -1
- package/adminWww/assets/{Objects-DINVHd_e.js → Objects-Cqm9Rvym.js} +1 -1
- package/adminWww/assets/{Overview-DK4R41zR.js → Overview-JgjcHwlz.js} +1 -1
- package/adminWww/assets/{State-DcEACXzL.js → State-BV14HSwZ.js} +1 -1
- package/adminWww/assets/{UsedResources-C1LcM0Rb.js → UsedResources-Dz48WzEF.js} +1 -1
- package/adminWww/assets/{Users-DvDdSyDY.js → Users-D19YlRCD.js} +1 -1
- package/adminWww/assets/{bootstrap-Dbj_GbnP.js → bootstrap-a7POLSDr.js} +4 -4
- package/adminWww/assets/{hostInit-BNFIx0-f.js → hostInit-keGjwsZR.js} +1 -1
- package/adminWww/assets/{icons-material-DVbdXNgr.js → icons-material-Omb_HCfb.js} +1 -1
- package/adminWww/assets/{index-CoKP1NSA.js → index-DqPrQK7T.js} +2 -2
- package/adminWww/assets/{installSVGRenderer-CMvku1F1.js → installSVGRenderer-iWfLFoQU.js} +1 -1
- package/adminWww/assets/{mf-entry-bootstrap-0-ac330bce.js → mf-entry-bootstrap-0-2a856bb6.js} +2 -2
- package/adminWww/index.html +23 -23
- package/adminWww/mf-manifest.json +1 -1
- package/adminWww/mf-stats.json +1 -1
- package/adminWww/remoteEntry-eos-9.0.25.js +12 -0
- package/adminWww/remoteEntry.js +1 -1
- package/build/lib/eosHistoryBackupScope.js +73 -0
- package/build/lib/eosHistoryBackupScope.js.map +1 -0
- package/build/lib/eosKiosk.js +348 -0
- package/build/lib/eosKiosk.js.map +1 -0
- package/build/lib/eosLegacyMigration.js +24 -3
- package/build/lib/eosLegacyMigration.js.map +1 -1
- package/build/lib/eosLicenseService.js +1 -1
- package/build/lib/eosLicenseService.js.map +1 -1
- package/build/lib/eosModuleConfigStore.js +2 -2
- package/build/lib/eosModuleConfigStore.js.map +1 -1
- package/build/lib/eosModuleHost.js +289 -25
- package/build/lib/eosModuleHost.js.map +1 -1
- package/build/lib/eosModuleHttp.js +71 -8
- package/build/lib/eosModuleHttp.js.map +1 -1
- package/build/lib/eosModuleProcess.js +317 -0
- package/build/lib/eosModuleProcess.js.map +1 -0
- package/build/lib/eosModuleProcessProtocol.js +213 -0
- package/build/lib/eosModuleProcessProtocol.js.map +1 -0
- package/build/lib/eosModuleProcessWorker.js +279 -0
- package/build/lib/eosModuleProcessWorker.js.map +1 -0
- package/build/lib/eosPostgresProvisioning.js +189 -0
- package/build/lib/eosPostgresProvisioning.js.map +1 -0
- package/build/lib/eosRuntimeControl.js +224 -0
- package/build/lib/eosRuntimeControl.js.map +1 -0
- package/build/lib/eosRuntimeHealth.js +170 -0
- package/build/lib/eosRuntimeHealth.js.map +1 -0
- package/build/lib/eosUiProcess.js +728 -0
- package/build/lib/eosUiProcess.js.map +1 -0
- package/build/lib/eosUiProcessRpc.js +292 -0
- package/build/lib/eosUiProcessRpc.js.map +1 -0
- package/build/lib/eosUiProcessWorker.js +443 -0
- package/build/lib/eosUiProcessWorker.js.map +1 -0
- package/build/lib/eosUiSecretCodec.js +64 -0
- package/build/lib/eosUiSecretCodec.js.map +1 -0
- package/build/lib/eosUnifiedBoundary.js +28 -4
- package/build/lib/eosUnifiedBoundary.js.map +1 -1
- package/build/lib/eosUpdateSnapshot.js +32 -1
- package/build/lib/eosUpdateSnapshot.js.map +1 -1
- package/build/lib/web.js +175 -18
- package/build/lib/web.js.map +1 -1
- package/build/main.js +6 -2
- package/build/main.js.map +1 -1
- package/docs/reports/unified-9.0.21/CRA_NACHWEISSTAND.md +159 -0
- package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_BACKEND_REVIEW.md +30 -0
- package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_UI_REVIEW.md +44 -0
- package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_WORKER_REVIEW.md +147 -0
- package/docs/reports/unified-9.0.21/CUSTOMER_WORKER_ZWEITPRUEFUNG.md +108 -0
- package/docs/reports/unified-9.0.21/DEVICE_STABILITY_REVIEW.md +50 -0
- package/docs/reports/unified-9.0.21/EMS_STABILITAET.md +41 -0
- package/docs/reports/unified-9.0.21/HISTORY_TARIFF_STABILITY_REVIEW.md +48 -0
- package/docs/reports/unified-9.0.21/MQTT_ZWEITPRUEFUNG_EMS.md +47 -0
- package/docs/reports/unified-9.0.21/PERSISTENZ_STABILITAET.md +76 -0
- package/docs/reports/unified-9.0.21/PRUEFBERICHT.md +64 -0
- package/docs/reports/unified-9.0.21/SECURITY_STABILITY_REVIEW.md +118 -0
- package/docs/reports/unified-9.0.21/UI_SECURITY_GATE_REVIEW.md +62 -0
- package/docs/reports/unified-9.0.21/UPDATE_HTTP_SNAPSHOT_PRUEFUNG.md +46 -0
- package/docs/reports/unified-9.0.21/raw/INDEX.json +1307 -0
- package/docs/reports/unified-9.0.21/raw/audit-full.log +345 -0
- package/docs/reports/unified-9.0.21/raw/audit-full.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/audit-runtime.log +23 -0
- package/docs/reports/unified-9.0.21/raw/audit-runtime.result.json +15 -0
- package/docs/reports/unified-9.0.21/raw/backend-final.log +5 -0
- package/docs/reports/unified-9.0.21/raw/backend-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/cra/frontend-installer-sbom.json +32 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-glue/root-glue-focused-node24.tap +34 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/real920-archive-inspection.json +20 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/service-node22.log +110 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/service-node24.log +24 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/service-verification.json +54 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-service/typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-node22.tap +86 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-node24.tap +20 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-strict-typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/independent-worker-probes.cjs +109 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/node22.tap +86 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/node24.tap +20 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/probes-node22.tap +44 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/probes-node24.tap +13 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/receipt.json +89 -0
- package/docs/reports/unified-9.0.21/raw/customer-update-worker/receipt.json +42 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-catch-node22.log +1959 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-test-update-node22.log +1968 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-test-update-node24.log +337 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-runtime-review-node22.log +1895 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-runtime-review-node24.log +317 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-final-node22.log +1959 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-final-node24.log +327 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-final-message-test-node22.log +36 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-final-message-test-node24.log +28 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-message-session-node22.log +36 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-message-session-node24.log +28 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-command-replay-repro-node22.log +15 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-command-replay-repro-node24.log +13 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-shutdown-repro-node22.log +16 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-shutdown-repro-node24.log +14 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-resources-node22.log +74 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-resources-node24.log +46 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-before-drain-test-update.json +206 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-before-runtime-review.json +150 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-final.json +275 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/commands.json +134 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/env-node22.log +3 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/env-node24.log +1 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-drain-test-update-node22.log +2 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-drain-test-update-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-runtime-review-node22.log +2 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-runtime-review-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-final-node22.log +2 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-final-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/mqtt-command-replay-repro.cjs +38 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/mqtt-shutdown-repro.cjs +31 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/regression-node22.log +322 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/regression-node24.log +55 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/run-evidence.py +23 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/run-final-evidence.py +20 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/runtime-lint-920.json +1 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/runtime-lint-921.json +1 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/source-hashes.json +16 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-drain-test-update-node22.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-drain-test-update-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-runtime-review-node22.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-runtime-review-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-final-node22.log +0 -0
- package/docs/reports/unified-9.0.21/raw/device-mqtt/types-final-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/ems/baseline-files-eslint.json +1 -0
- package/docs/reports/unified-9.0.21/raw/ems/changed-files-eslint.json +1 -0
- package/docs/reports/unified-9.0.21/raw/ems/engine.patch +38 -0
- package/docs/reports/unified-9.0.21/raw/ems/eslint-delta.json +6 -0
- package/docs/reports/unified-9.0.21/raw/ems/evidence.json +171 -0
- package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-baseline-node24.log +124 -0
- package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-node22.log +56 -0
- package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-node24.log +15 -0
- package/docs/reports/unified-9.0.21/raw/ems/farm-owned-methods.patch +133 -0
- package/docs/reports/unified-9.0.21/raw/ems/generated-regression-node22.log +460 -0
- package/docs/reports/unified-9.0.21/raw/ems/generated-regression-node24.log +82 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-frozen-node22.log +170 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-frozen-node24.log +33 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-review-node22.log +153 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-review-node24.log +39 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-reviewed-node22.log +170 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-reviewed-node24.log +33 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-queue-inheritance-before.log +28 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-baseline-node24.log +64 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-initial-timing.log +32 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-node22.log +44 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-node24.log +13 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-session-review.cjs +23 -0
- package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-session-review.log +119 -0
- package/docs/reports/unified-9.0.21/raw/ems/nvp-baseline-node22.log +170 -0
- package/docs/reports/unified-9.0.21/raw/ems/nvp-baseline-node24.log +121 -0
- package/docs/reports/unified-9.0.21/raw/ems/nvp-node22.log +68 -0
- package/docs/reports/unified-9.0.21/raw/ems/nvp-node24.log +17 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-code-delta-inventory.json +32 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-docs-check.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-farm-fingerprint-moves.json +74 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-lint-policy-tests.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-final-node22.log +5 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-final-node24.log +8 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-initial.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-main-full-delta.patch +135 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-reviewed-changes.json +93 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-reviewed-findings-before.json +3185 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-security-final-node22.json +28833 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-security-final-node24.json +28833 -0
- package/docs/reports/unified-9.0.21/raw/ems/ui-security-inventory-before.json +28991 -0
- package/docs/reports/unified-9.0.21/raw/ems/update-ui-reviewed-findings.cjs +59 -0
- package/docs/reports/unified-9.0.21/raw/frontend-build.log +152 -0
- package/docs/reports/unified-9.0.21/raw/frontend-build.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/frontend-installer-sbom.json +32 -0
- package/docs/reports/unified-9.0.21/raw/history/baseline920-influx-sequence-node24.log +12 -0
- package/docs/reports/unified-9.0.21/raw/history/baseline920-outage-node24.log +64 -0
- package/docs/reports/unified-9.0.21/raw/history/cra-tariff-source-node22.log +38 -0
- package/docs/reports/unified-9.0.21/raw/history/cra-tariff-source-node24.log +36 -0
- package/docs/reports/unified-9.0.21/raw/history/lint-baseline-comparison.json +83 -0
- package/docs/reports/unified-9.0.21/raw/history/lint-scope.cjs +29 -0
- package/docs/reports/unified-9.0.21/raw/history/regression-node22.log +438 -0
- package/docs/reports/unified-9.0.21/raw/history/regression-node24.log +75 -0
- package/docs/reports/unified-9.0.21/raw/history/results-node22.json +37 -0
- package/docs/reports/unified-9.0.21/raw/history/results-node24.json +66 -0
- package/docs/reports/unified-9.0.21/raw/history/run-checks.py +18 -0
- package/docs/reports/unified-9.0.21/raw/history/source-evidence.json +83 -0
- package/docs/reports/unified-9.0.21/raw/installer-build.log +26 -0
- package/docs/reports/unified-9.0.21/raw/installer-build.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/keygen-source.json +6 -0
- package/docs/reports/unified-9.0.21/raw/lint-final.log +16 -0
- package/docs/reports/unified-9.0.21/raw/lint-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/modules-build.log +5 -0
- package/docs/reports/unified-9.0.21/raw/modules-build.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/node22-tests-final.log +13274 -0
- package/docs/reports/unified-9.0.21/raw/node22-tests-final.result.json +13 -0
- package/docs/reports/unified-9.0.21/raw/node22-typecheck-final.log +7 -0
- package/docs/reports/unified-9.0.21/raw/node22-typecheck-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/node22-version.log +1 -0
- package/docs/reports/unified-9.0.21/raw/node24-tests-final.log +2223 -0
- package/docs/reports/unified-9.0.21/raw/node24-tests-final.result.json +13 -0
- package/docs/reports/unified-9.0.21/raw/node24-typecheck-final.log +5 -0
- package/docs/reports/unified-9.0.21/raw/node24-typecheck-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/node24-version.log +1 -0
- package/docs/reports/unified-9.0.21/raw/persistence/920-http-draft-revision-node24.log +50 -0
- package/docs/reports/unified-9.0.21/raw/persistence/920-late-commit-overwrite-node24.log +30 -0
- package/docs/reports/unified-9.0.21/raw/persistence/920-save-lifecycle-node24.log +59 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-backend-types.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-editor-lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-eebus-editor-typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-final-format-review.json +24 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-new-update-http-before.log +177 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-new-update-snapshot-before.log +80 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node22.log +1019 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node22.receipt.json +28 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node24.log +174 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node24.receipt.json +28 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-eslint-final.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node22.log +137 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node22.receipt.json +21 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node24.log +30 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node24.receipt.json +21 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-strict-typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-typecheck-final.log +0 -0
- package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-after.log +3 -0
- package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-before-observation.json +25 -0
- package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-repro.cjs +7 -0
- package/docs/reports/unified-9.0.21/raw/persistence/source-files.pre-final-format.sha256 +14 -0
- package/docs/reports/unified-9.0.21/raw/persistence/source-files.sha256 +14 -0
- package/docs/reports/unified-9.0.21/raw/release-overlay/obsolete-assets-920-added.json +94 -0
- package/docs/reports/unified-9.0.21/raw/release-overlay/publish-catalog-regression.log +49 -0
- package/docs/reports/unified-9.0.21/raw/release-overlay/publish-catalog-regression.result.json +15 -0
- package/docs/reports/unified-9.0.21/raw/sbom-runtime.log +7 -0
- package/docs/reports/unified-9.0.21/raw/sbom-runtime.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/sbom-vendor-check.log +1 -0
- package/docs/reports/unified-9.0.21/raw/sbom-vendor-check.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/backend-typecheck.log +0 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/boundaries-node22.tap +495 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/boundaries-node24.tap +88 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/coexistence-node22.tap +179 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/coexistence-node24.tap +36 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/results.json +118 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/upload-admission-before-node22.tap +63 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/upload-admission-before-node24.tap +47 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/upload-lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/upload-node22.tap +148 -0
- package/docs/reports/unified-9.0.21/raw/security-stability/upload-node24.tap +30 -0
- package/docs/reports/unified-9.0.21/raw/ui-docs-check.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ui-docs-check.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-runtime-final.log +7 -0
- package/docs/reports/unified-9.0.21/raw/ui-runtime-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-runtime-sync.log +1 -0
- package/docs/reports/unified-9.0.21/raw/ui-runtime-sync.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-sbom-check.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ui-sbom-check.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-sbom-final.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ui-sbom-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-secret-final.log +6 -0
- package/docs/reports/unified-9.0.21/raw/ui-secret-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/ui-security-final.log +8 -0
- package/docs/reports/unified-9.0.21/raw/ui-security-final.result.json +14 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/baseline-ui.log +280 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/browser-preview.test.cjs +170 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/draft-regression.log +214 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/eos-updates-before.ts +171 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/lint.log +0 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/results.json +90 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/source-evidence.json +30 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/type-node22.log +0 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/type-node24.log +0 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/ui-node22.log +98 -0
- package/docs/reports/unified-9.0.21/raw/update-ui/ui-node24.log +22 -0
- package/docs/reports/unified-9.0.22/BACKUP_POSTGRES_FOLLOWUP.md +44 -0
- package/docs/reports/unified-9.0.22/ENERGIEFLUSS_BROWSERPRUEFUNG.md +40 -0
- package/docs/reports/unified-9.0.22/ENERGY_FLOW_BACKEND.md +44 -0
- package/docs/reports/unified-9.0.22/FLOW_TARIFF_INDEPENDENT_REVIEW.md +33 -0
- package/docs/reports/unified-9.0.22/OCPP_STOP_WRITER_REVIEW.md +27 -0
- package/docs/reports/unified-9.0.22/POSTGRESQL_SYSTEM_SETUP.md +34 -0
- package/docs/reports/unified-9.0.22/PRUEFBERICHT.md +85 -0
- package/docs/reports/unified-9.0.22/flow/PRUEFVERMERK.md +42 -0
- package/docs/reports/unified-9.0.22/flow/frontend-cadence-tests.log +37 -0
- package/docs/reports/unified-9.0.22/flow/frontend-source-hashes.json +13 -0
- package/docs/reports/unified-9.0.22/flow/frontend-tests.log +31 -0
- package/docs/reports/unified-9.0.22/postgres-history-review.md +43 -0
- package/docs/reports/unified-9.0.22/postgres-real-review.tap +21 -0
- package/docs/reports/unified-9.0.22/postgres-review-lint.log +0 -0
- package/docs/reports/unified-9.0.22/postgres-review-typecheck.log +0 -0
- package/docs/reports/unified-9.0.22/postgres-review-unit-api.tap +25 -0
- package/docs/reports/unified-9.0.22/raw/INDEX.json +43 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/eslint-backup.log +0 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-after.tap +13 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-before.tap +54 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-test-eslint.log +0 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/influx-real-node24.tap +11 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/scope-hashes.json +51 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/storage-nullable-before.tap +96 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/storage-nullable-flow.tap +12 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/tests-node24.tap +116 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-backup-scope.log +0 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-backup.log +0 -0
- package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-postgres-setup.log +0 -0
- package/docs/reports/unified-9.0.22/raw/current/admin-build.log +152 -0
- package/docs/reports/unified-9.0.22/raw/current/availability-final.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/backend-build.log +5 -0
- package/docs/reports/unified-9.0.22/raw/current/baseline-repairs.log +60 -0
- package/docs/reports/unified-9.0.22/raw/current/baseline-unified.log +1675 -0
- package/docs/reports/unified-9.0.22/raw/current/combined-fixes.log +65 -0
- package/docs/reports/unified-9.0.22/raw/current/control-final.log +25 -0
- package/docs/reports/unified-9.0.22/raw/current/energyflow-browser.json +244 -0
- package/docs/reports/unified-9.0.22/raw/current/energyflow-browser.stderr +0 -0
- package/docs/reports/unified-9.0.22/raw/current/energyflow-cadence-browser.json +63 -0
- package/docs/reports/unified-9.0.22/raw/current/energyflow-cadence-browser.stderr +0 -0
- package/docs/reports/unified-9.0.22/raw/current/lint-final.log +5 -0
- package/docs/reports/unified-9.0.22/raw/current/lint.log +5 -0
- package/docs/reports/unified-9.0.22/raw/current/markdown-build.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/modules-build.log +5 -0
- package/docs/reports/unified-9.0.22/raw/current/pre-ocpp-full.log +2337 -0
- package/docs/reports/unified-9.0.22/raw/current/production-audit.json +22 -0
- package/docs/reports/unified-9.0.22/raw/current/production-audit.stderr +1 -0
- package/docs/reports/unified-9.0.22/raw/current/runtime-build-final.log +8 -0
- package/docs/reports/unified-9.0.22/raw/current/runtime-build.log +32 -0
- package/docs/reports/unified-9.0.22/raw/current/runtime-sync.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/safety-envelope-final.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/sbom-lock-graph.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/sbom.log +6120 -0
- package/docs/reports/unified-9.0.22/raw/current/station-permission-final.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/storage-feedforward-final.log +1 -0
- package/docs/reports/unified-9.0.22/raw/current/typecheck-final.log +5 -0
- package/docs/reports/unified-9.0.22/raw/current/typecheck.log +5 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/eslint.txt +0 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-availability.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-safety.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-station.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-tests.tap +124 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-availability.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-safety.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-station.txt +1 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-tests.tap +26 -0
- package/docs/reports/unified-9.0.22/raw/ems-control-points/typecheck.txt +0 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/core-pv-node22.tap +30 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/core-pv-node24.tap +11 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/environment.json +7 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/lint.log +0 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/node22.tap +164 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/node24.tap +33 -0
- package/docs/reports/unified-9.0.22/raw/flow-backend/typecheck.log +0 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/browser-runtime.json +11 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/browser-smoke.json +49 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/browser-smoke.stderr +0 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/build.log +18 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/environment.json +38 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/lint.log +0 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/node22.tap +144 -0
- package/docs/reports/unified-9.0.22/raw/history-ui/node24.tap +30 -0
- package/docs/reports/unified-9.0.22/raw/node22-tests-final.log +14086 -0
- package/docs/reports/unified-9.0.22/raw/node22-version.log +1 -0
- package/docs/reports/unified-9.0.22/raw/node24-tests-final.log +2356 -0
- package/docs/reports/unified-9.0.22/raw/node24-version.log +1 -0
- package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-eslint.log +0 -0
- package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-node22.tap +72 -0
- package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-node24.tap +70 -0
- package/docs/reports/unified-9.0.22/raw/postgresql-system/status-eslint.log +0 -0
- package/docs/reports/unified-9.0.22/raw/postgresql-system/typecheck.log +0 -0
- package/docs/reports/unified-9.0.23/MODULE_PROCESS_IMPLEMENTATION.md +43 -0
- package/docs/reports/unified-9.0.23/OCPP_0.4.3_ERGEBNIS.json +24 -0
- package/docs/reports/unified-9.0.23/OCPP_0.4.3_PRUEFBERICHT.md +50 -0
- package/docs/reports/unified-9.0.23/OCPP_AUTOMATISCHE_ZUORDNUNG.md +49 -0
- package/docs/reports/unified-9.0.23/OCPP_CM_INTEGRATION.md +31 -0
- package/docs/reports/unified-9.0.23/PROZESSDIAGNOSE.md +35 -0
- package/docs/reports/unified-9.0.23/PRUEFBERICHT.md +75 -0
- package/docs/reports/unified-9.0.23/UI_EMS_PROZESSGRENZE.md +36 -0
- package/docs/reports/unified-9.0.23/UI_PROCESS_INDEPENDENT_FOLLOWUP.md +33 -0
- package/docs/reports/unified-9.0.23/module-process-contract-review-node22.tap +86 -0
- package/docs/reports/unified-9.0.23/module-process-contract-review-node24.tap +20 -0
- package/docs/reports/unified-9.0.23/module-process-contract-review.md +39 -0
- package/docs/reports/unified-9.0.23/module-process-contract-review.tap +20 -0
- package/docs/reports/unified-9.0.23/module-process-final.tap +27 -0
- package/docs/reports/unified-9.0.23/module-process-static.json +57 -0
- package/docs/reports/unified-9.0.23/raw/INDEX.json +43 -0
- package/docs/reports/unified-9.0.23/raw/build-backend-final.log +5 -0
- package/docs/reports/unified-9.0.23/raw/build-frontend.log +152 -0
- package/docs/reports/unified-9.0.23/raw/build-installer.log +26 -0
- package/docs/reports/unified-9.0.23/raw/build-ui-final.log +7 -0
- package/docs/reports/unified-9.0.23/raw/current/evcs-stop-writer-ocpp043.txt +20 -0
- package/docs/reports/unified-9.0.23/raw/current/ocpp-runtime-feedback-lint.txt +1 -0
- package/docs/reports/unified-9.0.23/raw/current/ocpp-runtime-feedback-tests.txt +28 -0
- package/docs/reports/unified-9.0.23/raw/current/runtime-health-browser.json +49 -0
- package/docs/reports/unified-9.0.23/raw/current/runtime-health-browser.stderr.txt +0 -0
- package/docs/reports/unified-9.0.23/raw/current/runtime-health-lint.txt +1 -0
- package/docs/reports/unified-9.0.23/raw/current/runtime-health-tests.txt +27 -0
- package/docs/reports/unified-9.0.23/raw/current/runtime-health-types.txt +1 -0
- package/docs/reports/unified-9.0.23/raw/eos-production-audit.json +22 -0
- package/docs/reports/unified-9.0.23/raw/idle-pwa-node22.log +75 -0
- package/docs/reports/unified-9.0.23/raw/idle-pwa-node24.log +22 -0
- package/docs/reports/unified-9.0.23/raw/lint-final.log +5 -0
- package/docs/reports/unified-9.0.23/raw/node22-tests-final.log +14612 -0
- package/docs/reports/unified-9.0.23/raw/node22-version.log +1 -0
- package/docs/reports/unified-9.0.23/raw/node24-tests-final.log +2443 -0
- package/docs/reports/unified-9.0.23/raw/node24-version.log +1 -0
- package/docs/reports/unified-9.0.23/raw/ocpp-auto-discovery.log +21 -0
- package/docs/reports/unified-9.0.23/raw/ocpp-discovery-browser.json +55 -0
- package/docs/reports/unified-9.0.23/raw/ocpp-discovery-lifecycle-regression.log +48 -0
- package/docs/reports/unified-9.0.23/raw/ocpp-production-audit.json +69 -0
- package/docs/reports/unified-9.0.23/raw/typecheck-final.log +5 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/discovery-review.tap +21 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/lint.log +0 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/node22.tap +118 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/node24.tap +112 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/root-typecheck.log +0 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/typecheck.log +0 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/unified-listen-build-node24.tap +196 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/unified-listen-node22.tap +200 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/web-lint.log +0 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/web-pipeline-node22.tap +92 -0
- package/docs/reports/unified-9.0.23/raw/ui-process/web-pipeline-node24.tap +90 -0
- package/docs/reports/unified-9.0.23/ui-process-contract-review.md +30 -0
- package/docs/reports/unified-9.0.23/ui-process-final-review-node22.tap +50 -0
- package/docs/reports/unified-9.0.23/ui-process-final-review-node24.tap +14 -0
- package/docs/reports/unified-9.0.23/ui-process-followup-hashes.json +13 -0
- package/docs/reports/unified-9.0.23/ui-process-operational-review-node22.tap +30 -0
- package/docs/reports/unified-9.0.23/ui-process-operational-review-node24.tap +11 -0
- package/docs/reports/unified-9.0.23/ui-process-review-node22.tap +48 -0
- package/docs/reports/unified-9.0.23/ui-process-review-node24.tap +46 -0
- package/docs/reports/unified-9.0.24/BACKUP_INTEROP_PRUEFBERICHT.md +48 -0
- package/docs/reports/unified-9.0.24/KIOSK_FRONTEND_BROWSERPRUEFUNG.md +49 -0
- package/docs/reports/unified-9.0.24/KIOSK_UNABHAENGIGER_REVIEW.md +21 -0
- package/docs/reports/unified-9.0.24/OCPP_HOST_MIGRATION.md +41 -0
- package/docs/reports/unified-9.0.24/OCPP_NAMESPACE_REGELPFAD.md +55 -0
- package/docs/reports/unified-9.0.24/OCPP_UNABHAENGIGER_REVIEW.md +37 -0
- package/docs/reports/unified-9.0.24/OCPP_VERWALTUNG.md +33 -0
- package/docs/reports/unified-9.0.24/PRUEFBERICHT.md +54 -0
- package/docs/reports/unified-9.0.24/PUBLISH_OVERLAY_9_0_21.md +23 -0
- package/docs/reports/unified-9.0.24/raw/INDEX.json +43 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/ems-independence-node24.tap +9 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/final-node22.tap +175 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/final-node24.tap +35 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/focused-node22.tap +132 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/focused-node24.tap +27 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/kiosk-review-node24.tap +13 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/kiosk-update-snapshot-node24.tap +22 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/lint-source.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/lint-tests.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/ocpp-backup-node24.tap +10 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/own-source-hashes.json +12 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/types.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/backup-interop/update-snapshot-node24.tap +20 -0
- package/docs/reports/unified-9.0.24/raw/build.log +200 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser-node22.json +69 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser-node22.stderr.txt +3 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser.json +69 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser.stderr.txt +2 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-http-node22.txt +253 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-http-node24.txt +52 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-lint.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-types.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-lease-registration-before.txt +28 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-namespace-independent-node22.txt +302 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-namespace-independent-node24.txt +55 -0
- package/docs/reports/unified-9.0.24/raw/current/ocpp-native-generic-before.txt +25 -0
- package/docs/reports/unified-9.0.24/raw/current/runtime-health-browser.json +49 -0
- package/docs/reports/unified-9.0.24/raw/current/runtime-health-browser.stderr.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/current/runtime-health-types.txt +0 -0
- package/docs/reports/unified-9.0.24/raw/eos-production-audit.json +77 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-auth-profiles-node22.log +16 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-auth-profiles-node24.log +14 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-browser-node22.json +57 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-browser-node24.json +57 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-idle-node22.log +215 -0
- package/docs/reports/unified-9.0.24/raw/kiosk-idle-node24.log +42 -0
- package/docs/reports/unified-9.0.24/raw/lint.log +45 -0
- package/docs/reports/unified-9.0.24/raw/node22-tests-final.log +15517 -0
- package/docs/reports/unified-9.0.24/raw/node22-version.log +1 -0
- package/docs/reports/unified-9.0.24/raw/node24-tests-final.log +2595 -0
- package/docs/reports/unified-9.0.24/raw/node24-version.log +1 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-host-node22.tap +105 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-host-node24.tap +24 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-host-regression-node22.tap +818 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-host-regression-node24.tap +140 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-hosted-mapping-browser.log +2 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-legacy-mapping-browser.log +2 -0
- package/docs/reports/unified-9.0.24/raw/ocpp-namespace-control.log +49 -0
- package/docs/reports/unified-9.0.24/raw/publish-overlay-node22.tap +278 -0
- package/docs/reports/unified-9.0.24/raw/publish-overlay-node24.tap +52 -0
- package/docs/reports/unified-9.0.24/raw/publish-overlay-provenance-922-923.json +32 -0
- package/docs/reports/unified-9.0.24/raw/publish-overlay-provenance.json +19 -0
- package/docs/reports/unified-9.0.24/raw/typecheck.log +5 -0
- package/docs/reports/unified-9.0.25/MIGRATION_INDEPENDENT_REVIEW.md +74 -0
- package/docs/reports/unified-9.0.25/OCPP_STARTSPERRE_9.0.24.md +60 -0
- package/docs/reports/unified-9.0.25/PRUEFBERICHT.md +78 -0
- package/docs/reports/unified-9.0.25/RUNTIME_CONTROLS_BROWSERPRUEFUNG.md +81 -0
- package/docs/reports/unified-9.0.25/RUNTIME_CONTROL_BACKEND.md +58 -0
- package/docs/reports/unified-9.0.25/RUNTIME_CONTROL_INDEPENDENT_REVIEW.md +66 -0
- package/docs/reports/unified-9.0.25/RUNTIME_LOGIN_RECOVERY.md +32 -0
- package/docs/reports/unified-9.0.25/TARIFF_UPDATE_PERSISTENCE.md +50 -0
- package/docs/reports/unified-9.0.25/UI_CONFIG_COMMIT_ACK.md +51 -0
- package/docs/reports/unified-9.0.25/raw/BUILD_CHECKS.json +49 -0
- package/docs/reports/unified-9.0.25/raw/INDEX.json +43 -0
- package/docs/reports/unified-9.0.25/raw/SBOM_GENERATION.json +42 -0
- package/docs/reports/unified-9.0.25/raw/build-backend.log +5 -0
- package/docs/reports/unified-9.0.25/raw/build-frontend.log +152 -0
- package/docs/reports/unified-9.0.25/raw/build-installer.log +26 -0
- package/docs/reports/unified-9.0.25/raw/build-modules.log +5 -0
- package/docs/reports/unified-9.0.25/raw/build-ui-runtime.log +7 -0
- package/docs/reports/unified-9.0.25/raw/eos-production-audit.json +77 -0
- package/docs/reports/unified-9.0.25/raw/eos-production-audit.stderr +1 -0
- package/docs/reports/unified-9.0.25/raw/frontend-sbom.stderr +1 -0
- package/docs/reports/unified-9.0.25/raw/installer-sbom.stderr +1 -0
- package/docs/reports/unified-9.0.25/raw/lint.log +45 -0
- package/docs/reports/unified-9.0.25/raw/node22-tests-final.log +15879 -0
- package/docs/reports/unified-9.0.25/raw/node22-version.log +1 -0
- package/docs/reports/unified-9.0.25/raw/node24-tests-final.log +2653 -0
- package/docs/reports/unified-9.0.25/raw/node24-version.log +1 -0
- package/docs/reports/unified-9.0.25/raw/runtime-control-backend/runtime-control-backend-node22-final.tap +236 -0
- package/docs/reports/unified-9.0.25/raw/runtime-control-backend/runtime-control-backend-node24-final.tap +44 -0
- package/docs/reports/unified-9.0.25/raw/runtime-control-backend/source-sha256.json +19 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/controls-node22.json +70 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/controls-node24.json +70 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/health-node22.json +49 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/health-node24.json +49 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/login-contract-node22.log +15 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/login-contract-node24.log +15 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/login-node22.json +32 -0
- package/docs/reports/unified-9.0.25/raw/runtime-controls/login-node24.json +32 -0
- package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/node22.log +28 -0
- package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/node24.log +10 -0
- package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/route-regression-node24.log +28 -0
- package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/source-sha256.json +6 -0
- package/docs/reports/unified-9.0.25/raw/runtime-processes/README.md +41 -0
- package/docs/reports/unified-9.0.25/raw/runtime-processes/runtime-control-processes-node22.tap +44 -0
- package/docs/reports/unified-9.0.25/raw/runtime-processes/runtime-control-processes-node24.tap +13 -0
- package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-and-ui-review-node22.tap +232 -0
- package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-and-ui-review-node24.tap +43 -0
- package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-review-node22.tap +68 -0
- package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-review-node24.tap +17 -0
- package/docs/reports/unified-9.0.25/raw/sbom-lock.log +1 -0
- package/docs/reports/unified-9.0.25/raw/sbom-lock.stderr +1 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/ack-node22.tap +44 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/ack-node24.tap +40 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/ack-review-node22.tap +44 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/ack-review-node24.tap +13 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/commit-ack-sha256.txt +4 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/config-ack-result.json +19 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/generate-921-fixture.cjs +36 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/node22.tap +68 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/node24.tap +64 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/reproduce-config-ack.cjs +55 -0
- package/docs/reports/unified-9.0.25/raw/tariff-update/reviewed-sha256.txt +4 -0
- package/docs/reports/unified-9.0.25/raw/typecheck.log +5 -0
- package/docs/unified/EMS_BEDIEN_DATENPUNKTE_9_0_22.md +51 -0
- package/docs/unified/HISTORY_UI_9_0_22.md +75 -0
- package/docs/unified/POSTGRESQL_9_0_22.md +89 -0
- package/io-package.json +20 -22
- package/modules/backup/README.md +10 -0
- package/modules/backup/RECOVERY-9.0.22.md +59 -0
- package/modules/backup/admin/index.html +2 -1
- package/modules/backup/admin/index.js +17 -1
- package/modules/backup/build/config.js +2 -0
- package/modules/backup/build/coverage.js +64 -0
- package/modules/backup/build/creators.js +22 -17
- package/modules/backup/build/databaseTargets.js +42 -0
- package/modules/backup/build/index.js +47 -4
- package/modules/backup/build/influxIntegrity.js +159 -0
- package/modules/backup/build/postgresHistory.js +91 -0
- package/modules/backup/build/preflight.js +3 -8
- package/modules/backup/build/publicTrust.js +46 -0
- package/modules/backup/build/restore-cli.js +72 -1
- package/modules/backup/build/storageRetention.js +26 -0
- package/modules/backup/build/worker.js +18 -1
- package/modules/backup/src/config.ts +2 -0
- package/modules/backup/src/coverage.ts +50 -0
- package/modules/backup/src/creators.ts +20 -17
- package/modules/backup/src/databaseTargets.ts +45 -0
- package/modules/backup/src/index.ts +37 -4
- package/modules/backup/src/influxIntegrity.ts +125 -0
- package/modules/backup/src/postgresHistory.ts +66 -0
- package/modules/backup/src/preflight.ts +3 -10
- package/modules/backup/src/publicTrust.ts +34 -0
- package/modules/backup/src/restore-cli.ts +55 -4
- package/modules/backup/src/storageRetention.ts +20 -0
- package/modules/backup/src/types.ts +5 -0
- package/modules/backup/src/worker.ts +18 -2
- package/modules/backup/test/completeness.test.cjs +193 -0
- package/modules/backup/test/hosted.test.cjs +43 -3
- package/modules/backup/test/influx-real.test.cjs +75 -0
- package/modules/backup/test/lifecycle.test.cjs +7 -5
- package/modules/backup/test/ocpp-coverage.test.cjs +152 -0
- package/modules/devices/admin/index.html +1 -1
- package/modules/eebus/admin/index.html +1 -1
- package/modules/ocpp/LICENSE +21 -0
- package/modules/ocpp/README.md +61 -0
- package/modules/ocpp/admin/config-fields.json +353 -0
- package/modules/ocpp/admin/index.html +52 -0
- package/modules/ocpp/admin/index.js +228 -0
- package/modules/ocpp/admin/style.css +27 -0
- package/modules/ocpp/build/index.js +401 -0
- package/modules/ocpp/build/operationGuard.js +26 -0
- package/modules/ocpp/build/server.js +155 -0
- package/modules/ocpp/eslint.config.mjs +13 -0
- package/modules/ocpp/index.js +3 -0
- package/modules/ocpp/native-defaults.json +44 -0
- package/modules/ocpp/ocpp/common.js +646 -0
- package/modules/ocpp/ocpp/compact.js +332 -0
- package/modules/ocpp/ocpp/configuration.js +364 -0
- package/modules/ocpp/ocpp/eos-contract.js +149 -0
- package/modules/ocpp/ocpp/freshness.d.ts +10 -0
- package/modules/ocpp/ocpp/freshness.js +272 -0
- package/modules/ocpp/ocpp/schemas/NOTICE.md +17 -0
- package/modules/ocpp/ocpp/schemas/ocpp2_0_1_official.json +1 -0
- package/modules/ocpp/ocpp/schemas/ocpp2_1_official.json +1 -0
- package/modules/ocpp/ocpp/server.js +3 -0
- package/modules/ocpp/ocpp/v16.js +213 -0
- package/modules/ocpp/ocpp/v201.js +4 -0
- package/modules/ocpp/ocpp/v21.js +4 -0
- package/modules/ocpp/ocpp/v2base.js +255 -0
- package/modules/ocpp/package.json +11 -0
- package/modules/ocpp/provenance.json +33 -0
- package/modules/ocpp/runtime.d.ts +16 -0
- package/modules/ocpp/runtime.js +3391 -0
- package/modules/ocpp/src/index.ts +463 -0
- package/modules/ocpp/src/operationGuard.ts +29 -0
- package/modules/ocpp/src/server.ts +193 -0
- package/modules/ocpp/test/configuration-runtime.test.js +786 -0
- package/modules/ocpp/test/core.test.js +772 -0
- package/modules/ocpp/test/eos-contract.test.js +67 -0
- package/modules/ocpp/test/hosted.test.cjs +165 -0
- package/modules/ocpp/tsconfig.json +7 -0
- package/modules/ocpp/validation/manifest.json +36 -0
- package/modules/ocpp/validation/node22-tests.log +525 -0
- package/modules/ocpp/validation/node24-tests.log +92 -0
- package/package.json +29 -11
- package/public/eos-migration/index.html +1 -1
- package/public/eos-migration/index.js +2 -2
- package/public/eos-runtime/index.html +36 -0
- package/public/eos-runtime/index.js +249 -0
- package/public/eos-runtime/style.css +27 -0
- package/release-manifests/unified/build-environment.cdx.json +767 -131
- package/release-manifests/unified/files.json +700 -214
- package/release-manifests/unified/frontend.cdx.json +6 -6
- package/release-manifests/unified/installer.cdx.json +6 -6
- package/release-manifests/unified/obsolete-admin-assets.json +292 -6
- package/release-manifests/unified/runtime.cdx.json +871 -143
- package/release-manifests/unified/validation.json +15 -15
- package/reports/unified/ocpp-pure-pv-9.0.22/PRUEFVERMERK.md +35 -0
- package/reports/unified/ocpp-pure-pv-9.0.22/raw/auto-pv-phases.log +1 -0
- package/reports/unified/ocpp-pure-pv-9.0.22/raw/control-tests.log +11 -0
- package/reports/unified/ocpp-pure-pv-9.0.22/raw/ocpp-stability.log +1 -0
- package/reports/unified/ocpp-pure-pv-9.0.22/raw/rc60.log +1 -0
- package/reports/unified/tariff-energy-flow-9.0.22/PRUEFVERMERK.md +44 -0
- package/reports/unified/tariff-energy-flow-9.0.22/raw/focused-tests.log +37 -0
- package/reports/unified/tariff-energy-flow-9.0.22/raw/grid-charge-policy.log +1 -0
- package/reports/unified/tariff-energy-flow-9.0.22/raw/status-truth.log +1 -0
- package/tools/eos-release-check.cjs +5 -0
- package/tools/eos-release-manifest.cjs +3 -3
- package/tools/eos-sbom-vendored.cjs +2 -1
- package/tools/system/eos-postgresql-setup.cjs +409 -0
- package/tsconfig.eos-history-backup-scope.json +9 -0
- package/tsconfig.eos-postgres-system.json +15 -0
- package/ui/admin/react/assets/index-wHWXfD_g.js +13 -0
- package/ui/admin/react/index.html +1 -1
- package/ui/ems/consumers/evcs.js +11 -7
- package/ui/ems/datapoints.js +14 -5
- package/ui/ems/engine.js +4 -1
- package/ui/ems/modules/charging-management.js +193 -63
- package/ui/ems/modules/core-limits.js +15 -20
- package/ui/ems/modules/storage-control.js +8 -6
- package/ui/ems/modules/tarif-vis.js +7 -2
- package/ui/ems/modules/tariff-status.js +19 -1
- package/ui/eslint.postgres-history.config.mjs +9 -0
- package/ui/io-package.json +5 -1
- package/ui/lib/ems-control-values.js +64 -0
- package/ui/lib/flow-measurement.js +72 -0
- package/ui/lib/hosted-adapter.js +12 -1
- package/ui/lib/influx-history-runtime.js +66 -24
- package/ui/lib/installer-lifecycle.js +4 -2
- package/ui/lib/ocpp-auto-discovery.js +397 -0
- package/ui/lib/ocpp-limit-feedback.js +166 -0
- package/ui/lib/partner-runtime.js +35 -2
- package/ui/lib/partner-websocket.js +4 -1
- package/ui/lib/postgres-history-config.js +57 -0
- package/ui/lib/postgres-history.js +344 -0
- package/ui/lib/runtime-proxy-html.js +34 -1
- package/ui/lib/smarthome-device-controls.js +4 -1
- package/ui/lib/ui-access-policy.js +39 -6
- package/ui/main.js +392 -222
- package/ui/package.json +1 -1
- package/ui/tsconfig.postgres-history.json +4 -0
- package/ui/www/app.js +106 -152
- package/ui/www/auth.js +36 -10
- package/ui/www/charging-diagnostics-appcenter.js +1 -0
- package/ui/www/customer-tariff.js +1 -0
- package/ui/www/dashboard-lp-status.js +1 -0
- package/ui/www/dc-station-display.js +1 -0
- package/ui/www/ems-apps.js +48 -8
- package/ui/www/energy-origin-appcenter.js +1 -0
- package/ui/www/energy-origin-ledger-view.js +1 -0
- package/ui/www/eos-kiosk-settings.js +174 -0
- package/ui/www/eos-session-idle.js +40 -6
- package/ui/www/eos-updates.js +1 -0
- package/ui/www/index.html +2 -1
- package/ui/www/license.js +1 -0
- package/ui/www/licenses/smarthome-markdown-components.json +157 -157
- package/ui/www/live-display.js +4 -2
- package/ui/www/login.js +25 -9
- package/ui/www/manifest.webmanifest +3 -3
- package/ui/www/netoperator-appcenter.js +1 -0
- package/ui/www/netoperator.js +1 -0
- package/ui/www/operating-strategies-appcenter.js +1 -0
- package/ui/www/operating-strategies-rule-builder.js +1 -0
- package/ui/www/power-measurements.js +27 -2
- package/ui/www/pwa.js +1 -0
- package/ui/www/runtime-base.js +1 -0
- package/ui/www/settings.html +13 -1
- package/ui/www/smarthome-activation.js +1 -0
- package/ui/www/smarthome-alias-config.js +1 -0
- package/ui/www/smarthome-custom-config.js +1 -0
- package/ui/www/smarthome-custom-views.js +1 -0
- package/ui/www/smarthome-device-categories.js +1 -0
- package/ui/www/smarthome-device-config.js +1 -0
- package/ui/www/smarthome-device-controls.js +1 -0
- package/ui/www/smarthome-feedback.js +1 -0
- package/ui/www/smarthome-layout-editor.js +1 -0
- package/ui/www/smarthome-presentation.js +1 -0
- package/ui/www/smarthome-setup.js +1 -0
- package/ui/www/smarthome-touch.js +1 -0
- package/ui/www/storagefarm-dispatch.js +1 -0
- package/ui/www/storagefarm-summary.js +1 -0
- package/ui/www/tariff-display.js +62 -2
- package/adminWww/remoteEntry-eos-9.0.21.js +0 -12
- package/ui/admin/react/assets/index-BJO3q7oe.js +0 -13
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{"filePath":"/workspace/scratch/741f792566ea/source-920/iobroker.eos-admin/modules/devices/lib/deviceRuntime.js","messages":[{"ruleId":"no-unused-vars","severity":2,"message":"'path' is assigned a value but never used.","line":3,"column":7,"nodeType":"Identifier","messageId":"unusedVar","endLine":3,"endColumn":11,"suggestions":[{"messageId":"removeVar","data":{"varName":"path"},"fix":{"range":[15,44],"text":""},"desc":"Remove unused variable 'path'."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":626,"column":17,"nodeType":"BlockStatement","messageId":"unexpected","endLine":626,"endColumn":19,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[23191,23191],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":630,"column":17,"nodeType":"BlockStatement","messageId":"unexpected","endLine":630,"endColumn":19,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[23353,23353],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":1036,"column":60,"nodeType":"BlockStatement","messageId":"unexpected","endLine":1036,"endColumn":62,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[38578,38578],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-control-regex","severity":2,"message":"Unexpected control character(s) in regular expression: \\x00.","line":3261,"column":22,"nodeType":"Literal","messageId":"unexpected","endLine":3261,"endColumn":31},{"ruleId":"no-unused-vars","severity":2,"message":"'scnCurrentL1Dp' is assigned a value but never used.","line":3326,"column":17,"nodeType":"Identifier","messageId":"unusedVar","endLine":3326,"endColumn":31,"suggestions":[{"messageId":"removeVar","data":{"varName":"scnCurrentL1Dp"},"fix":{"range":[121344,121400],"text":""},"desc":"Remove unused variable 'scnCurrentL1Dp'."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'scnCurrentL2Dp' is assigned a value but never used.","line":3327,"column":17,"nodeType":"Identifier","messageId":"unusedVar","endLine":3327,"endColumn":31,"suggestions":[{"messageId":"removeVar","data":{"varName":"scnCurrentL2Dp"},"fix":{"range":[121411,121467],"text":""},"desc":"Remove unused variable 'scnCurrentL2Dp'."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'scnCurrentL3Dp' is assigned a value but never used.","line":3328,"column":17,"nodeType":"Identifier","messageId":"unusedVar","endLine":3328,"endColumn":31,"suggestions":[{"messageId":"removeVar","data":{"varName":"scnCurrentL3Dp"},"fix":{"range":[121478,121534],"text":""},"desc":"Remove unused variable 'scnCurrentL3Dp'."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'scnEnableDp' is assigned a value but never used.","line":3335,"column":17,"nodeType":"Identifier","messageId":"unusedVar","endLine":3335,"endColumn":28,"suggestions":[{"messageId":"removeVar","data":{"varName":"scnEnableDp"},"fix":{"range":[122019,122076],"text":""},"desc":"Remove unused variable 'scnEnableDp'."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'kebaSetPhaseSourceDp' is assigned a value but never used.","line":3936,"column":17,"nodeType":"Identifier","messageId":"unusedVar","endLine":3936,"endColumn":37,"suggestions":[{"messageId":"removeVar","data":{"varName":"kebaSetPhaseSourceDp"},"fix":{"range":[151741,151808],"text":""},"desc":"Remove unused variable 'kebaSetPhaseSourceDp'."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":6243,"column":72,"nodeType":"BlockStatement","messageId":"unexpected","endLine":6243,"endColumn":74,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[245443,245443],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":6937,"column":74,"nodeType":"BlockStatement","messageId":"unexpected","endLine":6937,"endColumn":76,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[278766,278766],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7163,"column":127,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7163,"endColumn":129,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[289293,289293],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7189,"column":126,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7189,"endColumn":128,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[290539,290539],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7385,"column":70,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7385,"endColumn":72,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[301250,301250],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7392,"column":69,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7392,"endColumn":71,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[301516,301516],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7396,"column":73,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7396,"endColumn":75,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[301683,301683],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7404,"column":48,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7404,"endColumn":50,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[302039,302039],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7411,"column":59,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7411,"endColumn":61,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[302242,302242],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7419,"column":60,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7419,"endColumn":62,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[302436,302436],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7423,"column":72,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7423,"endColumn":74,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[302592,302592],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7466,"column":74,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7466,"endColumn":76,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[304151,304151],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7469,"column":61,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7469,"endColumn":63,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[304269,304269],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'msg' is defined but never used. Allowed unused args must match /^_/u.","line":7522,"column":42,"nodeType":"Identifier","messageId":"unusedVar","endLine":7522,"endColumn":45,"suggestions":[{"messageId":"removeVar","data":{"varName":"msg"},"fix":{"range":[306773,306778],"text":""},"desc":"Remove unused variable 'msg'."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7528,"column":17,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7528,"endColumn":19,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[307016,307016],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7535,"column":17,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7535,"endColumn":19,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[307191,307191],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-unused-vars","severity":2,"message":"'dpId' is defined but never used. Allowed unused args must match /^_/u.","line":7564,"column":28,"nodeType":"Identifier","messageId":"unusedVar","endLine":7564,"endColumn":32,"suggestions":[{"messageId":"removeVar","data":{"varName":"dpId"},"fix":{"range":[308244,308248],"text":""},"desc":"Remove unused variable 'dpId'."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7621,"column":19,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7621,"endColumn":21,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[311397,311397],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7686,"column":70,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7686,"endColumn":72,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[313981,313981],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7687,"column":76,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7687,"endColumn":78,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[314059,314059],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7942,"column":55,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7942,"endColumn":57,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[325486,325486],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":7990,"column":23,"nodeType":"BlockStatement","messageId":"unexpected","endLine":7990,"endColumn":25,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[328233,328233],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":8619,"column":19,"nodeType":"BlockStatement","messageId":"unexpected","endLine":8619,"endColumn":21,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[353188,353188],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":8627,"column":56,"nodeType":"BlockStatement","messageId":"unexpected","endLine":8627,"endColumn":58,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[353442,353442],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":8783,"column":83,"nodeType":"BlockStatement","messageId":"unexpected","endLine":8783,"endColumn":85,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[359024,359024],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]},{"ruleId":"no-useless-catch","severity":2,"message":"Unnecessary try/catch wrapper.","line":9509,"column":7,"nodeType":"TryStatement","messageId":"unnecessaryCatch","endLine":9520,"endColumn":8},{"ruleId":"no-empty","severity":2,"message":"Empty block statement.","line":9531,"column":17,"nodeType":"BlockStatement","messageId":"unexpected","endLine":9531,"endColumn":19,"suggestions":[{"messageId":"suggestComment","data":{"type":"block"},"fix":{"range":[396112,396112],"text":" /* empty */ "},"desc":"Add comment inside empty block statement."}]}],"suppressedMessages":[],"errorCount":37,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"'use strict';\n\nconst path = require('path');\nconst { roundTo, normalizeValueByUnit } = require('./utils');\nconst {\n SCHEMA_VERSION: ALIAS_SCHEMA_VERSION,\n STANDARD_NAMESPACE: ALIAS_STANDARD_NAMESPACE,\n getDeviceClass: getAliasDeviceClass,\n canonicalAliasPath,\n legacyAliasPath,\n cloneStandardDefinition,\n buildStandardAliasDefinitions,\n buildManifest: buildAliasManifest,\n mergeStandardDefinition,\n} = require('./aliasContract');\nconst { ModbusDriver } = require('./drivers/modbus');\nconst { VartaModbusDriver } = require('./drivers/vartaModbus');\nconst { DeyeModbusDriver } = require('./drivers/deyeModbus');\nconst { getDeyeProfile, buildDeyeAliases } = require('./deyeProtocol');\nconst { getVartaProfile, registersForProfile, buildVartaAliases } = require('./vartaProtocol');\nconst { extendedRegistersForProfile, buildVartaExtendedAliases } = require('./vartaExtendedProtocol');\nconst { MqttDriver } = require('./drivers/mqtt');\nconst { CanbusDriver } = require('./drivers/canbus');\nconst { HttpDriver } = require('./drivers/http');\nconst { UdpDriver } = require('./drivers/udp');\nconst { SpeedwireDriver } = require('./drivers/speedwire');\nconst { OneWireDriver } = require('./drivers/onewire');\nconst { MbusDriver } = require('./drivers/mbus');\nconst { KostalTcpDriver } = require('./drivers/kostalTcp');\nconst { KostalRs485Driver } = require('./drivers/kostalRs485');\nconst { TaCmiDriver } = require('./drivers/taCmi');\nconst { isEnergyFreshnessClass, isEnergyFreshnessAlias, captureAliasSources, hasNewAliasSample } = require('./deviceAliasFreshness');\nconst { hasSameReadResponse } = require('./modbusReadEvidence');\n\nconst ABL_EMH1_LIVE_ALIAS_PATHS = new Set([\n 'r.currentL1',\n 'r.currentL2',\n 'r.currentL3',\n 'r.currentA',\n 'r.currentTotalA',\n 'r.currentPhaseSumA',\n 'r.power',\n 'r.powerEstimated',\n]);\n\n// Safety-relevant EV charger feedback must remain temporally fresh even when the\n// value itself does not change. Idle chargers commonly report 0 W / false for\n// hours. ioBroker otherwise keeps the old state timestamp because _setStateCached\n// suppresses identical writes, which can make an upstream load-management\n// failsafe classify a healthy charger as stale.\n//\n// EV charger feedback keeps its established refresh policy below. Operational\n// meter/storage/PV aliases use deviceAliasFreshness as well, with exact sampled\n// source evidence for polled, Speedwire and MQTT data. Static metadata, energy\n// counters and command aliases remain change-only to bound state/history traffic.\nconst EV_CHARGER_FRESHNESS_ALIAS_PATHS = new Set([\n 'comm.connected',\n 'alarm.offline',\n 'r.status',\n 'r.statusCode',\n 'r.statusText',\n 'r.available',\n 'r.vehicleConnected',\n 'r.charging',\n 'r.soc',\n 'r.power',\n 'r.powerEstimated',\n 'r.currentA',\n 'r.currentTotalA',\n 'r.currentPhaseSumA',\n 'r.currentL1',\n 'r.currentL2',\n 'r.currentL3',\n 'r.mode3Code',\n 'r.mode3State',\n 'r.evState',\n]);\n\nconst DEFAULT_EV_CHARGER_FRESHNESS_REFRESH_MS = 5000;\nconst MIN_EV_CHARGER_FRESHNESS_REFRESH_MS = 1000;\nconst MAX_EV_CHARGER_FRESHNESS_REFRESH_MS = 10000;\n\nclass DeviceRuntime {\n constructor(adapter, deviceConfig, template, globalConfig) {\n this.adapter = adapter;\n this.cfg = deviceConfig;\n this.template = template;\n this.global = globalConfig || {};\n\n this.baseId = `devices.${this.cfg.id}`;\n this.dpByStateRelId = new Map(); // relId -> dpDef\n this.dpById = new Map(); // dpId -> dpDef\n this.dynamicDatapoints = []; // runtime-discovered datapoints (e.g. TA CMI JSON API)\n\n // Alias states: stable datapoint names across different manufacturers/templates.\n // These are created under: devices.<id>.aliases.*\n this.aliasByStateRelId = new Map(); // relId -> aliasDef\n this.aliasDefs = []; // list of aliasDef\n // Mode-dependent device readbacks never use command acknowledgements or\n // cached mode objects as evidence. No additional polling or timer is needed.\n this._qualifiedAliasSamples = new Map();\n this._qualifiedAliasGeneration = 0;\n this._qualifiedAliasPendingWrites = new Set();\n this._qualifiedAliasMaxAgeMs = Math.max(1000,\n (Number(this.template?.driverHints?.polling?.slowIntervalMs) || 5000) + 10000);\n\n // Alias Contract v1: versioned, manufacturer-independent interface for the\n // NexoWatt UI and future integration adapters. Legacy aliases remain available.\n this.aliasDeviceClass = getAliasDeviceClass(this.template, this.cfg);\n this.aliasContractInfo = {\n schemaVersion: ALIAS_SCHEMA_VERSION,\n namespace: ALIAS_STANDARD_NAMESPACE,\n deviceClass: this.aliasDeviceClass,\n capabilities: [],\n missingRequired: [],\n };\n this._aliasMetadataRefreshTimer = null;\n\n this.driver = null;\n this.pollTimer = null;\n this._pollLoopActive = false;\n this._lifecycleGeneration = 0;\n /** @type {Promise<void> | null} */\n this._initialPollPromise = null;\n\n // Stop optional write loop and clear queued writes\n try {\n this._writeQueueEnabled = false;\n this._stopWriteLoop();\n if (this._writeQueue) this._writeQueue.clear();\n this._writeBusy = false;\n } catch (e) {\n // ignore\n }\n this.watchdogTimer = null;\n this.watchdogStartTimer = null;\n this._watchdogCounter = 0;\n this._watchdogBusy = false;\n this._connOk = false;\n\n // Optional Modbus setpoint keepalive: some devices (e.g. EV chargers) expose\n // control setpoints with a *valid time*. If the setpoint is not refreshed before\n // it expires, the device falls back to its safe/default value.\n // Enabled per template via: driverHints.modbus.setpointKeepalive\n this._setpointKeepaliveTimer = null;\n this._setpointKeepaliveBusy = false;\n this._setpointKeepaliveLastWriteByDpId = new Map();\n\n // Optional Sungrow External EMS/VPP heartbeat refresh. Sungrow treats the\n // heartbeat register as a timeout value in seconds, not as a changing counter.\n // Keep this separate from power-setpoint keepalive so a single EMS power DP\n // can trigger the full control block once while the adapter refreshes only\n // the lightweight heartbeat cyclically.\n this._sungrowHeartbeatTimer = null;\n this._sungrowHeartbeatStartTimer = null;\n this._sungrowHeartbeatBusy = false;\n this._setpointKeepaliveUnsupportedUntilByDpId = new Map();\n this._unsupportedWriteSkipLogTsByDpId = new Map();\n\n // Optional post-write confirmation repeat. Some chargers, especially Alfen ACE,\n // need a freshly changed EMS command to be sent again after the command stream\n // has been quiet for a few seconds.\n this._postWriteRepeatTimersByDpId = new Map();\n\n // Optional Modbus setpoint restore (on start/reconnect): some devices reset their control setpoints\n // after a reboot or communication outage (e.g. PV export limit goes back to 100%).\n // Enabled per template via: template.driverHints.modbus.restoreSetpointsOnStart\n this._restoreCfg = null;\n this._restoreDpIds = new Set();\n this._restoreFallback = new Map(); // dpId -> last known value (captured from dp state before first poll)\n this._restoreTimer = null;\n this._restoreBusy = false;\n\n // Persisted setpoint memory states live under: devices.<id>.info.setpoints.<dpId>\n this._setpointsInfoReady = false;\n\n\n // Track recent writes to datapoints. This enables safe watchdog behavior\n // where watchdog values are only refreshed while an external controller\n // is actively sending setpoints.\n this._lastWriteByDpId = new Map(); // dpId -> unix ms\n // Last values that were successfully commanded by this adapter. Readback registers on\n // some devices are not stable command mirrors (Alfen ACE socket control can expose the\n // accepted command at an alternate address and adjacent/read-only registers may otherwise\n // decode as 0 A / 1 phase). Keep command aliases and watchdog refreshes tied to the last\n // known successful command instead of volatile readback.\n this._lastCommandedValueByDpId = new Map(); // dpId -> last successfully written engineering value\n // ABL eMH1 uses 100 % PWM as the normal \"no current available\" command. Preserve\n // the last active 10..96 % value so ctrl.run/ctrl.chargeEnable can resume charging\n // without abusing the service-state register 0x0005.\n this._ablLastActiveDutyPctByDpId = new Map(); // write dpId -> last active PWM duty cycle\n\n // Fail-safe control flags for watchdog-managed \"VK\" interfaces (e.g. TESVOLT).\n this._autoWatchdogControlEverActive = false;\n this._autoWatchdogControlDisabled = false;\n // Error log throttling (avoid log spam on persistent comm errors)\n this._lastErrorLogMsg = '';\n this._lastErrorLogTs = 0;\n\n // Optional write throttling / coalescing (needed for devices that require >=1s between Modbus commands).\n // Enabled via template driverHints.modbus.writeThrottleMs.\n this._writeThrottleMs = 0;\n this._writeQueueMaxPerTick = 1;\n this._writeQueue = new Map(); // dpId -> { dp, deviceValue, ackByRelId, attempts, isPreWrite, preWriteTriggerDpId }\n this._lastSuccessfulQueuedValueByDpId = new Map();\n this._writeLoopActive = false;\n this._writeTimer = null;\n this._writeLoopBusy = false;\n\n // Pre-write throttling: remember when a preWrite sequence for a trigger datapoint was last executed.\n this._preWriteLastTsByTrigger = new Map();\n\n // Optional command cadence scheduler: on each cadence tick we perform either a poll (if due) or one queued write.\n // Enabled via template driverHints.modbus.commandCadenceMs (e.g. SolaX recommends >=1s between instructions).\n this._commandCadenceMs = 0;\n\n // --- Heartbeat / Liveness (safety-critical) ---\n // Always exposed via stable alias states:\n // devices.<id>.aliases.r.heartbeat (number counter)\n // devices.<id>.aliases.r.lastSeenMs (unix ms)\n // devices.<id>.aliases.r.online (boolean)\n // Updated ONLY on real incoming data:\n // - polling protocols: successful read cycle\n // - speedwire: only when a new telegram arrives (not when serving cached values)\n // - mqtt/canbus: incoming messages/frames\n this._hbCounter = 0;\n this._hbLastSeen = 0;\n this._hbOnline = false;\n this._hbTimeoutMs = 0;\n this._hbLastWriteAt = 0;\n this._hbCheckTimer = null;\n this._hbLastSourceStamp = 0;\n\n // Cache last adapter-written values per state. This avoids flooding ioBroker with\n // unchanged setState() calls on every poll cycle. Operational energy/EV\n // aliases can opt into a bounded periodic refresh so their ioBroker timestamp\n // proves that a new device snapshot was actually received.\n this._stateCache = new Map(); // relId -> { val, ack, writtenAt }\n this._liveAliasRefreshMs = 0;\n\n this.started = false;\n }\n\n getDatapoints() {\n const base = (this.template && Array.isArray(this.template.datapoints)) ? this.template.datapoints : [];\n if (!Array.isArray(this.dynamicDatapoints) || !this.dynamicDatapoints.length) return base;\n return base.concat(this.dynamicDatapoints);\n }\n\n relStateId(dp) {\n return `${this.baseId}.${dp.id}`;\n }\n\n async _ensureDatapointPathChannels(stateRelId) {\n const parts = String(stateRelId || '').split('.').filter(Boolean);\n if (parts.length < 2) return;\n\n // baseId itself is already a channel. Create every parent below it so nested\n // dynamic ids such as nodes.1.inputs.1.value are displayed cleanly in ioBroker.\n const baseParts = String(this.baseId).split('.');\n for (let i = baseParts.length; i < parts.length - 1; i++) {\n const rel = parts.slice(0, i + 1).join('.');\n const name = parts[i];\n await this.adapter.setObjectNotExistsAsync(rel, {\n type: 'channel',\n common: { name },\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n dynamicContainer: true,\n }\n });\n }\n }\n\n _datapointCommon(dp) {\n const common = {\n name: dp.name || dp.id,\n type: dp.type || 'number',\n role: dp.role || 'value',\n read: dp.rw !== 'wo',\n write: dp.rw === 'rw' || dp.rw === 'wo',\n };\n if (common.write && getVartaProfile(this.template)) common.write = this._vartaDatapointAllowsWrite(dp.id);\n if (dp.unit !== undefined && dp.unit !== null && dp.unit !== '') common.unit = dp.unit;\n if (dp.states && typeof dp.states === 'object') common.states = dp.states;\n if ((common.type || '').toString().toLowerCase() === 'number') {\n const dec = this._getRoundingDecimals(dp);\n if (typeof dec === 'number' && Number.isFinite(dec) && dec >= 0 && dec <= 10) common.decimals = dec;\n }\n return common;\n }\n\n async registerDynamicDatapoint(dp) {\n if (!dp || !dp.id) return null;\n const id = String(dp.id);\n const existing = this.dpById.get(id);\n const effective = existing || Object.assign({}, dp);\n if (existing) Object.assign(existing, dp);\n\n const relId = this.relStateId(effective);\n await this._ensureDatapointPathChannels(relId);\n const common = this._datapointCommon(effective);\n const src = effective.source || {};\n\n await this.adapter.setObjectNotExistsAsync(relId, {\n type: 'state',\n common,\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n datapointId: id,\n source: src,\n dynamic: true,\n }\n });\n await this.adapter.extendObjectAsync(relId, {\n common,\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n datapointId: id,\n source: src,\n dynamic: true,\n }\n }).catch(() => {});\n\n if (!existing) this.dynamicDatapoints.push(effective);\n this.dpById.set(id, effective);\n this.dpByStateRelId.set(relId, effective);\n return effective;\n }\n\n async initObjects() {\n await this.adapter.setObjectNotExistsAsync(this.baseId, {\n type: 'channel',\n common: { name: this.cfg.name || this.cfg.id },\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n category: this.cfg.category,\n manufacturer: this.cfg.manufacturer,\n aliasSchemaVersion: ALIAS_SCHEMA_VERSION,\n aliasNamespace: ALIAS_STANDARD_NAMESPACE,\n deviceClass: this.aliasDeviceClass,\n }\n });\n\n await this.adapter.setObjectNotExistsAsync(`${this.baseId}.info`, {\n type: 'channel',\n common: { name: 'Info' },\n native: {}\n });\n\n await this.adapter.setObjectNotExistsAsync(`${this.baseId}.info.connection`, {\n type: 'state',\n common: {\n name: 'Connection',\n type: 'boolean',\n role: 'indicator.connected',\n read: true,\n write: false,\n def: false\n },\n native: {}\n });\n\n await this.adapter.setObjectNotExistsAsync(`${this.baseId}.info.lastError`, {\n type: 'state',\n common: {\n name: 'Last error',\n type: 'string',\n role: 'text',\n read: true,\n write: false,\n def: ''\n },\n native: {}\n });\n\n if (this.template?.driverHints?.oemModbusV1003) {\n await this.adapter.setObjectNotExistsAsync(`${this.baseId}.info.depowerControl`, {\n type: 'state',\n common: { name: 'DEPower requested limit and Modbus readback', type: 'string', role: 'json', read: true, write: false, def: '{}' },\n native: {},\n });\n await this._setStateCached(`${this.baseId}.info.depowerControl`, JSON.stringify({ status: 'no_command', requestedW: null, readbackW: null }), true);\n }\n\n const dps = this.getDatapoints();\n for (const dp of dps) {\n const relId = this.relStateId(dp);\n\n const src = dp.source || {};\n const common = {\n name: dp.name || dp.id,\n type: dp.type || 'number',\n role: dp.role || 'value',\n read: dp.rw !== 'wo',\n write: dp.rw === 'rw' || dp.rw === 'wo',\n };\n if (common.write && getVartaProfile(this.template)) common.write = this._vartaDatapointAllowsWrite(dp.id);\n\n // Keep units consistent across protocols (important for alias normalization).\n if (dp.unit !== undefined && dp.unit !== null && dp.unit !== '') {\n common.unit = dp.unit;\n }\n\n // Provide deterministic display formatting in ioBroker front-ends.\n // (Value rounding is applied on every poll; this is the corresponding meta-data.)\n if ((common.type || '').toString().toLowerCase() === 'number') {\n const dec = this._getRoundingDecimals(dp);\n if (typeof dec === 'number' && Number.isFinite(dec) && dec >= 0 && dec <= 10) {\n common.decimals = dec;\n }\n }\n\n await this.adapter.setObjectNotExistsAsync(relId, {\n type: 'state',\n common,\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n datapointId: dp.id,\n source: src,\n }\n });\n\n // Keep object meta-data (e.g. unit/role) in sync when templates evolve.\n // This is important for consistent units (e.g. kW instead of W) without forcing users to delete objects.\n await this.adapter.extendObjectAsync(relId, {\n common,\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n datapointId: dp.id,\n source: src,\n }\n }).catch(() => {});\n\n this.dpByStateRelId.set(relId, dp);\n this.dpById.set(dp.id, dp);\n }\n\n // Create stable alias states (optional per template/category).\n try {\n await this._initAliasObjects();\n } catch (e) {\n // Alias creation must never break device start.\n this.adapter.log.debug(`[${this.cfg.id}] alias init failed: ${e && e.message ? e.message : e}`);\n }\n\n // Heartbeat alias states are always available for every device/template.\n // These are used by safety-critical higher-level logic (e.g. charge management fail-safe).\n try {\n await this._initHeartbeatAliasObjects();\n } catch (e) {\n this.adapter.log.debug(`[${this.cfg.id}] heartbeat alias init failed: ${e && e.message ? e.message : e}`);\n }\n\n try {\n await this._initAliasContractMetadata();\n } catch (e) {\n this.adapter.log.debug(`[${this.cfg.id}] alias contract metadata init failed: ${e && e.message ? e.message : e}`);\n }\n }\n\n _getDpByRole(role) {\n const dps = this.getDatapoints();\n for (const dp of dps) {\n if (!dp || !dp.role) continue;\n if (dp.role === role) return dp;\n }\n return null;\n }\n\n _getDpById(id) {\n if (!id) return null;\n return this.dpById.get(id) || null;\n }\n\n _findFirstDatapoint(predicate) {\n const dps = this.getDatapoints();\n for (const dp of dps) {\n if (!dp) continue;\n try {\n if (predicate(dp)) return dp;\n } catch (e) {\n // ignore\n }\n }\n return null;\n }\n _getRoundingDecimals(dp) {\n // VARTA already applies explicit per-register exponents. Preserve fractional\n // W/Wh values rather than rounding away an intentionally selected SF.\n if (getVartaProfile(this.template) || getDeyeProfile(this.template)) return null;\n // Preserve sub-10 Wh increments before the kWh -> Wh alias conversion.\n if (this.template?.driverHints?.oemModbusV1003 && dp?.source?.depowerEnergyCounter) return 4;\n // Adapter-wide rounding policy to keep state values readable and to avoid\n // Modbus/MQTT floating point artefacts (e.g. 0.30000000004).\n //\n // Rules:\n // - SoC (battery/storage): 1 decimal\n // - SoC (EV connector): 0 decimals\n // - Power: kW/kVA/kvar -> 2 decimals, W/VA/var -> 0 decimals\n // - Energy: kWh -> 2 decimals, Wh -> 0 decimals\n // - Everything else numeric: 2 decimals (default), except status-like unitless values -> 0\n\n if (!dp) return null;\n\n const unit = (dp.unit ?? '').toString().trim();\n const unitLower = unit.toLowerCase();\n const roleLower = (dp.role ?? '').toString().toLowerCase();\n\n const id = (dp.id ?? '').toString();\n const name = (dp.name ?? '').toString();\n\n // --- SoC ---\n const looksLikeSoc =\n /(^|[^a-z0-9])soc([^a-z0-9]|$)/i.test(id) ||\n /(^|[^a-z0-9])soc([^a-z0-9]|$)/i.test(name) ||\n roleLower === 'value.battery';\n\n const looksLikeEvConnectorSoc =\n /^c\\d+_soc$/i.test(id) ||\n /connector\\s*\\d*\\s*soc/i.test(name) ||\n /ev\\s*connector/i.test(name);\n\n if (looksLikeSoc) {\n if (looksLikeEvConnectorSoc) return 0;\n return 1;\n }\n\n // --- Power ---\n const looksLikePower =\n roleLower.includes('power') ||\n ['w', 'kw', 'va', 'kva', 'var', 'kvar'].includes(unitLower);\n\n if (looksLikePower) {\n if (['w', 'va', 'var'].includes(unitLower)) return 0;\n if (['kw', 'kva', 'kvar'].includes(unitLower)) return 2;\n return 2;\n }\n\n // --- Energy ---\n const looksLikeEnergy =\n roleLower.includes('energy') ||\n ['wh', 'kwh'].includes(unitLower);\n\n if (looksLikeEnergy) {\n if (unitLower === 'wh') return 0;\n if (unitLower === 'kwh') return 2;\n return 2;\n }\n\n // --- Status / enums (unitless) ---\n const looksLikeStatus =\n roleLower.startsWith('indicator.') ||\n roleLower.includes('status') ||\n /status|state|mode|code|fault|error/i.test(id) ||\n /status|state|mode|code|fault|error/i.test(name);\n\n if (looksLikeStatus && !unitLower) return 0;\n\n // Default: 2 decimals for all other numeric values.\n return 2;\n }\n\n _aliasRelId(aliasPath) {\n // Always place aliases under: devices.<id>.aliases.<...>\n return `${this.baseId}.aliases.${aliasPath}`;\n }\n\n _standardAliasRelId(aliasPath) {\n return this._aliasRelId(`${ALIAS_STANDARD_NAMESPACE}.${aliasPath}`);\n }\n\n // --- Heartbeat alias helpers ---\n _hbRelId(name) {\n return this._aliasRelId(`r.${name}`);\n }\n\n _hbRelIds(name) {\n return [\n this._hbRelId(name),\n this._standardAliasRelId(`r.${name}`),\n ];\n }\n\n _normalizeMs(v) {\n const n = Number(v);\n return (Number.isFinite(n) && n > 0) ? Math.trunc(n) : 0;\n }\n\n _parseNumberWithUnits(v) {\n if (v === null || v === undefined) return undefined;\n if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;\n if (typeof v === 'boolean') return v ? 1 : 0;\n if (typeof v === 'string') {\n const s = v.trim().replace(',', '.');\n if (!s) return undefined;\n const direct = Number(s);\n if (Number.isFinite(direct)) return direct;\n // Accept user/front-end strings such as \"6 A\", \"3 phases\", \"4.2 kW\".\n const m = s.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (!m) return undefined;\n const n = Number(m[0]);\n return Number.isFinite(n) ? n : undefined;\n }\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n }\n\n _sameStateValue(a, b) {\n if (a === b) return true;\n if (typeof a === 'number' && typeof b === 'number' && Number.isNaN(a) && Number.isNaN(b)) return true;\n return false;\n }\n\n _stateTypeHintForRelId(relId) {\n const key = String(relId || '');\n try {\n const aliasDef = this.aliasByStateRelId && this.aliasByStateRelId.get(key);\n if (aliasDef && aliasDef.type) return String(aliasDef.type).toLowerCase();\n } catch (_) {}\n try {\n const dp = this.dpByStateRelId && this.dpByStateRelId.get(key);\n if (dp && dp.type) return String(dp.type).toLowerCase();\n } catch (_) {}\n\n // Built-in adapter states that are not part of the template maps yet.\n if (/\\.(online|connection|connected|offline)$/i.test(key)) return 'boolean';\n if (/\\.(lastError|statusText|mode3State|mode3Code)$/i.test(key)) return 'string';\n if (/\\.(heartbeat|lastSeenMs)$/i.test(key)) return 'number';\n return '';\n }\n\n _coerceStateValueForRelId(relId, val) {\n const type = this._stateTypeHintForRelId(relId);\n if (!type || val === null || val === undefined) return val;\n\n if (type === 'boolean') {\n if (typeof val === 'boolean') return val;\n if (typeof val === 'number') {\n if (Number.isNaN(val)) return null;\n return val !== 0;\n }\n if (typeof val === 'string') {\n const s = val.trim().toLowerCase();\n if (!s) return false;\n if (['true', '1', 'on', 'yes', 'y', 'ja', 'an'].includes(s)) return true;\n if (['false', '0', 'off', 'no', 'n', 'nein', 'aus'].includes(s)) return false;\n }\n return !!val;\n }\n\n if (type === 'number') {\n if (typeof val === 'number') return Number.isNaN(val) ? null : val;\n if (typeof val === 'boolean') return val ? 1 : 0;\n if (typeof val === 'string') {\n const n = this._parseNumberWithUnits(val);\n return Number.isFinite(n) ? n : null;\n }\n const n = this._parseNumberWithUnits(val);\n return Number.isFinite(n) ? n : null;\n }\n\n if (type === 'string') {\n return (val === null || val === undefined) ? '' : String(val);\n }\n\n return val;\n }\n\n async _setStateCached(relId, val, ack = true, options = undefined) {\n if (!relId) return false;\n const key = String(relId);\n const nextAck = !!ack;\n const nextVal = this._coerceStateValueForRelId(key, val);\n const prev = this._stateCache.get(key);\n const now = Date.now();\n const refreshAfterRaw = Number(options && options.refreshAfterMs);\n const refreshAfterMs = Number.isFinite(refreshAfterRaw) && refreshAfterRaw > 0\n ? Math.max(1, Math.floor(refreshAfterRaw))\n : 0;\n const unchanged = !!(prev && prev.ack === nextAck && this._sameStateValue(prev.val, nextVal));\n\n if (unchanged) {\n const writtenAt = Number(prev.writtenAt) || 0;\n const refreshDue = refreshAfterMs > 0 && (writtenAt <= 0 || (now - writtenAt) >= refreshAfterMs);\n if (!refreshDue) return false;\n }\n\n try {\n await this.adapter.setStateAsync(key, { val: nextVal, ack: nextAck });\n this._stateCache.set(key, { val: nextVal, ack: nextAck, writtenAt: now });\n return true;\n } catch (_) {\n return false;\n }\n }\n\n _computeLiveAliasRefreshMs({ fastIntervalMs, isEventDriven } = {}) {\n if (this.aliasDeviceClass !== 'evCharger' && !isEnergyFreshnessClass(this.aliasDeviceClass)) return 0;\n\n const candidates = [\n this.cfg && this.cfg.liveStatusRefreshMs,\n this.cfg && this.cfg.liveAliasRefreshMs,\n this.cfg && this.cfg.connection && this.cfg.connection.liveStatusRefreshMs,\n this.template && this.template.driverHints && this.template.driverHints.liveStatusRefreshMs,\n this.template && this.template.driverHints && this.template.driverHints.liveAliasRefreshMs,\n ];\n let requested = 0;\n for (const candidate of candidates) {\n const value = Number(candidate);\n if (Number.isFinite(value) && value > 0) {\n requested = value;\n break;\n }\n }\n\n if (!(requested > 0)) {\n const poll = Number(fastIntervalMs);\n if (Number.isFinite(poll) && poll > 0) {\n requested = poll;\n } else if (isEventDriven) {\n requested = DEFAULT_EV_CHARGER_FRESHNESS_REFRESH_MS;\n } else {\n requested = DEFAULT_EV_CHARGER_FRESHNESS_REFRESH_MS;\n }\n }\n\n return Math.max(\n MIN_EV_CHARGER_FRESHNESS_REFRESH_MS,\n Math.min(MAX_EV_CHARGER_FRESHNESS_REFRESH_MS, Math.floor(requested)),\n );\n }\n\n _isEvChargerFreshnessAlias(relId) {\n if (this.aliasDeviceClass !== 'evCharger') return false;\n const path = legacyAliasPath(relId);\n return !!path && EV_CHARGER_FRESHNESS_ALIAS_PATHS.has(path);\n }\n\n _liveAliasRefreshOptions(relId, values, ctx, sourceIds = []) {\n if (!(this._liveAliasRefreshMs > 0)) return undefined;\n const energyAlias = isEnergyFreshnessAlias(this.aliasDeviceClass, legacyAliasPath(relId));\n if (!this._isEvChargerFreshnessAlias(relId) && !energyAlias) return undefined;\n if (ctx && (ctx.connected === false || ctx.diagnosticsOnly === true)) return undefined;\n if (!values || typeof values !== 'object' || Object.keys(values).length === 0) return undefined;\n if (energyAlias) {\n const path = legacyAliasPath(relId);\n const connectionAlias = path === 'comm.connected' || path === 'alarm.offline';\n if (!hasNewAliasSample({\n protocol: String(this.cfg.protocol || '').toLowerCase(),\n sourceIds: connectionAlias ? Object.keys(values) : sourceIds,\n values,\n lastWriteMs: Number(this._stateCache.get(String(relId))?.writtenAt) || 0,\n sampleTimestamp: Number(this.driver?.lastSeen),\n sourceTimestamps: this.driver?.updatedAtByDpId,\n })) return undefined;\n }\n return { refreshAfterMs: this._liveAliasRefreshMs };\n }\n\n async _initHeartbeatAliasObjects() {\n // Legacy heartbeat objects are intentionally kept byte-for-byte compatible\n // with releases before Alias Contract v1. Existing installations therefore\n // keep the same IDs, types, roles and native metadata.\n await this._ensureAliasPathChannels(this._hbRelId('heartbeat'));\n\n const legacyDefs = [\n {\n relId: this._hbRelId('heartbeat'),\n name: 'Heartbeat counter',\n role: 'value',\n type: 'number',\n def: 0,\n },\n {\n relId: this._hbRelId('lastSeenMs'),\n name: 'Last seen (unix ms)',\n role: 'value.time',\n type: 'number',\n def: 0,\n },\n {\n relId: this._hbRelId('online'),\n name: 'Online (heartbeat)',\n role: 'indicator.connected',\n type: 'boolean',\n def: false,\n },\n ];\n\n for (const def of legacyDefs) {\n const common = {\n name: def.name,\n type: def.type,\n role: def.role,\n read: true,\n write: false,\n def: def.def,\n };\n const native = {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAlias: true,\n aliasKind: 'heartbeat',\n };\n\n await this.adapter.setObjectNotExistsAsync(def.relId, {\n type: 'state',\n common,\n native,\n });\n await this.adapter.extendObjectAsync(def.relId, {\n common,\n native,\n }).catch(() => {});\n }\n\n // Alias Contract v1 is additive and lives only below aliases.v1.*.\n const standardDefs = [\n { name: 'heartbeat', displayName: 'Heartbeat counter', role: 'value', type: 'number', def: 0 },\n { name: 'lastSeenMs', displayName: 'Last seen (unix ms)', role: 'value.time', type: 'number', unit: 'ms', def: 0 },\n { name: 'online', displayName: 'Online (heartbeat)', role: 'indicator.connected', type: 'boolean', def: false },\n ];\n\n for (const def of standardDefs) {\n const relId = this._standardAliasRelId(`r.${def.name}`);\n await this._ensureAliasPathChannels(relId);\n const common = {\n name: def.displayName,\n type: def.type,\n role: def.role,\n read: true,\n write: false,\n def: def.def,\n };\n if (def.unit) common.unit = def.unit;\n const native = {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAlias: true,\n aliasKind: 'heartbeat',\n aliasContractVersion: ALIAS_SCHEMA_VERSION,\n aliasContractPath: `r.${def.name}`,\n capability: `read.${def.name}`,\n deviceClass: this.aliasDeviceClass,\n };\n await this.adapter.setObjectNotExistsAsync(relId, { type: 'state', common, native });\n await this.adapter.extendObjectAsync(relId, { common, native }).catch(() => {});\n }\n }\n\n _computeHeartbeatTimeoutMs({ fastIntervalMs, isEventDriven } = {}) {\n // Priority:\n // 1) per-device override: cfg.heartbeatTimeoutMs\n // 2) template hint: driverHints.heartbeatTimeoutMs\n // 3) protocol-derived default\n const cfgMs = this._normalizeMs(this.cfg?.heartbeatTimeoutMs);\n if (cfgMs > 0) return cfgMs;\n\n const tplMs = this._normalizeMs(this.template?.driverHints?.heartbeatTimeoutMs);\n if (tplMs > 0) return tplMs;\n\n const proto = String(this.cfg?.protocol || '').toLowerCase();\n const isSpeedwire = proto === 'speedwire';\n\n if (isEventDriven || proto === 'mqtt' || proto === 'canbus') {\n return 30000;\n }\n\n if (isSpeedwire) {\n const stale = this._normalizeMs(this.cfg?.connection?.staleTimeoutMs) || 30000;\n return Math.max(stale, 30000);\n }\n\n const poll = this._normalizeMs(fastIntervalMs);\n if (poll > 0) return Math.max(3 * poll, 15000);\n return 30000;\n }\n\n async _loadHeartbeatStateFromDb() {\n // Best-effort: keep heartbeat counter monotonic across adapter restarts.\n try {\n const [hb, lastSeen] = await Promise.all([\n this.adapter.getStateAsync(this._hbRelId('heartbeat')).catch(() => null),\n this.adapter.getStateAsync(this._hbRelId('lastSeenMs')).catch(() => null),\n ]);\n\n const hbVal = hb && hb.val !== undefined ? Number(hb.val) : 0;\n if (Number.isFinite(hbVal) && hbVal >= 0) this._hbCounter = Math.trunc(hbVal);\n\n const lsVal = lastSeen && lastSeen.val !== undefined ? Number(lastSeen.val) : 0;\n if (Number.isFinite(lsVal) && lsVal > 0) this._hbLastSeen = Math.trunc(lsVal);\n } catch (_) {\n // ignore\n }\n }\n\n _isAblEmh1EvccTemplate() {\n return String(this.template?.id || this.cfg?.templateId || '').toLowerCase() ===\n 'evcs.abl.emh1.evcc2_3.modbusascii';\n }\n\n _isAblEmh1LiveMeasurementAlias(relId) {\n if (!this._isAblEmh1EvccTemplate()) return false;\n const text = String(relId || '');\n const marker = '.aliases.';\n const index = text.indexOf(marker);\n if (index < 0) return false;\n let path = text.slice(index + marker.length);\n if (path.startsWith(`${ALIAS_STANDARD_NAMESPACE}.`)) {\n path = path.slice(ALIAS_STANDARD_NAMESPACE.length + 1);\n }\n return ABL_EMH1_LIVE_ALIAS_PATHS.has(path);\n }\n\n _shouldResetAblEmh1LiveMeasurements(values, ctx) {\n if (!this._isAblEmh1EvccTemplate()) return false;\n if (ctx && ctx.connected === false) return true;\n\n const snapshot = (values && typeof values === 'object') ? values : {};\n const currentIds = ['cURRENT_L1', 'cURRENT_L2', 'cURRENT_L3'];\n const hasCurrentField = currentIds.some(id => Object.prototype.hasOwnProperty.call(snapshot, id));\n\n // The EVCC2/3 full-current response uses state A/B/E/F for non-charging operation.\n // C2, C3 and C4 are the only states in which a positive charging-current/power\n // value is valid. This also clears a previous current immediately when the vehicle\n // disconnects and the phase-current registers change to the documented null sentinel.\n if (Object.prototype.hasOwnProperty.call(snapshot, 'eVSE_STATE')) {\n const rawState = Number(snapshot.eVSE_STATE);\n if (Number.isFinite(rawState)) {\n const stateCode = Math.trunc(rawState) & 0xFF;\n if (![0xC2, 0xC3, 0xC4].includes(stateCode)) return true;\n }\n }\n\n // A successful poll without the atomic R5 current group, or a group containing only\n // null/NaN values, must fail safe to zero instead of preserving the previous load.\n if (!hasCurrentField) return true;\n const hasFiniteCurrent = currentIds.some(id => {\n if (!Object.prototype.hasOwnProperty.call(snapshot, id)) return false;\n const raw = snapshot[id];\n if (raw === null || raw === undefined || raw === '') return false;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0;\n });\n return !hasFiniteCurrent;\n }\n\n async _resetAblEmh1LiveMeasurements() {\n if (!this._isAblEmh1EvccTemplate() || !Array.isArray(this.aliasDefs)) return;\n for (const def of this.aliasDefs) {\n if (!def || !this._isAblEmh1LiveMeasurementAlias(def.relId)) continue;\n await this._setStateCached(def.relId, 0, true);\n }\n }\n\n async _setHeartbeatOnline(nextOnline, offlineReason) {\n const b = !!nextOnline;\n if (!b) await this._resetAblEmh1LiveMeasurements();\n\n // MQTT devices are push-driven. When their heartbeat expires, let the driver\n // actively clear template-declared live power values before updating aliases.\n // This prevents a stale storage/charger power from remaining visible forever.\n if (!b && String(this.cfg?.protocol || '').toLowerCase() === 'mqtt' && this.driver && typeof this.driver.handleOffline === 'function') {\n await this.driver.handleOffline(String(offlineReason || 'MQTT heartbeat timeout')).catch(() => {});\n }\n\n if (String(this.cfg?.protocol || '').toLowerCase() === 'mqtt') {\n await this._setStateCached(`${this.baseId}.info.connection`, b, true);\n }\n\n if (b === this._hbOnline) return;\n this._hbOnline = b;\n for (const relId of this._hbRelIds('online')) {\n await this._setStateCached(relId, b, true);\n }\n }\n\n async _tickHeartbeatFromIncomingData(sourceStamp) {\n // sourceStamp: optional monotonic marker that only changes when *new* data arrived\n // (e.g., Speedwire lastSeen timestamp). If provided, we only tick when it changes.\n if (!this.started) return;\n const now = Date.now();\n\n if (sourceStamp !== undefined && sourceStamp !== null) {\n const s = Number(sourceStamp) || 0;\n if (s <= 0) return;\n if (s === this._hbLastSourceStamp) {\n // No fresh data since last tick (e.g. Speedwire soft-stale serving cached values)\n this._hbLastSeen = Math.max(this._hbLastSeen, s);\n return;\n }\n this._hbLastSourceStamp = s;\n this._hbLastSeen = s;\n } else {\n this._hbLastSeen = now;\n }\n\n // Flip online immediately when we see the device alive\n if (!this._hbOnline) {\n await this._setHeartbeatOnline(true);\n }\n\n // Throttle writes to max 1 Hz per device\n if (this._hbLastWriteAt && (now - this._hbLastWriteAt) < 1000) return;\n this._hbLastWriteAt = now;\n\n this._hbCounter = (Number.isFinite(this._hbCounter) ? this._hbCounter : 0) + 1;\n if (this._hbCounter > 2147480000) this._hbCounter = 1;\n\n for (const relId of this._hbRelIds('heartbeat')) {\n await this._setStateCached(relId, this._hbCounter, true);\n }\n for (const relId of this._hbRelIds('lastSeenMs')) {\n await this._setStateCached(relId, this._hbLastSeen || now, true);\n }\n\n // Keep the online state timestamp fresh for live energy/EV devices as an additional\n // liveness signal. This is still tied to real incoming data; no timer fabricates\n // freshness while communication is down.\n if (this._liveAliasRefreshMs > 0) {\n for (const relId of this._hbRelIds('online')) {\n await this._setStateCached(relId, true, true, { refreshAfterMs: this._liveAliasRefreshMs });\n }\n }\n }\n\n _startHeartbeatChecker() {\n if (this._hbCheckTimer) {\n try { clearInterval(this._hbCheckTimer); } catch (_) {}\n this._hbCheckTimer = null;\n }\n\n if (!this._hbTimeoutMs || this._hbTimeoutMs <= 0) return;\n\n this._hbCheckTimer = setInterval(() => {\n try {\n if (!this.started) return;\n const now = Date.now();\n const last = Number(this._hbLastSeen) || 0;\n const age = last > 0 ? (now - last) : Number.POSITIVE_INFINITY;\n const nextOnline = (last > 0) && (age <= this._hbTimeoutMs);\n if (nextOnline !== this._hbOnline) {\n this._setHeartbeatOnline(nextOnline).catch(() => {});\n }\n } catch (_) {\n // ignore\n }\n }, 1000);\n }\n\n async _ensureChannel(relId, name) {\n await this.adapter.setObjectNotExistsAsync(relId, {\n type: 'channel',\n common: { name: name || relId.split('.').slice(-1)[0] },\n native: {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAliasContainer: true,\n }\n });\n }\n\n async _ensureAliasPathChannels(stateRelId) {\n // Example: devices.<id>.aliases.ctrl.powerLimitPct\n // Create channels for: devices.<id>.aliases and devices.<id>.aliases.ctrl\n const parts = String(stateRelId).split('.');\n // Find index of \"aliases\" in the path\n const idx = parts.indexOf('aliases');\n if (idx < 0) return;\n\n const channels = [];\n // Build incremental channel ids up to the parent of the state\n for (let i = 0; i < parts.length - 1; i++) {\n const p = parts[i];\n if (p === '') continue;\n const rel = parts.slice(0, i + 1).join('.');\n if (i >= idx) channels.push(rel);\n }\n\n // Ensure base aliases channel has a friendly name\n for (const ch of channels) {\n const chName = ch.endsWith('.aliases') ? 'Aliases' : ch.split('.').slice(-1)[0];\n await this._ensureChannel(ch, chName);\n }\n }\n\n _buildAliasDefinitions() {\n const defs = [];\n // Canonical-only source definitions are converted into aliases.v1.* but are\n // deliberately not published below the legacy aliases.* namespace.\n const standardOnlyDefs = [];\n const relIds = new Set();\n const add = (def) => {\n if (!def || !def.relId) return;\n if (relIds.has(def.relId)) {\n // Most generic aliases are added early. A few manufacturer-specific integrations\n // need to replace a generic alias with a safer computed one (for example Alfen\n // meter-only installations where the socket status/control register block is not exposed).\n if (def.replace === true) {\n const idx = defs.findIndex(x => x && x.relId === def.relId);\n if (idx >= 0) defs[idx] = def;\n }\n return;\n }\n relIds.add(def.relId);\n defs.push(def);\n };\n const addStandardSource = (def) => {\n if (!def || !def.relId) return;\n standardOnlyDefs.push(def);\n };\n\n const cat = (this.template && this.template.category) ? String(this.template.category) : '';\n const chargerCats = new Set(['EVCS', 'EVSE', 'CHARGER', 'DC_CHARGER']);\n\n const findByIdRe = (re) => this._findFirstDatapoint(dp => re.test(String(dp && dp.id ? dp.id : '')));\n const findByIdOrNameRe = (re) => this._findFirstDatapoint(dp =>\n re.test(String(dp && dp.id ? dp.id : '')) || re.test(String(dp && dp.name ? dp.name : ''))\n );\n\n const getAnyById = (...ids) => {\n for (const id of ids) {\n const dp = this._getDpById(id);\n if (dp) return dp;\n }\n return null;\n };\n\n const findById = (id) => this._getDpById(id);\n\n // --- Always available (communication) ---\n add({\n relId: this._aliasRelId('comm.connected'),\n name: 'Device communication connected',\n role: 'indicator.connected',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (_values, ctx) => !!(ctx && ctx.connected),\n });\n\n add({\n relId: this._aliasRelId('comm.lastError'),\n name: 'Device communication last error',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (_values, ctx) => (ctx && typeof ctx.lastError === 'string') ? ctx.lastError : '',\n });\n\n add({\n relId: this._aliasRelId('alarm.offline'),\n name: 'Device offline',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (_values, ctx) => !(ctx && ctx.connected),\n });\n\n // --- Generic role-based aliases (best-effort) ---\n // Only use these for categories where roles are typically reliable and where \"first match wins\" is acceptable.\n // For meters, chargers, batteries and ESS we create dedicated alias mapping further below.\n const allowGenericRoleAliases = !chargerCats.has(cat) && !['METER', 'BATTERY', 'ESS', 'BATTERY_INVERTER'].includes(cat);\n\n if (allowGenericRoleAliases) {\n const powerDp = getAnyById('W') || this._findFirstDatapoint(dp => dp.role === 'value.power' && dp.rw !== 'wo');\n if (powerDp) {\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Active power',\n role: 'value.power',\n type: 'number',\n unit: powerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: powerDp.id,\n });\n }\n\n const energyDp = getAnyById('WH', 'TotWhOut') || this._findFirstDatapoint(dp => dp.role === 'value.energy' && dp.rw !== 'wo');\n if (energyDp) {\n add({\n relId: this._aliasRelId('r.energyTotal'),\n name: 'Total energy',\n role: 'value.energy',\n type: 'number',\n unit: energyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: energyDp.id,\n });\n }\n\n const statusDp = getAnyById('Health', 'St') || this._findFirstDatapoint(dp => dp.role === 'indicator.status' && dp.rw !== 'wo');\n if (statusDp) {\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: statusDp.id,\n });\n }\n }\n\n\n\n // --- HEAT aliases (heat pumps / heating systems) ---\n // Provide a stable API for heat pumps so that higher-level control adapters can link\n // against consistent alias names even if manufacturers label datapoints differently.\n if (cat === 'HEAT') {\n const asNumber = (v) => {\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string') {\n const s = v.trim();\n if (s !== '' && !Number.isNaN(Number(s))) return Number(s);\n }\n return undefined;\n };\n\n // Temperatures (best effort)\n const ambientTempDp = getAnyById(\n 'ambient.actualAmbientTemp',\n 'ambient.calculatedAmbientTemp',\n 'ambient.avgAmbientTemp1h'\n ) || findByIdOrNameRe(/ambient.*temp|outside.*temp|outdoor.*temp|au[ßs]en.*temp/i);\n\n if (ambientTempDp) {\n add({\n relId: this._aliasRelId('r.ambientTemp'),\n name: 'Ambient temperature',\n role: 'value.temperature',\n type: 'number',\n unit: ambientTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: ambientTempDp.id,\n });\n }\n\n const flowTempDp = getAnyById(\n 'hc.flowTemp',\n 'hp.sinkLineTemp',\n 'buffer.tempHigh'\n ) || findByIdOrNameRe(/flow.*temp|vorlauf.*temp|supply.*temp/i);\n\n if (flowTempDp) {\n add({\n relId: this._aliasRelId('r.flowTemp'),\n name: 'Flow / supply temperature',\n role: 'value.temperature',\n type: 'number',\n unit: flowTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: flowTempDp.id,\n });\n }\n\n const returnTempDp = getAnyById(\n 'hc.returnTemp',\n 'hp.sinkReturnLineTemp',\n 'buffer.tempLow'\n ) || findByIdOrNameRe(/return.*temp|ruecklauf.*temp|rücklauf.*temp/i);\n\n if (returnTempDp) {\n add({\n relId: this._aliasRelId('r.returnTemp'),\n name: 'Return temperature',\n role: 'value.temperature',\n type: 'number',\n unit: returnTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: returnTempDp.id,\n });\n }\n\n const roomTempDp = getAnyById('hc.roomTemp') || findByIdOrNameRe(/room.*temp|raum.*temp/i);\n if (roomTempDp) {\n add({\n relId: this._aliasRelId('r.roomTemp'),\n name: 'Room temperature',\n role: 'value.temperature',\n type: 'number',\n unit: roomTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: roomTempDp.id,\n });\n }\n\n const bufferTempDp = getAnyById(\n 'buffer.tempHigh',\n 'buffer.tempMedium',\n 'buffer.tempLow'\n ) || findByIdOrNameRe(/buffer.*temp|puffer.*temp/i);\n\n if (bufferTempDp) {\n add({\n relId: this._aliasRelId('r.bufferTemp'),\n name: 'Buffer temperature',\n role: 'value.temperature',\n type: 'number',\n unit: bufferTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: bufferTempDp.id,\n });\n }\n\n // Controls (best effort)\n const operatingModeDp = getAnyById('hc.operatingMode') || this._findFirstDatapoint(dp =>\n /operatingMode|betriebsmodus/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (operatingModeDp) {\n add({\n relId: this._aliasRelId('ctrl.operatingMode'),\n name: 'Set operating mode',\n role: 'level',\n type: 'number',\n rw: 'rw',\n kind: 'dp',\n dpId: operatingModeDp.id,\n writeDpId: operatingModeDp.id,\n });\n }\n\n const flowSetpointDp = getAnyById(\n 'hc.setFlowTempRequest',\n 'hp.requestFlowLineTemp',\n 'buffer.requestFlowLineTemp'\n ) || this._findFirstDatapoint(dp =>\n /setFlow|flow.*request|vorlauf.*request/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (flowSetpointDp) {\n add({\n relId: this._aliasRelId('ctrl.flowSetpoint'),\n name: 'Set flow/supply setpoint',\n role: 'level.temperature',\n type: 'number',\n unit: flowSetpointDp.unit || '°C',\n rw: 'rw',\n kind: 'dp',\n dpId: flowSetpointDp.id,\n writeDpId: flowSetpointDp.id,\n });\n }\n\n const roomHeatSpDp = getAnyById('hc.roomSetpointHeating') || this._findFirstDatapoint(dp =>\n /roomSetpointHeating|raum.*heizen/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (roomHeatSpDp) {\n add({\n relId: this._aliasRelId('ctrl.roomSetpointHeating'),\n name: 'Set room setpoint (heating)',\n role: 'level.temperature',\n type: 'number',\n unit: roomHeatSpDp.unit || '°C',\n rw: 'rw',\n kind: 'dp',\n dpId: roomHeatSpDp.id,\n writeDpId: roomHeatSpDp.id,\n });\n }\n\n const roomCoolSpDp = getAnyById('hc.roomSetpointCooling') || this._findFirstDatapoint(dp =>\n /roomSetpointCooling|raum.*kuehlen|raum.*kühlen/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (roomCoolSpDp) {\n add({\n relId: this._aliasRelId('ctrl.roomSetpointCooling'),\n name: 'Set room setpoint (cooling)',\n role: 'level.temperature',\n type: 'number',\n unit: roomCoolSpDp.unit || '°C',\n rw: 'rw',\n kind: 'dp',\n dpId: roomCoolSpDp.id,\n writeDpId: roomCoolSpDp.id,\n });\n }\n\n const heatingCapacityDp = getAnyById('buffer.requestHeatingCapacity') || this._findFirstDatapoint(dp =>\n /heatingCapacity|heizleistung/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (heatingCapacityDp) {\n add({\n relId: this._aliasRelId('ctrl.requestHeatingCapacity'),\n name: 'Set requested heating capacity',\n role: 'level.power',\n type: 'number',\n unit: heatingCapacityDp.unit || 'kW',\n rw: 'rw',\n kind: 'dp',\n dpId: heatingCapacityDp.id,\n writeDpId: heatingCapacityDp.id,\n });\n }\n\n // Optional: feed an external power signal into the heat pump's energy manager module\n const externalPowerDp = getAnyById('emanager.actualPowerInputOrExcess') || this._findFirstDatapoint(dp =>\n /inputOrExcess|excess/i.test(String(dp && dp.id ? dp.id : '')) && (dp.rw === 'rw' || dp.rw === 'wo')\n );\n\n if (externalPowerDp) {\n add({\n relId: this._aliasRelId('ctrl.externalPower'),\n name: 'Set external power signal (input/excess)',\n role: 'level.power',\n type: 'number',\n unit: externalPowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: externalPowerDp.id,\n writeDpId: externalPowerDp.id,\n });\n }\n\n // Fault alarm: best-effort based on any error number/state datapoints\n const errorDps = this.getDatapoints().filter(dp => dp && dp.id && /error(Number|State)$/i.test(String(dp.id)) && dp.rw !== 'wo');\n if (errorDps.length) {\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Device fault',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n for (const dp of errorDps) {\n const v = values[dp.id];\n const n = asNumber(v);\n if (n === undefined) continue;\n if (/errorState$/i.test(String(dp.id))) {\n if (n >= 4) return true;\n } else if (n !== 0) {\n return true;\n }\n }\n return false;\n },\n });\n }\n }\n // --- IO aliases (digital inputs/outputs/counters) ---\n // Provide a stable API for I/O components so that other adapters can link against\n // consistent alias names even if manufacturers label channels differently.\n //\n // Aliases created:\n // - devices.<id>.aliases.r.inputs.in0..inN\n // - devices.<id>.aliases.r.outputs.out0..outN\n // - devices.<id>.aliases.ctrl.outputs.out0..outN (write)\n // - devices.<id>.aliases.r.counters.count0..countN (optional)\n if (cat === 'IO') {\n const boolFrom = (v) => {\n if (typeof v === 'boolean') return v;\n if (typeof v === 'number') return v !== 0;\n if (typeof v === 'string') {\n const s = v.trim().toLowerCase();\n if (s === 'true' || s === 'on' || s === '1') return true;\n if (s === 'false' || s === 'off' || s === '0') return false;\n }\n return undefined;\n };\n\n const boolTo = (v) => {\n const b = boolFrom(v);\n if (b === undefined) return false;\n return b;\n };\n\n const inputs = [];\n const outputs = [];\n const counters = [];\n\n const dps = this.getDatapoints();\n for (const dp of dps) {\n if (!dp || !dp.id) continue;\n const id = String(dp.id);\n\n // Input patterns (0-based preferred)\n let m = id.match(/^(?:Input|IN|input|in)[_ ]?(\\d+)$/i) || id.match(/^(?:DI|Din)[_ ]?(\\d+)$/i);\n if (m && (dp.type === 'boolean' || dp.type === 'bool')) {\n const idx = Number(m[1]);\n if (Number.isFinite(idx)) inputs.push({ idx, dp });\n continue;\n }\n\n // Output patterns\n m = id.match(/^(?:Output|OUT|output|out)[_ ]?(\\d+)$/i) || id.match(/^(?:DO|Dout)[_ ]?(\\d+)$/i);\n if (m && (dp.type === 'boolean' || dp.type === 'bool')) {\n const idx = Number(m[1]);\n if (Number.isFinite(idx)) outputs.push({ idx, dp });\n continue;\n }\n\n // Relay patterns: rELAY_1..rELAY_N (1-based -> map to 0-based)\n m = id.match(/^rELAY_(\\d+)$/i);\n if (m && (dp.type === 'boolean' || dp.type === 'bool')) {\n const idx = Number(m[1]);\n if (Number.isFinite(idx) && idx > 0) outputs.push({ idx: idx - 1, dp });\n continue;\n }\n\n // Counter patterns\n m = id.match(/^Counter[_ ]?(\\d+)$/i) || id.match(/^counter[_ ]?(\\d+)$/i);\n if (m && (dp.type === 'number' || dp.type === 'string')) {\n const idx = Number(m[1]);\n if (Number.isFinite(idx)) counters.push({ idx, dp });\n continue;\n }\n }\n\n inputs.sort((a, b) => a.idx - b.idx);\n outputs.sort((a, b) => a.idx - b.idx);\n counters.sort((a, b) => a.idx - b.idx);\n\n for (const it of inputs) {\n add({\n relId: this._aliasRelId(`r.inputs.in${it.idx}`),\n name: `Digital input ${it.idx}`,\n role: 'sensor',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: it.dp.id,\n fromDevice: boolFrom,\n });\n }\n\n for (const it of outputs) {\n // readback\n add({\n relId: this._aliasRelId(`r.outputs.out${it.idx}`),\n name: `Digital output ${it.idx}`,\n role: 'switch',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: it.dp.id,\n fromDevice: boolFrom,\n });\n\n // control\n if (it.dp.rw === 'rw' || it.dp.rw === 'wo') {\n add({\n relId: this._aliasRelId(`ctrl.outputs.out${it.idx}`),\n name: `Set digital output ${it.idx}`,\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: it.dp.id,\n writeDpId: it.dp.id,\n toDevice: boolTo,\n fromDevice: boolFrom,\n });\n }\n }\n\n for (const it of counters) {\n add({\n relId: this._aliasRelId(`r.counters.count${it.idx}`),\n name: `Counter ${it.idx}`,\n role: 'value',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: it.dp.id,\n });\n }\n }\n\n // --- PV inverter specific controls & alarms ---\n if (cat === 'PV_INVERTER') {\n // grid state (raw)\n const gridStateDp = getAnyById('PVConn', 'PvGriConn', 'GriSwStt');\n if (gridStateDp) {\n add({\n relId: this._aliasRelId('r.gridConnectionState'),\n name: 'Grid connection state (raw)',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: gridStateDp.id,\n });\n }\n\n // grid connected (boolean) - computed from known SMA codes where possible\n add({\n relId: this._aliasRelId('r.gridConnected'),\n name: 'Grid connected',\n role: 'indicator.connected',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return undefined;\n if (typeof values.PvGriConn === 'number') return values.PvGriConn === 1780;\n if (typeof values.GriSwStt === 'number') return values.GriSwStt === 51;\n if (typeof values.PVConn === 'number') return values.PVConn !== 0;\n return undefined;\n }\n });\n\n // power limit percent setpoint\n const limitPctDp = getAnyById('WMaxLimPct', 'WLimPct') || this._findFirstDatapoint(dp =>\n (dp.unit === '%' || dp.unit === ' %' || dp.unit === '% ') &&\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /lim/i.test(String(dp.id))\n );\n if (limitPctDp) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitPct'),\n name: 'Active power limit (%)',\n role: 'level',\n type: 'number',\n unit: '%',\n // Expose as read+write even if the underlying register is write-only.\n // In that case we keep the last commanded value until the device provides a readable feedback register.\n rw: 'rw',\n kind: 'dp',\n dpId: limitPctDp.id,\n // allow writes through the alias even if the underlying datapoint is write-only\n writeDpId: limitPctDp.id,\n });\n }\n\n // power limit enable\n const limitEnaDp = getAnyById('WMaxLim_Ena') || this._findFirstDatapoint(dp =>\n (dp.type === 'boolean') &&\n (dp.rw === 'rw') &&\n /lim/i.test(String(dp.id)) &&\n /ena/i.test(String(dp.id))\n );\n if (limitEnaDp) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitEnable'),\n name: 'Active power limit enable',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: limitEnaDp.id,\n writeDpId: limitEnaDp.id,\n });\n }\n\n // run/stop command\n // Preference order:\n // 1) boolean \"Conn\" (true/false)\n // 2) \"FstStop\" (fast shut-down command, often Start=1467 / Stop=381)\n // 3) \"OpMod\" (operating mode codes)\n const connDp = getAnyById('Conn');\n const fstStopDp = getAnyById('FstStop');\n const opModDp = getAnyById('OpMod');\n let runAliasAdded = false;\n if (connDp && (connDp.rw === 'rw' || connDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (connect/start)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: connDp.id,\n writeDpId: connDp.id,\n toDevice: (v) => !!v,\n fromDevice: (v) => !!v,\n });\n runAliasAdded = true;\n } else if (fstStopDp && (fstStopDp.rw === 'rw' || fstStopDp.rw === 'wo')) {\n // Some SMA devices expose a \"Fast shut-down\" command that doubles as start/stop control.\n // Typical codes:\n // - 1467: Start\n // - 381 : Stop\n // - 1749: Full stop\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (start/stop)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: fstStopDp.id,\n writeDpId: fstStopDp.id,\n toDevice: (v) => (v ? 1467 : 381),\n fromDevice: (v) => {\n if (v === 1467) return true;\n if (v === 381 || v === 1749) return false;\n return undefined;\n }\n });\n runAliasAdded = true;\n } else if (opModDp && (opModDp.rw === 'rw' || opModDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (start/stop)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: opModDp.id,\n writeDpId: opModDp.id,\n toDevice: (v) => (v ? 1467 : 381),\n fromDevice: (v) => {\n if (v === 1467) return true;\n if (v === 381) return false;\n return undefined;\n }\n });\n runAliasAdded = true;\n }\n\n // Vendor specific ON/OFF command register (e.g., SolaX X3-MEGA/X3-FORTH: 0xAF=start, 0xAE=stop)\n if (!runAliasAdded) {\n const cmdOnOffDp = getAnyById('CmdOnOff', 'CMD_ON_OFF', 'COMMAND_ON_OFF');\n if (cmdOnOffDp && (cmdOnOffDp.rw === 'rw' || cmdOnOffDp.rw === 'wo')) {\n const onValueRaw = Number(cmdOnOffDp.onValue ?? cmdOnOffDp.trueValue ?? 0xAF);\n const offValueRaw = Number(cmdOnOffDp.offValue ?? cmdOnOffDp.falseValue ?? 0xAE);\n const onValue = Number.isFinite(onValueRaw) ? onValueRaw : 0xAF;\n const offValue = Number.isFinite(offValueRaw) ? offValueRaw : 0xAE;\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (start/stop)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: cmdOnOffDp.id,\n writeDpId: cmdOnOffDp.id,\n toDevice: (v) => (v ? onValue : offValue),\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n if (n === onValue) return true;\n if (n === offValue) return false;\n return undefined;\n }\n });\n }\n }\n\n // alarm.fault / alarm.warning (best-effort)\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Fault active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n // Offline should not automatically equal \"fault\"; keep separate.\n if (!values) return false;\n let fault = false;\n if (typeof values.Health === 'number') fault = fault || (values.Health === 35);\n if (typeof values.St === 'number') fault = fault || (values.St === 7);\n if (typeof values.Evt1 === 'number') fault = fault || (values.Evt1 !== 0);\n return fault;\n }\n });\n\n add({\n relId: this._aliasRelId('alarm.warning'),\n name: 'Warning active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return false;\n if (typeof values.Health === 'number') return values.Health === 455;\n return false;\n }\n });\n }\n\n // --- Battery / ESS aliases (BATTERY, ESS, BATTERY_INVERTER) ---\n // These categories often use vendor-specific datapoint IDs and generic ioBroker roles are not reliable.\n // We therefore derive a stable alias API primarily from datapoint IDs (best-effort).\n const batteryCats = new Set(['BATTERY', 'ESS', 'BATTERY_INVERTER']);\n if (batteryCats.has(cat) && !getVartaProfile(this.template) && !getDeyeProfile(this.template)) {\n const asNumber = (v) => (typeof v === 'number' && Number.isFinite(v)) ? v : undefined;\n const asBool01 = (v) => {\n if (typeof v === 'boolean') return v;\n if (typeof v === 'number') return v !== 0;\n return undefined;\n };\n\n // --- Core read signals ---\n // SoC is a common pain point: some devices expose multiple SoC datapoints where one may be stale\n // or return sentinel values (e.g. 0xFFFF). Therefore we pick the first *valid* SoC at runtime.\n const socCandidateDps = [];\n const pushSoc = (dp) => {\n if (!dp || !dp.id) return;\n if (socCandidateDps.find(x => x.id === dp.id)) return;\n socCandidateDps.push(dp);\n };\n\n // Prefer \"instant\" SoC inputs if available (e.g. *_SOC_IN)\n [\n 'eSS_SOC_IN',\n 'bATTERY_SOC_IN',\n 'sOC_IN',\n 'bATTERY_SOC',\n 'bATTERY_TOTAL_SOC',\n 'sOC',\n ].forEach((id) => pushSoc(findById(id)));\n\n // Regex fallbacks (best-effort)\n pushSoc(findByIdRe(/(^|_)soc_in($|_)/i));\n pushSoc(findByIdRe(/(^|_)soc($|_)/i));\n if (!socCandidateDps.length) {\n pushSoc(this._findFirstDatapoint(dp => /soc/i.test(String(dp.id || ''))));\n }\n\n if (socCandidateDps.length) {\n add({\n relId: this._aliasRelId('r.soc'),\n name: 'State of charge',\n role: 'value.battery',\n type: 'number',\n unit: socCandidateDps[0].unit || '%',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n for (const dp of socCandidateDps) {\n const n = asNumber(values[dp.id]);\n if (n === undefined) continue;\n\n // Standard percent\n if (n >= 0 && n <= 100) return n;\n\n // Some devices report SoC as 0..1 fraction\n if (n >= 0 && n <= 1) return Math.round(n * 10000) / 100;\n }\n return null;\n },\n });\n }\n\n const sohDp =\n getAnyById('sOH') ||\n findByIdRe(/(^|_)soh($|_)/i) ||\n this._findFirstDatapoint(dp => /soh/i.test(String(dp.id || '')));\n\n if (sohDp) {\n add({\n relId: this._aliasRelId('r.soh'),\n name: 'State of health',\n role: 'value',\n type: 'number',\n unit: sohDp.unit || '%',\n rw: 'ro',\n kind: 'dp',\n dpId: sohDp.id,\n });\n }\n\n const battVoltDp =\n getAnyById('bATTERY_VOLTAGE', 'dC_BATTERY_VOLTAGE', 'vOLTAGE', 'lINK_VOLTAGE', 'iNTERNAL_VOLTAGE') ||\n this._findFirstDatapoint(dp => /battery_.*voltage/i.test(String(dp.id || ''))) ||\n this._findFirstDatapoint(dp => /voltage/i.test(String(dp.id || '')) && !/grid_/i.test(String(dp.id || '')));\n\n if (battVoltDp) {\n add({\n relId: this._aliasRelId('r.voltage'),\n name: 'Battery voltage',\n role: 'value.voltage',\n type: 'number',\n unit: battVoltDp.unit || 'V',\n rw: 'ro',\n kind: 'dp',\n dpId: battVoltDp.id,\n });\n }\n\n const battCurrDp =\n getAnyById('bATTERY_CURRENT', 'dC_BATTERY_CURRENT', 'cURRENT') ||\n this._findFirstDatapoint(dp => /battery_.*current/i.test(String(dp.id || ''))) ||\n this._findFirstDatapoint(dp => /current/i.test(String(dp.id || '')) && !/input_/i.test(String(dp.id || '')) && !/output_/i.test(String(dp.id || '')));\n\n if (battCurrDp) {\n add({\n relId: this._aliasRelId('r.current'),\n name: 'Battery current',\n role: 'value.current',\n type: 'number',\n unit: battCurrDp.unit || 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: battCurrDp.id,\n });\n }\n\n const battTempDp =\n getAnyById('bATTERY_TEMPERATURE', 'aVG_BATTERY_TEMPERATURE') ||\n this._findFirstDatapoint(dp => /^bATTERY_.*tEMPERATURE$/i.test(String(dp.id || ''))) ||\n this._findFirstDatapoint(dp => /battery_.*temperature/i.test(String(dp.id || '')));\n\n if (battTempDp) {\n add({\n relId: this._aliasRelId('r.temperature'),\n name: 'Battery temperature',\n role: 'value.temperature',\n type: 'number',\n unit: battTempDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: battTempDp.id,\n });\n }\n\n // --- Power (W): prefer explicit charge/discharge power, else measured net power, else compute from V*I ---\n const chargePowerDp = getAnyById('bATTERY_CHARGE_POWER');\n const dischargePowerDp = getAnyById('bATTERY_DISCHARGE_POWER');\n const isFeneconHomeEss = this._isFeneconHomeEssTemplate();\n const feneconHybridPowerDp = isFeneconHomeEss ? getAnyById('bATTERY_POWER') : undefined;\n const feneconAcPowerDp = isFeneconHomeEss ? getAnyById('bATTERY_AC_POWER') : undefined;\n const activePowerDp = isFeneconHomeEss ? feneconAcPowerDp : (\n getAnyById('bATTERY_POWER', 'aCTIVE_POWER', 'eSS0_ACTIVE_POWER') ||\n this._findFirstDatapoint(dp => /^bATTERY_.*pOWER$/i.test(String(dp.id || '')) && dp.rw !== 'wo') ||\n this._findFirstDatapoint(dp => /^aCTIVE_POWER$/i.test(String(dp.id || '')) && dp.rw !== 'wo')\n );\n\n // Some SMA batteries provide separate charge/discharge currents (unsigned). Use these when present.\n const chargeCurrentDp = getAnyById('cUR_BAT_CHA');\n const dischargeCurrentDp = getAnyById('cUR_BAT_DSCH');\n\n // Per-phase active power (common in ESS/battery inverter)\n const pL1 = getAnyById('aCTIVE_POWER_L1');\n const pL2 = getAnyById('aCTIVE_POWER_L2');\n const pL3 = getAnyById('aCTIVE_POWER_L3');\n\n // Hybrid/ESS signals\n const pvPowerDp =\n getAnyById('pV_POWER', 'pV_POWER_SUM') ||\n this._findFirstDatapoint(dp => /^pV_.*pOWER/i.test(String(dp.id || '')) && dp.rw !== 'wo') ||\n this._findFirstDatapoint(dp => /pv.*power/i.test(String(dp.id || '')) && dp.rw !== 'wo');\n\n const powerUnit =\n (feneconAcPowerDp && feneconAcPowerDp.unit) ||\n (chargePowerDp && chargePowerDp.unit) ||\n (dischargePowerDp && dischargePowerDp.unit) ||\n (activePowerDp && activePowerDp.unit) ||\n (pL1 && pL1.unit) ||\n (pL2 && pL2.unit) ||\n (pL3 && pL3.unit) ||\n 'W';\n\n const hybridPowerUnit =\n (feneconHybridPowerDp && feneconHybridPowerDp.unit) ||\n powerUnit ||\n 'W';\n\n const getAbsPowerValue = (dp, values) => {\n if (!dp || !values) return undefined;\n const v = asNumber(values[dp.id]);\n if (v === undefined) return undefined;\n return Math.abs(v);\n };\n\n const computeFeneconHomeEssAcPowerW = (values) => {\n if (!isFeneconHomeEss) return undefined;\n if (!values || !feneconAcPowerDp) return null;\n const measured = asNumber(values[feneconAcPowerDp.id]);\n // _sum/EssDischargePower (415) already carries the battery direction.\n // ess0/ActivePower (604) includes DC-PV and cannot supply its sign or\n // replace an unavailable battery measurement. Publish null to invalidate\n // an earlier battery value instead of keeping it seemingly current.\n return measured === undefined ? null : measured;\n };\n\n const computeFeneconHomeEssHybridPowerW = (values) => {\n if (!isFeneconHomeEss) return undefined;\n if (!values || !feneconHybridPowerDp) return null;\n const v = asNumber(values[feneconHybridPowerDp.id]);\n return v === undefined ? null : v;\n };\n\n const computeBatteryAcPowerWFallback = (values) => {\n if (!values) return undefined;\n\n if (isFeneconHomeEss) return computeFeneconHomeEssAcPowerW(values);\n\n // Prefer explicit measured net power datapoint\n if (activePowerDp) {\n const v = asNumber(values[activePowerDp.id]);\n if (v !== undefined) return v;\n }\n\n // Sum per-phase active powers if present\n const v1 = pL1 ? asNumber(values[pL1.id]) : undefined;\n const v2 = pL2 ? asNumber(values[pL2.id]) : undefined;\n const v3 = pL3 ? asNumber(values[pL3.id]) : undefined;\n if (v1 !== undefined || v2 !== undefined || v3 !== undefined) return (v1 || 0) + (v2 || 0) + (v3 || 0);\n\n // If we have separate charge/discharge currents and a battery voltage, compute net power.\n if (battVoltDp && (chargeCurrentDp || dischargeCurrentDp)) {\n const u = asNumber(values[battVoltDp.id]);\n const icha = chargeCurrentDp ? asNumber(values[chargeCurrentDp.id]) : undefined;\n const idsch = dischargeCurrentDp ? asNumber(values[dischargeCurrentDp.id]) : undefined;\n if (u !== undefined && (icha !== undefined || idsch !== undefined)) {\n const pCharge = (icha || 0) * u;\n const pDischarge = (idsch || 0) * u;\n // Convention: discharge positive, charge negative\n return pDischarge - pCharge;\n }\n }\n\n // Fallback: compute from signed battery current * voltage\n if (battVoltDp && battCurrDp) {\n const u = asNumber(values[battVoltDp.id]);\n const i = asNumber(values[battCurrDp.id]);\n if (u !== undefined && i !== undefined) return u * i;\n }\n\n return undefined;\n };\n\n const computeBatteryAcSplitPower = (values) => {\n if (!values) return { charge: undefined, discharge: undefined };\n\n if (isFeneconHomeEss) {\n const feneconAcPower = computeFeneconHomeEssAcPowerW(values);\n if (feneconAcPower === null) return { charge: null, discharge: null };\n return {\n charge: feneconAcPower < 0 ? Math.abs(feneconAcPower) : 0,\n discharge: feneconAcPower > 0 ? feneconAcPower : 0,\n };\n }\n\n // Prefer explicit charge/discharge datapoints when present.\n const pCharge = getAbsPowerValue(chargePowerDp, values);\n const pDischarge = getAbsPowerValue(dischargePowerDp, values);\n if (pCharge !== undefined || pDischarge !== undefined) {\n return {\n charge: pCharge !== undefined ? pCharge : 0,\n discharge: pDischarge !== undefined ? pDischarge : 0,\n };\n }\n\n const p = computeBatteryAcPowerWFallback(values);\n if (p === undefined) return { charge: undefined, discharge: undefined };\n return {\n charge: p < 0 ? Math.abs(p) : 0,\n discharge: p > 0 ? p : 0,\n };\n };\n\n const computeBatteryAcPowerW = (values) => {\n if (isFeneconHomeEss) return computeFeneconHomeEssAcPowerW(values);\n const split = computeBatteryAcSplitPower(values);\n if (split.charge === undefined && split.discharge === undefined) return undefined;\n return (split.discharge || 0) - (split.charge || 0);\n };\n\n if (isFeneconHomeEss) {\n add({\n relId: this._aliasRelId('r.powerAc'),\n name: 'Battery power (AC-side, real)',\n role: 'value.power',\n type: 'number',\n unit: powerUnit || 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeBatteryAcPowerW(values),\n });\n\n add({\n relId: this._aliasRelId('r.powerBalance'),\n name: 'Battery power (hybrid incl. DC surplus, signed)',\n role: 'value.power',\n type: 'number',\n unit: hybridPowerUnit || 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeFeneconHomeEssHybridPowerW(values),\n });\n }\n\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Battery power (net)',\n role: 'value.power',\n type: 'number',\n unit: powerUnit || 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeBatteryAcPowerW(values),\n });\n\n // Split into charge/discharge power (absolute)\n add({\n relId: this._aliasRelId('r.powerCharge'),\n name: 'Battery charge power',\n role: 'value.power',\n type: 'number',\n unit: powerUnit || 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeBatteryAcSplitPower(values).charge,\n });\n\n add({\n relId: this._aliasRelId('r.powerDischarge'),\n name: 'Battery discharge power',\n role: 'value.power',\n type: 'number',\n unit: powerUnit || 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeBatteryAcSplitPower(values).discharge,\n });\n\n if (pvPowerDp) {\n add({\n relId: this._aliasRelId('r.pvPower'),\n name: 'PV power',\n role: 'value.power',\n type: 'number',\n unit: pvPowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: pvPowerDp.id,\n });\n }\n\n // --- Energy counters (Wh) ---\n const chargeEnergyDp =\n getAnyById('aCTIVE_CHARGE_ENERGY', 'dC_CHARGED_ENERGY', 'dC_CHARGE_ENERGY', 'aCT_BAT_CHRG') ||\n this._findFirstDatapoint(dp => /charge.*energy/i.test(String(dp.id || '')) && !/parameter/i.test(String(dp.id || '')));\n\n const dischargeEnergyDp =\n getAnyById('aCTIVE_DISCHARGE_ENERGY', 'dC_DISCHARGED_ENERGY', 'dC_DISCHARGE_ENERGY', 'aCT_BAT_DSCH') ||\n this._findFirstDatapoint(dp => /discharge.*energy/i.test(String(dp.id || '')) && !/parameter/i.test(String(dp.id || '')));\n\n const safeU64ToNumber = (raw) => {\n if (typeof raw === 'number' && Number.isFinite(raw)) return raw;\n if (typeof raw === 'string') {\n const n = Number(raw);\n if (Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER) return n;\n }\n return undefined;\n };\n\n if (chargeEnergyDp) {\n add({\n relId: this._aliasRelId('r.energyCharge'),\n name: 'Charge energy (total)',\n role: 'value.energy',\n type: 'number',\n unit: chargeEnergyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: chargeEnergyDp.id,\n fromDevice: (v) => safeU64ToNumber(v),\n });\n }\n\n if (dischargeEnergyDp) {\n add({\n relId: this._aliasRelId('r.energyDischarge'),\n name: 'Discharge energy (total)',\n role: 'value.energy',\n type: 'number',\n unit: dischargeEnergyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: dischargeEnergyDp.id,\n fromDevice: (v) => safeU64ToNumber(v),\n });\n }\n\n // --- BMS allow charge/discharge (read) ---\n const allowChargeDp = getAnyById('bP_CHARGE_BMS', 'vE_BUS_BMS_ALLOW_BATTERY_CHARGE');\n if (allowChargeDp) {\n add({\n relId: this._aliasRelId('r.allowCharge'),\n name: 'BMS allows charge',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: allowChargeDp.id,\n fromDevice: (v) => asBool01(v),\n });\n }\n\n const allowDischargeDp = getAnyById('bP_DISCHARGE_BMS', 'vE_BUS_BMS_ALLOW_BATTERY_DISCHARGE');\n if (allowDischargeDp) {\n add({\n relId: this._aliasRelId('r.allowDischarge'),\n name: 'BMS allows discharge',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: allowDischargeDp.id,\n fromDevice: (v) => asBool01(v),\n });\n }\n\n // --- Allowed charge/discharge power (W) ---\n const allowedChargePowerDp = getAnyById('aLLOWED_CHARGE_POWER', 'oRIGINAL_ALLOWED_CHARGE_POWER');\n if (allowedChargePowerDp) {\n add({\n relId: this._aliasRelId('r.allowedChargePower'),\n name: 'Allowed charge power',\n role: 'value.power',\n type: 'number',\n unit: allowedChargePowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: allowedChargePowerDp.id,\n });\n }\n\n const allowedDischargePowerDp = getAnyById('aLLOWED_DISCHARGE_POWER', 'oRIGINAL_ALLOWED_DISCHARGE_POWER', 'eSS_MAX_DISCHARGE_POWER');\n if (allowedDischargePowerDp) {\n add({\n relId: this._aliasRelId('r.allowedDischargePower'),\n name: 'Allowed discharge power',\n role: 'value.power',\n type: 'number',\n unit: allowedDischargePowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: allowedDischargePowerDp.id,\n });\n }\n\n // --- Control: active power setpoint (W) ---\n const setActivePowerDp =\n getAnyById('sET_ACTIVE_POWER') ||\n this._findFirstDatapoint(dp => /^sET_ACTIVE_POWER$/i.test(String(dp.id || '')) && (dp.rw === 'rw' || dp.rw === 'wo')) ||\n this._findFirstDatapoint(dp => /^sET_ACTIVE_POWER(_6_\\d+)?$/i.test(String(dp.id || '')) && (dp.rw === 'rw' || dp.rw === 'wo'));\n\n if (setActivePowerDp) {\n add({\n relId: this._aliasRelId('ctrl.powerSetpointW'),\n name: 'Active power setpoint (battery/ESS)',\n role: 'level.power',\n type: 'number',\n unit: setActivePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: setActivePowerDp.id,\n writeDpId: setActivePowerDp.id,\n });\n\n // Convenience aliases: split-direction power setpoints.\n // Standard: charge power is written as positive value and mapped to a NEGATIVE setpoint,\n // discharge power is written as positive value and mapped to a POSITIVE setpoint.\n // This is especially useful for devices like SolaX where one register controls both directions.\n add({\n relId: this._aliasRelId('ctrl.chargePowerW'),\n name: 'Charge power setpoint',\n role: 'level.power',\n type: 'number',\n unit: setActivePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: setActivePowerDp.id,\n writeDpId: setActivePowerDp.id,\n toDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return -Math.abs(n);\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n return n < 0 ? Math.abs(n) : 0;\n }\n });\n\n add({\n relId: this._aliasRelId('ctrl.dischargePowerW'),\n name: 'Discharge power setpoint',\n role: 'level.power',\n type: 'number',\n unit: setActivePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: setActivePowerDp.id,\n writeDpId: setActivePowerDp.id,\n toDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return Math.abs(n);\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n return n > 0 ? Math.abs(n) : 0;\n }\n });\n }\n\n\n // --- Control: PV power limit/target (W) (optional, mainly for hybrid ESS that support PV curtailment) ---\n const setPvPowerDp =\n getAnyById('sET_PV_POWER', 'sET_PV_ACTIVE_POWER', 'pV_W_TARGET', 'pV_POWER_TARGET') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /^sET_?pV_?.*pOWER/i.test(String(dp.id || ''))\n );\n\n if (setPvPowerDp) {\n add({\n relId: this._aliasRelId('ctrl.pvPowerLimitW'),\n name: 'PV power limit/target',\n role: 'level.power',\n type: 'number',\n unit: setPvPowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: setPvPowerDp.id,\n writeDpId: setPvPowerDp.id,\n });\n }\n\n\n // --- Control: max charge/discharge power limits (optional) ---\n const maxDischargePowerDp =\n getAnyById('sET_MAX_DISCHARGE_POWER', 'sET_MAX_DISCHARGE_POWER_W', 'sET_MAX_DISCHARGE', 'sET_DISCHARGE_LIMIT') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /(max|limit).*(discharge|dsch|entlad).*power/i.test(String(dp.id || ''))\n );\n\n if (maxDischargePowerDp) {\n add({\n relId: this._aliasRelId('ctrl.maxDischargePowerW'),\n name: 'Max discharge power limit',\n role: 'level.power',\n type: 'number',\n unit: maxDischargePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: maxDischargePowerDp.id,\n writeDpId: maxDischargePowerDp.id,\n toDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return Math.abs(n);\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n return Math.abs(n);\n }\n });\n }\n\n const maxChargePowerDp =\n getAnyById('sET_MAX_CHARGE_POWER', 'sET_MAX_CHARGE_POWER_W', 'sET_MAX_CHARGE', 'sET_CHARGE_LIMIT') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /(max|limit).*(charge|cha|belad).*power/i.test(String(dp.id || ''))\n );\n\n if (maxChargePowerDp) {\n add({\n relId: this._aliasRelId('ctrl.maxChargePowerW'),\n name: 'Max charge power limit',\n role: 'level.power',\n type: 'number',\n unit: maxChargePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: maxChargePowerDp.id,\n writeDpId: maxChargePowerDp.id,\n toDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return Math.abs(n);\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n return Math.abs(n);\n }\n });\n }\n\n if (isFeneconHomeEss) {\n // ManagedSymmetricEss 706/710/714 are write-only constraints. A successful\n // write acknowledges the command, not a measured/applied device value.\n // Polling must neither invent a readback nor overwrite command memory.\n const commandIds = new Set(['sET_ACTIVE_POWER', 'sET_MAX_DISCHARGE_POWER', 'sET_MAX_CHARGE_POWER']);\n for (const def of defs) {\n if (def.kind !== 'dp' || !commandIds.has(def.writeDpId)) continue;\n def.commandOnlyAlias = true;\n def.preferCommandValue = true;\n }\n const chargeLimit = defs.find(def => def.relId === this._aliasRelId('ctrl.maxChargePowerW'));\n if (chargeLimit) {\n // SetActivePowerGreaterOrEquals: maximum charge is a NEGATIVE bound;\n // a positive bound would request minimum discharge instead.\n chargeLimit.toDevice = (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return n === 0 ? 0 : -Math.abs(n);\n };\n }\n }\n\n // Per-phase setpoints (if available)\n const setPL1 = getAnyById('sET_ACTIVE_POWER_L1');\n const setPL2 = getAnyById('sET_ACTIVE_POWER_L2');\n const setPL3 = getAnyById('sET_ACTIVE_POWER_L3');\n if (setPL1 && (setPL1.rw === 'rw' || setPL1.rw === 'wo')) add({ relId: this._aliasRelId('ctrl.powerSetpointL1'), name: 'Active power setpoint L1', role: 'level.power', type: 'number', unit: setPL1.unit || 'W', rw: 'rw', kind: 'dp', dpId: setPL1.id, writeDpId: setPL1.id });\n if (setPL2 && (setPL2.rw === 'rw' || setPL2.rw === 'wo')) add({ relId: this._aliasRelId('ctrl.powerSetpointL2'), name: 'Active power setpoint L2', role: 'level.power', type: 'number', unit: setPL2.unit || 'W', rw: 'rw', kind: 'dp', dpId: setPL2.id, writeDpId: setPL2.id });\n if (setPL3 && (setPL3.rw === 'rw' || setPL3.rw === 'wo')) add({ relId: this._aliasRelId('ctrl.powerSetpointL3'), name: 'Active power setpoint L3', role: 'level.power', type: 'number', unit: setPL3.unit || 'W', rw: 'rw', kind: 'dp', dpId: setPL3.id, writeDpId: setPL3.id });\n\n // Control: control mode (vendor-specific but stable location)\n const controlModeDp = getAnyById('sET_CONTROL_MODE');\n if (controlModeDp && (controlModeDp.rw === 'rw' || controlModeDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.controlMode'),\n name: 'Control mode',\n role: 'level',\n type: 'number',\n rw: 'rw',\n kind: 'dp',\n dpId: controlModeDp.id,\n writeDpId: controlModeDp.id,\n });\n }\n\n\n // Control: start/stop (hybrid inverters / energy systems that expose a boolean Conn datapoint)\n const essConnDp = getAnyById('Conn');\n if (essConnDp && (essConnDp.rw === 'rw' || essConnDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (start/stop)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: essConnDp.id,\n writeDpId: essConnDp.id,\n toDevice: (v) => !!v,\n fromDevice: (v) => {\n if (typeof v === 'boolean') return v;\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n if (n === 0xCF || n === 1) return true;\n if (n === 0xCE || n === 0) return false;\n return undefined;\n }\n });\n }\n\n // --- Grid / NAP power & setpoints (Energy Managers / Hybrid systems) ---\n // Some systems (e.g., TESVOLT Energy Manager Vermarkter-Schnittstelle) expose the grid connection point as \"NAP\".\n // We provide a stable read alias for the current grid/NAP power and a stable write alias for the grid/NAP setpoint.\n const gridPowerDp =\n getAnyById('gRID_POWER', 'nAP_POWER') ||\n this._findFirstDatapoint(dp => /(^|_)(grid|nap).*power/i.test(String(dp.id || '')) && dp.rw !== 'wo');\n\n if (gridPowerDp) {\n add({\n relId: this._aliasRelId('r.gridPower'),\n name: 'Grid / NAP power',\n role: 'value.power',\n type: 'number',\n unit: gridPowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: gridPowerDp.id,\n });\n }\n\n const gridSetpointDp =\n getAnyById('nAP_POWER_SETPOINT', 'sET_NAP_POWER', 'gRID_POWER_SETPOINT') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /(nap|grid).*(set|target|limit).*power/i.test(String(dp.id || ''))\n );\n\n if (gridSetpointDp) {\n add({\n relId: this._aliasRelId('ctrl.gridSetpointW'),\n name: 'Grid / NAP power setpoint',\n role: 'level.power',\n type: 'number',\n unit: gridSetpointDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: gridSetpointDp.id,\n writeDpId: gridSetpointDp.id,\n });\n\n // Synonym (more explicit)\n add({\n relId: this._aliasRelId('ctrl.napSetpointW'),\n name: 'NAP power setpoint',\n role: 'level.power',\n type: 'number',\n unit: gridSetpointDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: gridSetpointDp.id,\n writeDpId: gridSetpointDp.id,\n });\n }\n\n // FENECON ctrlBalancing0/SetGridActivePower is a write-only command that\n // shifts the grid-connection balancing target. Keep it out of the historic\n // aliases.* namespace so running installations remain byte-for-byte\n // compatible, but expose it through the canonical Alias Contract v1.\n const feneconGridActivePowerDp = getAnyById('sET_GRID_ACTIVE_POWER');\n if (feneconGridActivePowerDp && (feneconGridActivePowerDp.rw === 'rw' || feneconGridActivePowerDp.rw === 'wo')) {\n for (const [aliasPath, aliasName] of [\n ['ctrl.gridSetpointW', 'Grid connection active-power target'],\n ['ctrl.napSetpointW', 'NAP active-power target'],\n ]) {\n addStandardSource({\n relId: this._aliasRelId(aliasPath),\n name: aliasName,\n role: 'level.power',\n type: 'number',\n unit: feneconGridActivePowerDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: feneconGridActivePowerDp.id,\n writeDpId: feneconGridActivePowerDp.id,\n commandOnlyAlias: true,\n preferCommandValue: true,\n });\n }\n }\n\n\n\n // --- PV / export power limiting (best-effort) ---\n const exportPowerPctDp = getAnyById('eXPORT_POWER_PERCENTAGE', 'wMaxLimPct', 'wMAXLIMPCT');\n if (exportPowerPctDp && (exportPowerPctDp.rw === 'rw' || exportPowerPctDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitPct'),\n name: 'PV/export power limit (%)',\n role: 'level',\n type: 'number',\n unit: exportPowerPctDp.unit || '%',\n rw: 'rw',\n kind: 'dp',\n dpId: exportPowerPctDp.id,\n writeDpId: exportPowerPctDp.id,\n });\n\n // More explicit synonym (useful when multiple device categories are merged downstream)\n add({\n relId: this._aliasRelId('ctrl.exportLimitPct'),\n name: 'Export power limit (%)',\n role: 'level',\n type: 'number',\n unit: exportPowerPctDp.unit || '%',\n rw: 'rw',\n kind: 'dp',\n dpId: exportPowerPctDp.id,\n writeDpId: exportPowerPctDp.id,\n });\n }\n\n const exportPowerLimitDp = getAnyById('eXPORT_POWER_LIMIT', 'wMaxLim', 'wMAXLIM');\n if (exportPowerLimitDp && (exportPowerLimitDp.rw === 'rw' || exportPowerLimitDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitW'),\n name: 'PV/export power limit (W)',\n role: 'level.power',\n type: 'number',\n unit: exportPowerLimitDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: exportPowerLimitDp.id,\n writeDpId: exportPowerLimitDp.id,\n });\n\n add({\n relId: this._aliasRelId('ctrl.exportLimitW'),\n name: 'Export power limit (W)',\n role: 'level.power',\n type: 'number',\n unit: exportPowerLimitDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: exportPowerLimitDp.id,\n writeDpId: exportPowerLimitDp.id,\n });\n }\n\n // Control: charge enable (best-effort)\n const disableChargeDp = getAnyById('eSS_DISABLE_CHARGE_FLAG');\n if (disableChargeDp && (disableChargeDp.rw === 'rw' || disableChargeDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.chargeEnable'),\n name: 'Charge enable',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: disableChargeDp.id,\n writeDpId: disableChargeDp.id,\n toDevice: (v) => (v ? 0 : 1),\n fromDevice: (v) => {\n const b = asBool01(v);\n if (b === undefined) return undefined;\n // dp is DISABLE flag -> invert\n return !b;\n }\n });\n }\n\n // --- Status & alarms (best-effort, conservative) ---\n const statusDp =\n getAnyById('bAT_STATUS', 'bATTERY_STATE', 'bATTERY_WORK_STATE', 'sYSTEM_STATE', 'cLUSTER_RUN_STATE', 'sYSTEM_RUNNING_STATE', 'vE_BUS_STATE', 'sWITCH_POSITION') ||\n this._findFirstDatapoint(dp => /(^|_)(state|status|health)($|_)/i.test(String(dp.id || '')) && !/parameter/i.test(String(dp.id || '')));\n\n if (statusDp) {\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: statusDp.id,\n });\n }\n\n const errorCodeDp =\n getAnyById('vE_BUS_ERROR', 'vE_BUS_BMS_ERROR', 'iNSULATION_RESISTANCE_ERROR_LEVEL') ||\n this._findFirstDatapoint(dp => /(^|_)(error|fault)($|_)/i.test(String(dp.id || '')) && !/parameter/i.test(String(dp.id || '')));\n\n if (errorCodeDp) {\n add({\n relId: this._aliasRelId('r.errorCode'),\n name: 'Error code',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: errorCodeDp.id,\n });\n }\n\n // Conservative fault detection: explicit error codes or active alarm/protect flag registers (non-zero)\n const faultFlagDps = this.getDatapoints().filter(dp => {\n const id = String(dp && dp.id ? dp.id : '');\n if (!id) return false;\n // exclude configuration thresholds\n if (/(parameter|limit|recover|threshold)/i.test(id)) return false;\n return /(vE_BUS_ERROR|vE_BUS_BMS_ERROR|ALARM_FLAG_REGISTER|PROTECT_FLAG_REGISTER|SYSTEM_FAULT_COUNTERS|INSULATION_RESISTANCE_ERROR_LEVEL)/i.test(id);\n });\n\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Fault active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return false;\n\n // EMS1000: System operating status uses 4 = Failure\n // (1 = On-grid, 2 = Off-grid, 3 = Standby, 4 = Failure)\n if (typeof values.sYSTEM_OPERATING_STATUS === 'number' && values.sYSTEM_OPERATING_STATUS === 4) {\n return true;\n }\n // explicit error code\n if (errorCodeDp) {\n const v = values[errorCodeDp.id];\n if (typeof v === 'number') return v !== 0;\n }\n\n for (const dp of faultFlagDps) {\n const v = values[dp.id];\n if (typeof v === 'boolean' && v) return true;\n if (typeof v === 'number' && v !== 0) return true;\n }\n return false;\n }\n });\n\n // Warning (best-effort): look for active warning registers (exclude parameters)\n const warnFlagDps = this.getDatapoints().filter(dp => {\n const id = String(dp && dp.id ? dp.id : '');\n if (!id) return false;\n if (/(parameter|limit|recover|threshold)/i.test(id)) return false;\n return /(warning|warn)/i.test(id);\n });\n\n if (warnFlagDps && warnFlagDps.length) {\n add({\n relId: this._aliasRelId('alarm.warning'),\n name: 'Warning active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return false;\n for (const dp of warnFlagDps) {\n const v = values[dp.id];\n if (typeof v === 'boolean' && v) return true;\n if (typeof v === 'number' && v !== 0) return true;\n }\n return false;\n }\n });\n }\n }\n\n // --- Meter aliases (read-only, stable API) ---\n if (cat === 'METER') {\n // Identify datapoints (best-effort)\n const netPowerDp =\n getAnyById('aCTIVE_POWER') ||\n findByIdRe(/^aCTIVE_POWER$/i);\n\n const importPowerDp =\n getAnyById('aCTIVE_CONSUMPTION_POWER') ||\n findByIdRe(/^aCTIVE_CONSUMPTION_POWER(?!_L[123])/i);\n\n const exportPowerDp =\n getAnyById('aCTIVE_PRODUCTION_POWER') ||\n findByIdRe(/^aCTIVE_PRODUCTION_POWER(?!_L[123])/i);\n\n const posPowerDp =\n getAnyById('aCTIVE_POWER_POS') ||\n findByIdRe(/^aCTIVE_POWER_POS$/i);\n\n const negPowerDp =\n getAnyById('aCTIVE_POWER_NEG') ||\n findByIdRe(/^aCTIVE_POWER_NEG$/i);\n\n const pL1 = getAnyById('aCTIVE_POWER_L1');\n const pL2 = getAnyById('aCTIVE_POWER_L2');\n const pL3 = getAnyById('aCTIVE_POWER_L3');\n\n const importEnergyDp =\n getAnyById('aCTIVE_CONSUMPTION_ENERGY') ||\n findByIdRe(/^aCTIVE_CONSUMPTION_ENERGY(?!_L[123])/i);\n\n const exportEnergyDp =\n getAnyById('aCTIVE_PRODUCTION_ENERGY') ||\n findByIdRe(/^aCTIVE_PRODUCTION_ENERGY(?!_L[123])/i);\n\n const importEnergyL1 = findByIdRe(/^aCTIVE_CONSUMPTION_ENERGY_L1/i) || getAnyById('aCTIVE_CONSUMPTION_ENERGY_L1');\n const importEnergyL2 = findByIdRe(/^aCTIVE_CONSUMPTION_ENERGY_L2/i) || getAnyById('aCTIVE_CONSUMPTION_ENERGY_L2');\n const importEnergyL3 = findByIdRe(/^aCTIVE_CONSUMPTION_ENERGY_L3/i) || getAnyById('aCTIVE_CONSUMPTION_ENERGY_L3');\n\n const exportEnergyL1 = findByIdRe(/^aCTIVE_PRODUCTION_ENERGY_L1/i) || getAnyById('aCTIVE_PRODUCTION_ENERGY_L1');\n const exportEnergyL2 = findByIdRe(/^aCTIVE_PRODUCTION_ENERGY_L2/i) || getAnyById('aCTIVE_PRODUCTION_ENERGY_L2');\n const exportEnergyL3 = findByIdRe(/^aCTIVE_PRODUCTION_ENERGY_L3/i) || getAnyById('aCTIVE_PRODUCTION_ENERGY_L3');\n\n const asNumber = (v) => (typeof v === 'number' && Number.isFinite(v)) ? v : undefined;\n\n const computeNetPower = (values) => {\n if (!values) return undefined;\n\n const pNet = netPowerDp ? asNumber(values[netPowerDp.id]) : undefined;\n if (pNet !== undefined) return pNet;\n\n const imp = importPowerDp ? asNumber(values[importPowerDp.id]) : undefined;\n const exp = exportPowerDp ? asNumber(values[exportPowerDp.id]) : undefined;\n if (imp !== undefined || exp !== undefined) return (imp || 0) - (exp || 0);\n\n const pos = posPowerDp ? asNumber(values[posPowerDp.id]) : undefined;\n const neg = negPowerDp ? asNumber(values[negPowerDp.id]) : undefined;\n if (pos !== undefined || neg !== undefined) return (pos || 0) - (neg || 0);\n\n const p1 = pL1 ? asNumber(values[pL1.id]) : undefined;\n const p2 = pL2 ? asNumber(values[pL2.id]) : undefined;\n const p3 = pL3 ? asNumber(values[pL3.id]) : undefined;\n if (p1 !== undefined || p2 !== undefined || p3 !== undefined) return (p1 || 0) + (p2 || 0) + (p3 || 0);\n\n return undefined;\n };\n\n const computeImportPower = (values) => {\n if (!values) return undefined;\n\n const imp = importPowerDp ? asNumber(values[importPowerDp.id]) : undefined;\n if (imp !== undefined) return imp;\n\n const pos = posPowerDp ? asNumber(values[posPowerDp.id]) : undefined;\n if (pos !== undefined) return pos;\n\n const net = computeNetPower(values);\n if (net === undefined) return undefined;\n return net > 0 ? net : 0;\n };\n\n const computeExportPower = (values) => {\n if (!values) return undefined;\n\n const exp = exportPowerDp ? asNumber(values[exportPowerDp.id]) : undefined;\n if (exp !== undefined) return exp;\n\n const neg = negPowerDp ? asNumber(values[negPowerDp.id]) : undefined;\n if (neg !== undefined) return neg;\n\n const net = computeNetPower(values);\n if (net === undefined) return undefined;\n return net < 0 ? Math.abs(net) : 0;\n };\n\n const computeImportEnergy = (values) => {\n if (!values) return undefined;\n const e = importEnergyDp ? asNumber(values[importEnergyDp.id]) : undefined;\n if (e !== undefined) return e;\n\n const e1 = importEnergyL1 ? asNumber(values[importEnergyL1.id]) : undefined;\n const e2 = importEnergyL2 ? asNumber(values[importEnergyL2.id]) : undefined;\n const e3 = importEnergyL3 ? asNumber(values[importEnergyL3.id]) : undefined;\n if (e1 !== undefined || e2 !== undefined || e3 !== undefined) return (e1 || 0) + (e2 || 0) + (e3 || 0);\n\n return undefined;\n };\n\n const computeExportEnergy = (values) => {\n if (!values) return undefined;\n const e = exportEnergyDp ? asNumber(values[exportEnergyDp.id]) : undefined;\n if (e !== undefined) return e;\n\n const e1 = exportEnergyL1 ? asNumber(values[exportEnergyL1.id]) : undefined;\n const e2 = exportEnergyL2 ? asNumber(values[exportEnergyL2.id]) : undefined;\n const e3 = exportEnergyL3 ? asNumber(values[exportEnergyL3.id]) : undefined;\n if (e1 !== undefined || e2 !== undefined || e3 !== undefined) return (e1 || 0) + (e2 || 0) + (e3 || 0);\n\n return undefined;\n };\n\n const hasAnyPower = !!(netPowerDp || importPowerDp || exportPowerDp || posPowerDp || negPowerDp || pL1 || pL2 || pL3);\n\n // net power (W) - prefer direct active power, else compute from available signals\n if (hasAnyPower) {\n if (netPowerDp) {\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Net active power',\n role: 'value.power',\n type: 'number',\n unit: netPowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: netPowerDp.id,\n });\n } else {\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Net active power',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeNetPower(values),\n });\n }\n\n // powerImport (W)\n if (importPowerDp || posPowerDp) {\n const dp = importPowerDp || posPowerDp;\n add({\n relId: this._aliasRelId('r.powerImport'),\n name: 'Import power',\n role: 'value.power',\n type: 'number',\n unit: dp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: dp.id,\n });\n } else {\n add({\n relId: this._aliasRelId('r.powerImport'),\n name: 'Import power',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeImportPower(values),\n });\n }\n\n // powerExport (W)\n if (exportPowerDp || negPowerDp) {\n const dp = exportPowerDp || negPowerDp;\n add({\n relId: this._aliasRelId('r.powerExport'),\n name: 'Export power',\n role: 'value.power',\n type: 'number',\n unit: dp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: dp.id,\n });\n } else {\n add({\n relId: this._aliasRelId('r.powerExport'),\n name: 'Export power',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeExportPower(values),\n });\n }\n }\n\n // energy import/export (Wh) - use totals when available, else sum per phase\n const hasAnyEnergy = !!(importEnergyDp || exportEnergyDp || importEnergyL1 || importEnergyL2 || importEnergyL3 || exportEnergyL1 || exportEnergyL2 || exportEnergyL3);\n\n if (hasAnyEnergy) {\n if (importEnergyDp) {\n add({\n relId: this._aliasRelId('r.energyImport'),\n name: 'Import energy',\n role: 'value.energy',\n type: 'number',\n unit: importEnergyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: importEnergyDp.id,\n });\n } else {\n add({\n relId: this._aliasRelId('r.energyImport'),\n name: 'Import energy',\n role: 'value.energy',\n type: 'number',\n unit: 'Wh',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeImportEnergy(values),\n });\n }\n\n if (exportEnergyDp) {\n add({\n relId: this._aliasRelId('r.energyExport'),\n name: 'Export energy',\n role: 'value.energy',\n type: 'number',\n unit: exportEnergyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: exportEnergyDp.id,\n });\n } else {\n add({\n relId: this._aliasRelId('r.energyExport'),\n name: 'Export energy',\n role: 'value.energy',\n type: 'number',\n unit: 'Wh',\n rw: 'ro',\n kind: 'computed',\n get: (values) => computeExportEnergy(values),\n });\n }\n }\n\n // Phase voltages/currents (V/A) and frequency (Hz)\n const vL1 = getAnyById('vOLTAGE_L1') || getAnyById('vOLTAGE');\n const vL2 = getAnyById('vOLTAGE_L2');\n const vL3 = getAnyById('vOLTAGE_L3');\n\n const cL1 = getAnyById('cURRENT_L1') || getAnyById('cURRENT');\n const cL2 = getAnyById('cURRENT_L2');\n const cL3 = getAnyById('cURRENT_L3');\n\n if (vL1) add({ relId: this._aliasRelId('r.voltageL1'), name: 'Voltage L1', role: 'value.voltage', type: 'number', unit: vL1.unit || 'V', rw: 'ro', kind: 'dp', dpId: vL1.id });\n if (vL2) add({ relId: this._aliasRelId('r.voltageL2'), name: 'Voltage L2', role: 'value.voltage', type: 'number', unit: vL2.unit || 'V', rw: 'ro', kind: 'dp', dpId: vL2.id });\n if (vL3) add({ relId: this._aliasRelId('r.voltageL3'), name: 'Voltage L3', role: 'value.voltage', type: 'number', unit: vL3.unit || 'V', rw: 'ro', kind: 'dp', dpId: vL3.id });\n\n if (cL1) add({ relId: this._aliasRelId('r.currentL1'), name: 'Current L1', role: 'value.current', type: 'number', unit: cL1.unit || 'A', rw: 'ro', kind: 'dp', dpId: cL1.id });\n if (cL2) add({ relId: this._aliasRelId('r.currentL2'), name: 'Current L2', role: 'value.current', type: 'number', unit: cL2.unit || 'A', rw: 'ro', kind: 'dp', dpId: cL2.id });\n if (cL3) add({ relId: this._aliasRelId('r.currentL3'), name: 'Current L3', role: 'value.current', type: 'number', unit: cL3.unit || 'A', rw: 'ro', kind: 'dp', dpId: cL3.id });\n\n const freqDp = getAnyById('fREQUENCY');\n if (freqDp) {\n add({\n relId: this._aliasRelId('r.frequency'),\n name: 'Frequency',\n role: 'value.frequency',\n type: 'number',\n unit: freqDp.unit || 'Hz',\n rw: 'ro',\n kind: 'dp',\n dpId: freqDp.id,\n });\n }\n }\n\n // --- Canonical-only solar / DC charger aliases (CHARGER / DC_CHARGER) ---\n // The old aliases.* namespace remains exactly as it was before Alias Contract v1.\n // Additional solar-charger discovery paths are therefore generated only for v1.\n if (cat === 'CHARGER' || cat === 'DC_CHARGER') {\n const powerDp =\n getAnyById('aCTUAL_POWER', 'pV_POWER', 'cHARGE_POWER', 'oUTPUT_POWER') ||\n this._findFirstDatapoint(dp => dp && dp.rw !== 'wo' && dp.role === 'value.power');\n if (powerDp) {\n addStandardSource({\n relId: this._aliasRelId('r.power'),\n name: 'Charger power',\n role: 'value.power',\n type: 'number',\n unit: powerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: powerDp.id,\n });\n }\n\n const energyDp =\n getAnyById('aCTUAL_ENERGY', 'eNERGY_TOTAL', 'tOTAL_ENERGY', 'yIELD_TODAY') ||\n this._findFirstDatapoint(dp => dp && dp.rw !== 'wo' && dp.role === 'value.energy');\n if (energyDp) {\n addStandardSource({\n relId: this._aliasRelId('r.energyTotal'),\n name: 'Charger energy',\n role: 'value.energy',\n type: 'number',\n unit: energyDp.unit || 'Wh',\n rw: 'ro',\n kind: 'dp',\n dpId: energyDp.id,\n });\n }\n\n const voltageDp =\n getAnyById('vOLTAGE', 'pV_VOLTAGE', 'bATTERY_VOLTAGE') ||\n findByIdOrNameRe(/(^|_)(pv|charger|output).*voltage|^voltage$/i);\n if (voltageDp) {\n addStandardSource({\n relId: this._aliasRelId('r.voltage'),\n name: 'Charger voltage',\n role: 'value.voltage',\n type: 'number',\n unit: voltageDp.unit || 'V',\n rw: 'ro',\n kind: 'dp',\n dpId: voltageDp.id,\n });\n }\n\n const currentDp =\n getAnyById('cURRENT', 'pV_CURRENT', 'bATTERY_CURRENT') ||\n findByIdOrNameRe(/(^|_)(pv|charger|output).*current|^current$/i);\n if (currentDp) {\n addStandardSource({\n relId: this._aliasRelId('r.current'),\n name: 'Charger current',\n role: 'value.current',\n type: 'number',\n unit: currentDp.unit || 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentDp.id,\n });\n }\n\n const temperatureDp =\n getAnyById('bATTERY_TEMPERATURE', 'cHARGER_TEMPERATURE', 'tEMPERATURE') ||\n findByIdOrNameRe(/temperature|temperatur/i);\n if (temperatureDp) {\n addStandardSource({\n relId: this._aliasRelId('r.temperature'),\n name: 'Charger temperature',\n role: 'value.temperature',\n type: 'number',\n unit: temperatureDp.unit || '°C',\n rw: 'ro',\n kind: 'dp',\n dpId: temperatureDp.id,\n });\n }\n\n const statusDp =\n getAnyById('cHARGE_STATE', 'cHARGER_STATE', 'sTATUS', 'sTATE') ||\n findByIdOrNameRe(/charge.*state|charger.*state|status/i);\n if (statusDp) {\n addStandardSource({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Charger status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: statusDp.id,\n });\n }\n\n const errorDp =\n getAnyById('eRROR_CODE', 'fAULT_CODE') ||\n findByIdOrNameRe(/error.*code|fault.*code/i);\n if (errorDp) {\n addStandardSource({\n relId: this._aliasRelId('r.errorCode'),\n name: 'Charger error code',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: errorDp.id,\n });\n addStandardSource({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Charger fault',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const n = Number(values && values[errorDp.id]);\n return Number.isFinite(n) ? n !== 0 : false;\n },\n });\n }\n }\n\n // --- Charging station aliases (EVCS/EVSE/CHARGER/DC_CHARGER) ---\n if (chargerCats.has(cat)) {\n // Read: power\n const chargingPowerDp =\n getAnyById('aCTIVE_POWER') ||\n findByIdRe(/charging_power/i) ||\n findByIdRe(/power_W$/i) ||\n this._findFirstDatapoint(dp => dp.role === 'value.power' && dp.rw !== 'wo' && !/^station_/i.test(String(dp.id))) ||\n this._findFirstDatapoint(dp => dp.role === 'value.power' && dp.rw !== 'wo');\n\n if (chargingPowerDp) {\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Charging power',\n role: 'value.power',\n type: 'number',\n unit: chargingPowerDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: chargingPowerDp.id,\n });\n }\n\n // Read: energy session / total\n const makeEvcsEnergyAlias = (dp, aliasPath, name) => {\n if (!dp) return null;\n const srcUnit = String(dp.unit || '').trim();\n const unitLower = srcUnit.toLowerCase().replace(/\\s+/g, '');\n\n // Frontend/charge-management API convention: EVCS energy aliases are exposed in kWh.\n // A number of Modbus wallboxes (MENNEKES AMTRON, KEBA P40, etc.) report native energy\n // counters in Wh/0.1Wh. Keep vendor datapoints faithful to the template, but normalize\n // aliases so dashboards do not render Wh values as kWh.\n let factor = 1;\n let aliasUnit = srcUnit || 'kWh';\n if (unitLower === 'wh') {\n factor = 1 / 1000;\n aliasUnit = 'kWh';\n } else if (unitLower === '0.1wh' || unitLower === '0,1wh') {\n factor = 1 / 10000;\n aliasUnit = 'kWh';\n } else if (!srcUnit) {\n aliasUnit = 'kWh';\n }\n\n const def = {\n relId: this._aliasRelId(aliasPath),\n name,\n role: 'value.energy',\n type: 'number',\n unit: aliasUnit,\n rw: 'ro',\n kind: 'dp',\n dpId: dp.id,\n };\n\n if (factor !== 1) {\n def.fromDevice = (v) => {\n if (v === null || v === undefined) return v;\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n return roundTo(n * factor, 3);\n };\n }\n return def;\n };\n\n const energySessionDp =\n getAnyById('eNERGY_SESSION', 'lAST_ENERGY_SESSION') ||\n findByIdRe(/charged_energy_session/i) ||\n findByIdRe(/energy.*session/i) ||\n findByIdOrNameRe(/energy.*session/i);\n\n if (energySessionDp) {\n add(makeEvcsEnergyAlias(energySessionDp, 'r.energySession', 'Energy (session)'));\n }\n\n const energyTotalDp =\n findByIdRe(/total.*charged.*energy/i) ||\n findByIdRe(/total_charged_energy/i) ||\n findByIdRe(/total.*energy/i) ||\n getAnyById('aCTIVE_PRODUCTION_ENERGY') ||\n this._findFirstDatapoint(dp => dp.role === 'value.energy' && dp.rw !== 'wo' && !/session/i.test(String(dp.id || '') + ' ' + String(dp.name || '')));\n\n if (energyTotalDp) {\n add(makeEvcsEnergyAlias(energyTotalDp, 'r.energyTotal', 'Energy (total)'));\n }\n\n // --- Alfen NG9xx/ACE special aliases ---\n // Alfen exposes live socket control mainly through the \"Modbus Server Max Current\"\n // setpoint. There is no dedicated start/stop boolean in the Modbus map: charging is\n // released by writing a valid current (normally >= 6 A) and blocked by writing 0 A.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const mfrLower = String(this.template?.manufacturer || '').toLowerCase();\n const isAlfenAce = mfrLower === 'alfen' || tplIdLower.includes('alfen.ng9xx') || tplIdLower.includes('alfen');\n if (isAlfenAce) {\n const toNum = (v) => {\n if (typeof this._parseNumberWithUnits === 'function') return this._parseNumberWithUnits(v);\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string') {\n const n = Number(v.trim().replace(',', '.'));\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n };\n\n const commandNumber = (v) => toNum(v);\n\n const cleanMode3 = (v) => String(v ?? '')\n .replace(/\\u0000/g, '')\n .trim()\n .toUpperCase();\n\n const mode3Map = {\n A: { code: 0, label: 'No vehicle' },\n B1: { code: 1, label: 'Vehicle connected, not ready' },\n B2: { code: 2, label: 'Vehicle connected, ready' },\n C1: { code: 3, label: 'Vehicle connected, waiting for charging' },\n C2: { code: 4, label: 'Charging' },\n D1: { code: 5, label: 'Vehicle connected, ventilation required' },\n D2: { code: 6, label: 'Charging, ventilation required' },\n E: { code: 7, label: 'Error' },\n F: { code: 8, label: 'Error' },\n };\n\n const mode3StateCodeStates = {\n 0: 'No vehicle (A)',\n 1: 'Vehicle connected, not ready (B1)',\n 2: 'Vehicle connected, ready (B2)',\n 3: 'Vehicle connected, waiting for charging (C1)',\n 4: 'Charging (C2)',\n 5: 'Vehicle connected, ventilation required (D1)',\n 6: 'Charging, ventilation required (D2)',\n 7: 'Error (E)',\n 8: 'Error (F)',\n };\n\n const mode3Info = (v) => {\n const sMode = cleanMode3(v);\n if (!sMode) return null;\n const base = mode3Map[sMode];\n if (base) return { raw: sMode, code: base.code, label: base.label, text: `${base.label} (${sMode})` };\n return { raw: sMode, code: undefined, label: sMode, text: sMode };\n };\n\n const mode3Code = (v) => {\n const info = mode3Info(v);\n return info && Number.isFinite(info.code) ? info.code : undefined;\n };\n\n const mode3Text = (v) => {\n const info = mode3Info(v);\n return info ? info.text : 'Unknown';\n };\n\n const isVehicleConnectedMode = (v) => {\n const sMode = cleanMode3(v);\n return ['B1', 'B2', 'C1', 'C2', 'D1', 'D2'].includes(sMode);\n };\n\n const isChargingMode = (v) => {\n const sMode = cleanMode3(v);\n return sMode === 'C2' || sMode === 'D2';\n };\n\n const availabilityDp = getAnyById('eVSE_STATE');\n const mode3Dp = getAnyById('mODE3_STATE');\n const setCurrentDp = getAnyById('sET_CHARGING_CURRENT');\n const appliedCurrentDp = getAnyById('aCTUAL_APPLIED_MAX_CURRENT');\n const validTimeDp = getAnyById('mODBUS_MAX_CURRENT_VALID_TIME');\n const safeCurrentDp = getAnyById('aCTIVE_LOAD_BALANCING_SAFE_CURRENT');\n const accountedDp = getAnyById('sETPOINT_ACCOUNTED_FOR');\n const phasesDp = getAnyById('cHARGE_USING_PHASES');\n const scnAllCurrentDp = getAnyById('sCN_MAX_CURRENT');\n const scnCurrentL1Dp = getAnyById('sCN_MAX_CURRENT_L1');\n const scnCurrentL2Dp = getAnyById('sCN_MAX_CURRENT_L2');\n const scnCurrentL3Dp = getAnyById('sCN_MAX_CURRENT_L3');\n const scnActualCurrentL1Dp = getAnyById('sCN_ACTUAL_MAX_CURRENT_L1');\n const scnActualCurrentL2Dp = getAnyById('sCN_ACTUAL_MAX_CURRENT_L2');\n const scnActualCurrentL3Dp = getAnyById('sCN_ACTUAL_MAX_CURRENT_L3');\n const scnValidTimeL1Dp = getAnyById('sCN_REMAINING_VALID_TIME_L1');\n const scnValidTimeL2Dp = getAnyById('sCN_REMAINING_VALID_TIME_L2');\n const scnValidTimeL3Dp = getAnyById('sCN_REMAINING_VALID_TIME_L3');\n const scnEnableDp = getAnyById('sCN_MAX_CURRENT_ENABLE');\n const scnRemainingValidTimeL1Dp = getAnyById('sCN_REMAINING_VALID_TIME_L1');\n const scnSafeCurrentDp = getAnyById('sCN_SAFE_CURRENT');\n const scnMaxCurrentEnableDp = getAnyById('sCN_MAX_CURRENT_ENABLE');\n\n const alfenHints = this._getAlfenHints ? this._getAlfenHints() : {};\n const runCurrentRaw = Number(alfenHints.runCurrentA ?? alfenHints.defaultEnableCurrentA ?? 6);\n const runCurrentA = Number.isFinite(runCurrentRaw) && runCurrentRaw > 0 ? runCurrentRaw : 6;\n const stopCurrentRaw = Number(alfenHints.stopCurrentA ?? 0);\n const stopCurrentA = Number.isFinite(stopCurrentRaw) && stopCurrentRaw >= 0 ? stopCurrentRaw : 0;\n const powerThresholdWRaw = Number(alfenHints.chargingPowerThresholdW ?? 50);\n const powerThresholdW = Number.isFinite(powerThresholdWRaw) && powerThresholdWRaw >= 0 ? powerThresholdWRaw : 50;\n const minRunCurrentRaw = Number(alfenHints.minRunCurrentA ?? alfenHints.positiveCurrentMinA ?? alfenHints.minimumRunCurrentA ?? 6);\n const minRunCurrentA = Number.isFinite(minRunCurrentRaw) && minRunCurrentRaw > 0 ? Math.round(minRunCurrentRaw) : 6;\n const normalizeAlfenCurrentCommand = (amp) => {\n const n = Number(amp);\n if (!Number.isFinite(n)) return undefined;\n const rounded = Math.round(n);\n if (rounded <= 0) return 0;\n if (rounded < minRunCurrentA) return minRunCurrentA;\n if (rounded > 80) return 80;\n return rounded;\n };\n const alfenControlMode = String(alfenHints.controlMode || '').toLowerCase();\n const preferScnControl = !!(scnAllCurrentDp && (alfenControlMode === 'scn' || alfenHints.scnPrimaryControl === true || tplIdLower.includes('.scn.')));\n const primaryCurrentWriteDp = preferScnControl ? scnAllCurrentDp : setCurrentDp;\n // Readback and command are separate on Alfen. In Socket mode 1206..1207 is the\n // applied socket max current and 1210..1211 is the writable socket setpoint.\n // In SCN/Station mode the effective current is the SCN Actual Max Current\n // registers 1411..1416 and the writable setpoint is SCN Max Current 1417..1422.\n const primaryCurrentReadDp = preferScnControl ? (scnActualCurrentL1Dp || appliedCurrentDp || scnAllCurrentDp) : (appliedCurrentDp || setCurrentDp);\n const primaryValidTimeDp = preferScnControl ? (scnRemainingValidTimeL1Dp || validTimeDp) : validTimeDp;\n const primarySafeCurrentDp = preferScnControl ? (scnSafeCurrentDp || safeCurrentDp) : safeCurrentDp;\n const primaryAccountedDp = preferScnControl ? (scnMaxCurrentEnableDp || accountedDp) : accountedDp;\n\n // Alfen All-IDs templates expose Socket-1, Socket-2 and Station/SCN data in one\n // object tree. Socket-1 remains the stable primary control path unless the\n // template explicitly asks for SCN control. These helpers must be defined before\n // aliases are built; otherwise the Alfen-specific alias block silently aborts and\n // falls back to generic aliases, which makes manual writes look accepted while the\n // 5 s watchdog does not actually hold the intended command.\n const allIdsControl = !!(\n alfenControlMode === 'allidssocketprimary' ||\n alfenControlMode === 'all-ids' ||\n alfenControlMode === 'allids' ||\n String(alfenHints.safeDefaultMode || '').toLowerCase() === 'all-ids' ||\n tplIdLower.includes('.station.') ||\n String(this.template?.model || '').toLowerCase().includes('all ids')\n );\n\n const normalizeAlfenValidTimeS = (v) => {\n const n = toNum(v);\n if (!Number.isFinite(n) || n < 0) return undefined;\n // Alfen default is 60 s. Field logs showed 26214 s when the register was\n // not really usable for the active control mode; do not use such values to\n // mark the charger as released. Native DP stays untouched; only the alias is\n // normalized for EOS/UI decisions.\n if (n > 3600) return undefined;\n return Math.trunc(n);\n };\n\n const scnEnabledValue = (values) => {\n const n = scnMaxCurrentEnableDp ? toNum(values && values[scnMaxCurrentEnableDp.id]) : undefined;\n return Number.isFinite(n) && Math.trunc(n) === 1;\n };\n\n const scnActualLimitValue = (values) => {\n const vals = [scnActualCurrentL1Dp, scnActualCurrentL2Dp, scnActualCurrentL3Dp]\n .map(dp => dp ? toNum(values && values[dp.id]) : undefined)\n .filter(Number.isFinite);\n if (!vals.length) return undefined;\n return Math.min(...vals);\n };\n\n const scnRemainingValidTimeValue = (values) => {\n const vals = [scnValidTimeL1Dp, scnValidTimeL2Dp, scnValidTimeL3Dp]\n .map(dp => dp ? normalizeAlfenValidTimeS(values && values[dp.id]) : undefined)\n .filter(Number.isFinite);\n if (!vals.length) return undefined;\n return Math.min(...vals);\n };\n\n const getChargingPowerW = (values) => {\n if (!chargingPowerDp || !values) return undefined;\n const p = toNum(values[chargingPowerDp.id]);\n return Number.isFinite(p) ? p : undefined;\n };\n const isChargingByPower = (values) => {\n const p = getChargingPowerW(values);\n return Number.isFinite(p) ? p > powerThresholdW : undefined;\n };\n\n // Some Alfen/ACE installations with newer/limited meters expose only a subset of the\n // socket measurement map. Keep the stable total-energy alias useful by taking the first\n // finite value from the two relevant meter counters instead of binding it to one DP only.\n const energyDeliveredSumDp = getAnyById('tOTAL_CHARGED_ENERGY');\n const energyConsumedSumDp = getAnyById('eNERGY_CONSUMED_SUM');\n if (energyDeliveredSumDp || energyConsumedSumDp) {\n add({\n relId: this._aliasRelId('r.energyTotal'),\n name: 'Energy (total)',\n role: 'value.energy',\n type: 'number',\n // Alfen ACE meter energy counters are documented as Wh. EOS/frontends\n // expect EVCS energy aliases in kWh, so normalize here instead of\n // exposing raw Wh through the alias layer.\n unit: 'kWh',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const normalizeEnergyToKwh = (dp, v) => {\n const n = toNum(v);\n if (!Number.isFinite(n)) return undefined;\n const u = String(dp && dp.unit || '').trim().toLowerCase().replace(/\\s+/g, '');\n if (u === 'wh') return roundTo(n / 1000, 3);\n if (u === '0.1wh' || u === '0,1wh') return roundTo(n / 10000, 3);\n // Alfen template datapoints are already scaled to kWh as of 0.5.116.\n return roundTo(n, 3);\n };\n const delivered = energyDeliveredSumDp ? normalizeEnergyToKwh(energyDeliveredSumDp, values && values[energyDeliveredSumDp.id]) : undefined;\n if (Number.isFinite(delivered)) return delivered;\n const consumed = energyConsumedSumDp ? normalizeEnergyToKwh(energyConsumedSumDp, values && values[energyConsumedSumDp.id]) : undefined;\n if (Number.isFinite(consumed)) return consumed;\n return undefined;\n },\n });\n }\n\n if (mode3Dp) {\n add({\n relId: this._aliasRelId('r.mode3State'),\n name: 'Mode 3 state',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'dp',\n dpId: mode3Dp.id,\n fromDevice: (v) => mode3Text(v),\n });\n\n add({\n relId: this._aliasRelId('r.mode3Code'),\n name: 'Mode 3 code',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'dp',\n dpId: mode3Dp.id,\n fromDevice: (v) => cleanMode3(v),\n });\n\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Status code',\n role: 'indicator.status',\n type: 'number',\n states: mode3StateCodeStates,\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values, ctx) => {\n const n = mode3Code(values && values[mode3Dp.id]);\n if (Number.isFinite(n)) return n;\n const a = availabilityDp ? toNum(values && values[availabilityDp.id]) : undefined;\n if (Number.isFinite(a)) return a;\n const chg = isChargingByPower(values);\n if (chg === true) return 4; // C2-like: charging, derived from measured power\n if (chg === false && ctx && ctx.connected) return 1; // online/idle fallback\n return undefined;\n },\n });\n\n const getAlfenStatusText = (values, ctx) => {\n const raw = values && values[mode3Dp.id];\n const sMode = cleanMode3(raw);\n\n // Alfen exposes whether the received socket setpoint is accounted for.\n // If it is false while an active current command exists, the charger is\n // not using our socket/EMS command (common reasons: Socket vs SCN mode\n // mismatch, Enable sockets/SCN disabled, or another controller/backoffice\n // wins). Surface that instead of hiding it behind a generic charging state.\n const accounted = accountedDp ? toNum(values && values[accountedDp.id]) : undefined;\n const cmdKey = primaryCurrentWriteDp && primaryCurrentWriteDp.id ? String(primaryCurrentWriteDp.id) : '';\n const cmdVal = cmdKey && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(cmdKey)\n ? toNum(this._lastCommandedValueByDpId.get(cmdKey))\n : undefined;\n if (Number.isFinite(cmdVal) && cmdVal > 0.1 && accounted === 0) {\n const applied = appliedCurrentDp ? toNum(values && values[appliedCurrentDp.id]) : undefined;\n const suffix = Number.isFinite(applied) ? `; applied ${roundTo(applied, 2)} A` : '';\n return `Charging / EMS setpoint not accounted${suffix}`;\n }\n\n if (sMode) return mode3Text(sMode);\n const a = availabilityDp ? toNum(values && values[availabilityDp.id]) : undefined;\n if (a === 1) return 'Operative';\n if (a === 0) return 'Inoperative';\n const chg = isChargingByPower(values);\n if (chg === true) return 'Charging (derived from power)';\n if (chg === false && ctx && ctx.connected) return 'Online / idle (derived from power)';\n return undefined;\n };\n\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'Status text',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: getAlfenStatusText,\n });\n\n // A few dashboards look for aliases.r.status instead of aliases.r.statusText.\n // Keep both in sync and make both human-readable (not just IEC code \"A\").\n add({\n relId: this._aliasRelId('r.status'),\n name: 'Status',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: getAlfenStatusText,\n });\n\n add({\n relId: this._aliasRelId('r.vehicleConnected'),\n name: 'Vehicle connected',\n role: 'indicator.connected',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const raw = values && values[mode3Dp.id];\n const sMode = cleanMode3(raw);\n if (sMode) return isVehicleConnectedMode(sMode);\n const chg = isChargingByPower(values);\n // Without Mode3 we cannot distinguish \"car connected but idle\" from \"no car\".\n // A positive measured charging power is, however, a safe indicator for connected.\n return chg === true ? true : undefined;\n },\n });\n\n add({\n relId: this._aliasRelId('r.charging'),\n name: 'Charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const raw = values && values[mode3Dp.id];\n const sMode = cleanMode3(raw);\n if (sMode) return isChargingMode(sMode);\n return isChargingByPower(values);\n },\n });\n }\n\n if (availabilityDp) {\n add({\n relId: this._aliasRelId('r.available'),\n name: 'EVSE available / operative',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values, ctx) => {\n const n = availabilityDp ? toNum(values && values[availabilityDp.id]) : undefined;\n if (Number.isFinite(n)) return n === 1;\n // Some ACE profiles expose meter values but not the socket status/control\n // block 1200..1215. Keep the alias useful by falling back to connectivity.\n return !!(ctx && ctx.connected);\n },\n });\n }\n\n if (primaryCurrentReadDp) {\n add({\n relId: this._aliasRelId('r.appliedCurrentLimitA'),\n name: allIdsControl ? 'Effective actual applied max current' : (preferScnControl ? 'SCN actual applied max current' : 'Actual applied max current'),\n role: 'value.current',\n type: 'number',\n unit: primaryCurrentReadDp.unit || 'A',\n rw: 'ro',\n kind: allIdsControl ? 'computed' : 'dp',\n dpId: allIdsControl ? undefined : primaryCurrentReadDp.id,\n replace: true,\n get: allIdsControl ? ((values) => {\n // In All-IDs mode the charger may be configured either for Socket control\n // or SCN control. If SCN Max Current is enabled, the socket-level\n // setpoint-accounted flag can remain false even though the SCN limit is the\n // real effective limit. Prefer SCN actual current when the SCN enable flag is set.\n const scn = scnEnabledValue(values) ? scnActualLimitValue(values) : undefined;\n if (Number.isFinite(scn)) return roundTo(scn, 2);\n const socket = primaryCurrentReadDp ? toNum(values && values[primaryCurrentReadDp.id]) : undefined;\n return Number.isFinite(socket) ? roundTo(socket, 2) : undefined;\n }) : undefined,\n });\n }\n\n if (primaryValidTimeDp) {\n add({\n relId: this._aliasRelId('r.currentLimitValidTimeS'),\n name: allIdsControl ? 'Effective current-limit valid time remaining' : (preferScnControl ? 'SCN current-limit valid time remaining' : 'Current-limit valid time remaining'),\n role: 'value',\n type: 'number',\n unit: primaryValidTimeDp.unit || 's',\n rw: 'ro',\n kind: allIdsControl ? 'computed' : 'dp',\n dpId: allIdsControl ? undefined : primaryValidTimeDp.id,\n replace: true,\n fromDevice: allIdsControl ? undefined : normalizeAlfenValidTimeS,\n get: allIdsControl ? ((values) => {\n const scn = scnEnabledValue(values) ? scnRemainingValidTimeValue(values) : undefined;\n if (Number.isFinite(scn)) return scn;\n return normalizeAlfenValidTimeS(primaryValidTimeDp ? values && values[primaryValidTimeDp.id] : undefined);\n }) : undefined,\n });\n }\n\n if (primarySafeCurrentDp) {\n add({\n relId: this._aliasRelId('r.safeCurrentA'),\n name: preferScnControl ? 'SCN safe current' : 'Active Load Balancing safe current',\n role: 'value.current',\n type: 'number',\n unit: primarySafeCurrentDp.unit || 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: primarySafeCurrentDp.id,\n replace: true,\n });\n }\n\n if (primaryAccountedDp) {\n add({\n relId: this._aliasRelId('r.setpointAccountedFor'),\n name: preferScnControl ? 'SCN max-current enabled/accounted' : 'Setpoint accounted for',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: primaryAccountedDp.id,\n replace: true,\n fromDevice: (v) => {\n const n = toNum(v);\n return Number.isFinite(n) ? n !== 0 : undefined;\n },\n });\n }\n\n if ((preferScnControl || allIdsControl) && accountedDp) {\n add({\n relId: this._aliasRelId('r.socketSetpointAccountedFor'),\n name: 'Socket setpoint accounted for',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: accountedDp.id,\n fromDevice: (v) => {\n const n = toNum(v);\n return Number.isFinite(n) ? n !== 0 : undefined;\n },\n });\n }\n\n if ((preferScnControl || allIdsControl) && scnMaxCurrentEnableDp) {\n add({\n relId: this._aliasRelId('r.scnMaxCurrentEnabled'),\n name: 'SCN max-current enabled',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: scnMaxCurrentEnableDp.id,\n fromDevice: (v) => {\n const n = toNum(v);\n return Number.isFinite(n) ? n !== 0 : undefined;\n },\n });\n }\n\n if (allIdsControl && (accountedDp || scnMaxCurrentEnableDp)) {\n add({\n relId: this._aliasRelId('r.controlAccepted'),\n name: 'EMS control accepted by active Alfen mode',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const socketAcc = accountedDp ? toNum(values && values[accountedDp.id]) : undefined;\n const scnEn = scnMaxCurrentEnableDp ? toNum(values && values[scnMaxCurrentEnableDp.id]) : undefined;\n if (Number.isFinite(scnEn) && Math.trunc(scnEn) === 1) return true;\n if (Number.isFinite(socketAcc)) return Math.trunc(socketAcc) !== 0;\n return undefined;\n },\n });\n }\n\n if (phasesDp) {\n add({\n relId: this._aliasRelId('ctrl.phaseMode'),\n name: 'Charge using phases',\n role: 'level',\n type: 'number',\n unit: phasesDp.unit || 'phases',\n rw: 'rw',\n kind: 'dp',\n dpId: phasesDp.id,\n writeDpId: phasesDp.id,\n preferCommandValue: true,\n commandOnlyAlias: true,\n toDevice: (v) => {\n // Safety: only explicit 1 or 3 are valid Alfen phase commands.\n // Accept UI strings such as \"3 phases\" / \"3-phasig\" as well,\n // but do NOT coerce false/0/undefined/NaN to 3 phases.\n if (typeof v === 'string') {\n const m = v.trim().match(/^([13])(?:\\D|$)/);\n if (m) return Number(m[1]);\n }\n const parsed = commandNumber(v);\n const n = Math.trunc(Number(parsed));\n if (n === 1) return 1;\n if (n === 3) return 3;\n return undefined;\n },\n fromDevice: (v) => {\n const n = Math.trunc(Number(v));\n return n === 1 ? 1 : (n === 3 ? 3 : undefined);\n },\n });\n }\n\n if (primaryCurrentWriteDp && (primaryCurrentWriteDp.rw === 'rw' || primaryCurrentWriteDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: preferScnControl ? 'SCN charging current limit' : 'Charging current limit',\n role: 'level.current',\n type: 'number',\n unit: primaryCurrentWriteDp.unit || 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: (primaryCurrentReadDp && primaryCurrentReadDp.id) || primaryCurrentWriteDp.id,\n writeDpId: primaryCurrentWriteDp.id,\n preferCommandValue: true,\n commandOnlyAlias: true,\n toDevice: (v) => {\n const n = commandNumber(v);\n return normalizeAlfenCurrentCommand(n);\n },\n fromDevice: (v) => {\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n },\n });\n\n if (primaryCurrentWriteDp) {\n const nominalVoltage = Number(alfenHints.nominalVoltageV ?? 230);\n const voltageV = Number.isFinite(nominalVoltage) && nominalVoltage > 0 ? nominalVoltage : 230;\n const resolvePhaseForPowerCommand = () => {\n const phaseKey = phasesDp && phasesDp.id ? String(phasesDp.id) : '';\n const lastPhase = phaseKey && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(phaseKey)\n ? Math.trunc(Number(this._lastCommandedValueByDpId.get(phaseKey)))\n : NaN;\n if (lastPhase === 1 || lastPhase === 3) return lastPhase;\n return Math.trunc(Number(alfenHints.defaultPhaseMode ?? 3)) === 1 ? 1 : 3;\n };\n add({\n relId: this._aliasRelId('ctrl.powerLimitW'),\n name: preferScnControl ? 'SCN charging power limit' : 'Charging power limit',\n role: 'level.power',\n type: 'number',\n unit: 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: (primaryCurrentReadDp && primaryCurrentReadDp.id) || primaryCurrentWriteDp.id,\n writeDpId: primaryCurrentWriteDp.id,\n preferCommandValue: true,\n commandOnlyAlias: true,\n toDevice: (v) => {\n const w = commandNumber(v);\n if (!Number.isFinite(w)) return undefined;\n if (w <= 0) return 0;\n const phases = resolvePhaseForPowerCommand();\n const amp = Math.round(w / (voltageV * phases));\n return normalizeAlfenCurrentCommand(amp);\n },\n fromDevice: (v) => {\n const a = Number(v);\n if (!Number.isFinite(a)) return undefined;\n const phases = resolvePhaseForPowerCommand();\n return Math.round(a * voltageV * phases);\n },\n });\n }\n\n const runAlias = {\n name: preferScnControl ? 'Run / SCN charging release' : 'Run / charging release',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: (primaryCurrentReadDp && primaryCurrentReadDp.id) || primaryCurrentWriteDp.id,\n writeDpId: primaryCurrentWriteDp.id,\n preferCommandValue: true,\n commandOnlyAlias: true,\n toDevice: (v) => {\n const asBool = (typeof v === 'boolean') ? v : (Number.isFinite(commandNumber(v)) ? commandNumber(v) !== 0 : undefined);\n if (asBool === false) return stopCurrentA;\n if (asBool === true) {\n // For Alfen the release switch must not overwrite an already commanded\n // dynamic current limit. Min+PV/PV modes often write 6 A first and then\n // set run=true; returning a hard-coded 16 A here would cancel that 6 A\n // command. Reuse the latest desired current if present, otherwise fall\n // back to the configured release current.\n const key = String(primaryCurrentWriteDp.id);\n const lastCmd = this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(key)\n ? Number(this._lastCommandedValueByDpId.get(key))\n : NaN;\n if (Number.isFinite(lastCmd) && lastCmd > 0.1) return normalizeAlfenCurrentCommand(lastCmd);\n return normalizeAlfenCurrentCommand(runCurrentA);\n }\n return v;\n },\n fromDevice: (v) => {\n const n = Number(v);\n return Number.isFinite(n) ? n > 0.1 : undefined;\n },\n };\n\n add({ relId: this._aliasRelId('ctrl.run'), ...runAlias });\n add({ relId: this._aliasRelId('ctrl.chargeEnable'), ...runAlias, name: preferScnControl ? 'SCN charging release' : 'Charging release' });\n add({\n relId: this._aliasRelId('r.chargingReleased'),\n name: preferScnControl ? 'Charging released by SCN current setpoint' : 'Charging released by current setpoint',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n // This alias must describe the charger-side state, not merely the\n // command requested by EOS. For Socket mode Alfen register 1214\n // (sETPOINT_ACCOUNTED_FOR) is the decisive readback. If it is false,\n // the charger is deliberately not applying the Modbus setpoint, even if\n // the remaining-valid-time register contains a non-zero or bogus value.\n const accounted = primaryAccountedDp ? toNum(values && values[primaryAccountedDp.id]) : (accountedDp ? toNum(values && values[accountedDp.id]) : undefined);\n if (Number.isFinite(accounted)) return accounted !== 0;\n\n const validSRaw = primaryValidTimeDp ? (values && values[primaryValidTimeDp.id]) : (validTimeDp ? values && values[validTimeDp.id] : undefined);\n const validS = normalizeAlfenValidTimeS(validSRaw);\n if (Number.isFinite(validS) && validS > 0) return true;\n\n const applied = primaryCurrentReadDp ? toNum(values && values[primaryCurrentReadDp.id]) : (appliedCurrentDp ? toNum(values && values[appliedCurrentDp.id]) : undefined);\n if (Number.isFinite(applied)) return applied > 0.1;\n\n const cmd = this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(String(primaryCurrentWriteDp.id))\n ? toNum(this._lastCommandedValueByDpId.get(String(primaryCurrentWriteDp.id)))\n : undefined;\n return Number.isFinite(cmd) ? cmd > 0.1 : undefined;\n },\n });\n }\n }\n } catch (e) {\n // Never break generic EVCS alias generation due to Alfen-specific helpers.\n }\n\n // --- KEBA KeContact P40 Modbus special aliases ---\n // KEBA P40 exposes write registers in mA and uses a fixed Modbus/TCP Unit-ID 255.\n // P40 releases charging by writing the Max Current register (5004, mA); 0 mA blocks charging.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const mfrLower = String(this.template?.manufacturer || '').toLowerCase();\n const modelLower = String(this.template?.model || '').toLowerCase();\n const isKebaP40 = (mfrLower === 'keba' || tplIdLower.includes('keba')) && (tplIdLower.includes('keba') || modelLower.includes('p40'));\n if (isKebaP40) {\n const toNum = (v) => {\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string') {\n const n = Number(v.trim());\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n };\n\n const kebaStatusDp = getAnyById('cHARGING_STATE');\n const kebaCableDp = getAnyById('cABLE_STATE');\n const kebaErrorDp = getAnyById('eRROR_CODE');\n const kebaFastChargingStateDp = getAnyById('fAST_CHARGING_STATE');\n const kebaPhaseStateDp = getAnyById('pHASE_SWITCH_STATE');\n const kebaSetCurrentDp = getAnyById('sET_CHARGING_CURRENT');\n const kebaSetEnableDp = getAnyById('sET_ENABLE');\n const kebaSetUnlockDp = getAnyById('sET_UNLOCK_PLUG');\n const kebaSetPhaseSourceDp = getAnyById('sET_PHASE_SWITCH_SOURCE');\n const kebaSetPhaseTriggerDp = getAnyById('sET_TRIGGER_PHASE_SWITCH');\n const kebaSetFailsafeCurrentDp = getAnyById('sET_FAILSAFE_CURRENT');\n const kebaSetFailsafeTimeoutDp = getAnyById('sET_FAILSAFE_TIMEOUT') || getAnyById('wRITE_FAILSAFE_TIMEOUT');\n const kebaActivateFastChargingDp = getAnyById('aCTIVATE_FAST_CHARGING');\n const kebaFailsafeCurrentDp = getAnyById('fAILSAFE_CURRENT_SETTING');\n const kebaFailsafeTimeoutDp = getAnyById('fAILSAFE_TIMEOUT_SETTING');\n const kebaMaxCurrentDp = getAnyById('mAX_CHARGING_CURRENT');\n const kebaMaxSupportedCurrentDp = getAnyById('mAX_SUPPORTED_CURRENT');\n const kebaCurrentL1Dp = getAnyById('currentL1');\n const kebaCurrentL2Dp = getAnyById('currentL2');\n const kebaCurrentL3Dp = getAnyById('currentL3');\n const kebaVoltageL1Dp = getAnyById('voltageL1');\n const kebaVoltageL2Dp = getAnyById('voltageL2');\n const kebaVoltageL3Dp = getAnyById('voltageL3');\n const kebaPowerFactorDp = getAnyById('pOWER_FACTOR');\n\n const kebaCurrentDpIsAmp = (dp) => {\n if (!dp) return false;\n const unit = String(dp.unit || '').trim().toLowerCase();\n if (unit === 'a' || unit === 'amp' || unit === 'ampere') return true;\n const sf = Number(dp.source && dp.source.scaleFactor);\n return Number.isFinite(sf) && sf === -3;\n };\n const kebaCurrentFromDp = (dp, v) => {\n const n = toNum(v);\n if (!Number.isFinite(n)) return undefined;\n return kebaCurrentDpIsAmp(dp) ? n : (n / 1000);\n };\n const kebaCurrentToDp = (dp, v, opts = {}) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n let a = n;\n if (a <= 0) a = 0;\n else {\n const minA = Number(opts.minA ?? 6);\n const maxA = Number(opts.maxA ?? 32);\n if (Number.isFinite(minA) && a < minA) a = minA;\n if (Number.isFinite(maxA) && a > maxA) a = maxA;\n }\n return kebaCurrentDpIsAmp(dp) ? a : Math.round(a * 1000);\n };\n\n const statusText = (n) => ({\n 0: 'Starting',\n 1: 'Not ready for charging',\n 2: 'Ready for charging / waiting for EV',\n 3: 'Charging',\n 4: 'Error',\n 5: 'Charging interrupted / rejected',\n })[Math.trunc(n)] || `Unknown (${Math.trunc(n)})`;\n\n if (kebaStatusDp) {\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaStatusDp.id,\n replace: true,\n });\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'Status text',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const n = toNum(values && values[kebaStatusDp.id]);\n return Number.isFinite(n) ? statusText(n) : '';\n }\n });\n add({\n relId: this._aliasRelId('r.charging'),\n name: 'Charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const n = toNum(values && values[kebaStatusDp.id]);\n if (Number.isFinite(n)) return Math.trunc(n) === 3;\n const p = chargingPowerDp ? toNum(values && values[chargingPowerDp.id]) : undefined;\n return Number.isFinite(p) ? p > 50 : undefined;\n }\n });\n add({\n relId: this._aliasRelId('r.available'),\n name: 'EVCS available / ready',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const n = toNum(values && values[kebaStatusDp.id]);\n if (!Number.isFinite(n)) return undefined;\n const c = Math.trunc(n);\n return c === 2 || c === 3;\n }\n });\n }\n\n if (kebaCableDp) {\n add({\n relId: this._aliasRelId('r.cableState'),\n name: 'Cable state',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaCableDp.id,\n });\n add({\n relId: this._aliasRelId('r.vehicleConnected'),\n name: 'Vehicle connected',\n role: 'indicator.connected',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const n = toNum(values && values[kebaCableDp.id]);\n if (!Number.isFinite(n)) return undefined;\n return [5, 7].includes(Math.trunc(n));\n }\n });\n }\n\n if (kebaCurrentL1Dp) {\n add({ relId: this._aliasRelId('r.currentL1'), name: 'Current L1', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: kebaCurrentL1Dp.id, fromDevice: (v) => kebaCurrentFromDp(kebaCurrentL1Dp, v), replace: true });\n }\n if (kebaCurrentL2Dp) {\n add({ relId: this._aliasRelId('r.currentL2'), name: 'Current L2', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: kebaCurrentL2Dp.id, fromDevice: (v) => kebaCurrentFromDp(kebaCurrentL2Dp, v), replace: true });\n }\n if (kebaCurrentL3Dp) {\n add({ relId: this._aliasRelId('r.currentL3'), name: 'Current L3', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: kebaCurrentL3Dp.id, fromDevice: (v) => kebaCurrentFromDp(kebaCurrentL3Dp, v), replace: true });\n }\n\n if (kebaVoltageL1Dp) {\n add({ relId: this._aliasRelId('r.voltageL1'), name: 'Voltage L1', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: kebaVoltageL1Dp.id, replace: true });\n }\n if (kebaVoltageL2Dp) {\n add({ relId: this._aliasRelId('r.voltageL2'), name: 'Voltage L2', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: kebaVoltageL2Dp.id, replace: true });\n }\n if (kebaVoltageL3Dp) {\n add({ relId: this._aliasRelId('r.voltageL3'), name: 'Voltage L3', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: kebaVoltageL3Dp.id, replace: true });\n }\n if (kebaPowerFactorDp) {\n add({ relId: this._aliasRelId('r.powerFactor'), name: 'Power factor', role: 'value', type: 'number', unit: '%', rw: 'ro', kind: 'dp', dpId: kebaPowerFactorDp.id, replace: true });\n }\n\n if (kebaMaxCurrentDp) {\n add({\n relId: this._aliasRelId('r.currentLimitA'),\n name: 'Charging current limit',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaMaxCurrentDp.id,\n fromDevice: (v) => kebaCurrentFromDp(kebaMaxCurrentDp, v),\n replace: true,\n });\n }\n\n if (kebaMaxSupportedCurrentDp) {\n add({\n relId: this._aliasRelId('r.maxSupportedCurrentA'),\n name: 'Maximum supported current',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaMaxSupportedCurrentDp.id,\n fromDevice: (v) => kebaCurrentFromDp(kebaMaxSupportedCurrentDp, v),\n });\n }\n\n if (kebaErrorDp) {\n add({\n relId: this._aliasRelId('r.errorCode'),\n name: 'EVSE error code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaErrorDp.id,\n replace: true,\n });\n }\n\n if (kebaFastChargingStateDp) {\n add({\n relId: this._aliasRelId('r.fastCharging'),\n name: 'Fast charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaFastChargingStateDp.id,\n fromDevice: (v) => {\n const n = toNum(v);\n return Number.isFinite(n) ? Math.trunc(n) === 1 : undefined;\n },\n });\n }\n\n if (kebaPhaseStateDp) {\n add({\n relId: this._aliasRelId('r.phaseMode'),\n name: 'Charge using phases',\n role: 'value',\n type: 'number',\n unit: 'phases',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaPhaseStateDp.id,\n states: { 1: '1 phase', 3: '3 phases' },\n });\n }\n\n if (kebaFailsafeCurrentDp) {\n add({\n relId: this._aliasRelId('r.failsafeCurrentA'),\n name: 'Failsafe current',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaFailsafeCurrentDp.id,\n fromDevice: (v) => kebaCurrentFromDp(kebaFailsafeCurrentDp, v),\n });\n }\n\n if (kebaFailsafeTimeoutDp) {\n add({\n relId: this._aliasRelId('r.failsafeTimeoutS'),\n name: 'Failsafe timeout',\n role: 'value',\n type: 'number',\n unit: 's',\n rw: 'ro',\n kind: 'dp',\n dpId: kebaFailsafeTimeoutDp.id,\n });\n }\n\n if (kebaSetEnableDp && (kebaSetEnableDp.rw === 'rw' || kebaSetEnableDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.stationEnable'),\n name: 'Enable / disable charging station',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaSetEnableDp.id,\n writeDpId: kebaSetEnableDp.id,\n toDevice: (v) => (v ? 1 : 0),\n fromDevice: (v) => {\n if (typeof v === 'boolean') return v;\n const n = toNum(v);\n return Number.isFinite(n) ? Math.trunc(n) !== 0 : undefined;\n },\n preferCommandValue: true,\n commandOnlyAlias: true,\n });\n }\n\n if (kebaSetUnlockDp && (kebaSetUnlockDp.rw === 'rw' || kebaSetUnlockDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.unlockPlug'),\n name: 'Unlock plug',\n role: 'button',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaSetUnlockDp.id,\n writeDpId: kebaSetUnlockDp.id,\n // KEBA P40 register 5012 supports only value 0 = unlock plug. This is a\n // one-shot command; after a successful command the button alias returns to false.\n toDevice: (v) => (v ? 0 : undefined),\n fromDevice: () => false,\n preferCommandValue: true,\n commandOnlyAlias: true,\n });\n }\n\n if (kebaSetPhaseTriggerDp && (kebaSetPhaseTriggerDp.rw === 'rw' || kebaSetPhaseTriggerDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.phaseMode'),\n name: 'Charge using phases',\n role: 'level',\n type: 'number',\n unit: 'phases',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaPhaseStateDp ? kebaPhaseStateDp.id : kebaSetPhaseTriggerDp.id,\n writeDpId: kebaSetPhaseTriggerDp.id,\n states: { 1: '1 phase', 3: '3 phases' },\n toDevice: (v) => {\n const n = Math.trunc(Number(v));\n if (n === 1) return 0;\n if (n === 3) return 1;\n return v;\n },\n fromDevice: (v) => {\n const n = toNum(v);\n return Number.isFinite(n) ? Math.trunc(n) : undefined;\n },\n preferCommandValue: true,\n });\n }\n\n if (kebaSetFailsafeCurrentDp && (kebaSetFailsafeCurrentDp.rw === 'rw' || kebaSetFailsafeCurrentDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.failsafeCurrentA'),\n name: 'Failsafe current',\n role: 'level.current',\n type: 'number',\n unit: 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaFailsafeCurrentDp ? kebaFailsafeCurrentDp.id : kebaSetFailsafeCurrentDp.id,\n writeDpId: kebaSetFailsafeCurrentDp.id,\n toDevice: (v) => kebaCurrentToDp(kebaSetFailsafeCurrentDp, v),\n fromDevice: (v) => kebaCurrentFromDp(kebaFailsafeCurrentDp || kebaSetFailsafeCurrentDp, v),\n preferCommandValue: true,\n });\n }\n\n if (kebaSetFailsafeTimeoutDp && (kebaSetFailsafeTimeoutDp.rw === 'rw' || kebaSetFailsafeTimeoutDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.failsafeTimeoutS'),\n name: 'Failsafe timeout',\n role: 'level',\n type: 'number',\n unit: 's',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaFailsafeTimeoutDp ? kebaFailsafeTimeoutDp.id : kebaSetFailsafeTimeoutDp.id,\n writeDpId: kebaSetFailsafeTimeoutDp.id,\n preferCommandValue: true,\n });\n }\n\n if (kebaActivateFastChargingDp && (kebaActivateFastChargingDp.rw === 'rw' || kebaActivateFastChargingDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.fastCharge'),\n name: 'Activate fast charging',\n role: 'button',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaActivateFastChargingDp.id,\n writeDpId: kebaActivateFastChargingDp.id,\n // KEBA P40 register 5200 supports only value 1 = activate fast charging. This is a\n // one-shot command; use aliases.r.fastCharging for the actual readback state.\n toDevice: (v) => (v ? 1 : undefined),\n fromDevice: () => false,\n preferCommandValue: true,\n commandOnlyAlias: true,\n });\n }\n\n if (kebaSetCurrentDp && (kebaSetCurrentDp.rw === 'rw' || kebaSetCurrentDp.rw === 'wo')) {\n const toKebaMilliAmp = (v) => kebaCurrentToDp(kebaSetCurrentDp, v);\n const fromKebaMilliAmp = (v) => kebaCurrentFromDp(kebaMaxCurrentDp || kebaSetCurrentDp, v);\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: 'Charging current limit',\n role: 'level.current',\n type: 'number',\n unit: 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaMaxCurrentDp ? kebaMaxCurrentDp.id : kebaSetCurrentDp.id,\n writeDpId: kebaSetCurrentDp.id,\n toDevice: toKebaMilliAmp,\n fromDevice: fromKebaMilliAmp,\n preferCommandValue: true,\n replace: true,\n });\n }\n\n if (kebaSetCurrentDp && (kebaSetCurrentDp.rw === 'rw' || kebaSetCurrentDp.rw === 'wo')) {\n const defaultRunCurrentA = Number(this.template?.driverHints?.keba?.runCurrentA ?? 16);\n const stopCurrentA = Number(this.template?.driverHints?.keba?.stopCurrentA ?? 0);\n const toRunMilliAmp = (v) => {\n const runA = Number.isFinite(defaultRunCurrentA) && defaultRunCurrentA > 0 ? defaultRunCurrentA : 16;\n const stopA = Number.isFinite(stopCurrentA) && stopCurrentA >= 0 ? stopCurrentA : 0;\n if (typeof v === 'boolean') return kebaCurrentToDp(kebaSetCurrentDp, v ? runA : stopA);\n const n = Number(v);\n return Number.isFinite(n) ? kebaCurrentToDp(kebaSetCurrentDp, n ? runA : stopA) : v;\n };\n const runAlias = {\n name: 'Run / charging release',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: kebaMaxCurrentDp ? kebaMaxCurrentDp.id : kebaSetCurrentDp.id,\n writeDpId: kebaSetCurrentDp.id,\n toDevice: toRunMilliAmp,\n fromDevice: (v) => {\n const n = kebaCurrentFromDp(kebaMaxCurrentDp || kebaSetCurrentDp, v);\n return Number.isFinite(n) ? n > 0.1 : undefined;\n },\n preferCommandValue: true,\n replace: true,\n };\n add({ relId: this._aliasRelId('ctrl.run'), ...runAlias });\n add({ relId: this._aliasRelId('ctrl.chargeEnable'), ...runAlias, name: 'Charging release' });\n }\n }\n } catch (e) {\n // Never break generic EVCS alias generation due to KEBA-specific helpers.\n }\n\n // Read: status code (best-effort)\n const statusDp =\n getAnyById('eVSE_STATE', 'cHARGE_POINT_STATE', 'gOE_STATE') ||\n this._findFirstDatapoint(dp => /(^state$|_state$)/i.test(String(dp.id || '')) && dp.rw !== 'wo' && !/^station_/i.test(String(dp.id))) ||\n getAnyById('station_state') ||\n this._findFirstDatapoint(dp => /state/i.test(String(dp.id || '')) && dp.rw !== 'wo');\n\n if (statusDp) {\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: statusDp.id,\n });\n }\n\n // Read: error code -> alarm.fault\n const errorDp =\n getAnyById('eVSE_ERROR_CODE', 'eRROR_CODE') ||\n findByIdRe(/error_code/i) ||\n this._findFirstDatapoint(dp => /error/i.test(String(dp.id || '')) && dp.rw !== 'wo');\n\n // Some devices expose several error-code words/blocks (e.g. Mennekes: 4 x uint32).\n // Use the first one for r.errorCode, but treat any non-zero block as fault.\n const errorDpsForFault = [];\n const pushErrorDp = (dp) => {\n if (!dp || !dp.id) return;\n if (errorDpsForFault.find(x => x.id === dp.id)) return;\n errorDpsForFault.push(dp);\n };\n pushErrorDp(errorDp);\n for (const dp of this.getDatapoints()) {\n if (!dp || !dp.id || dp.rw === 'wo') continue;\n const id = String(dp.id || '');\n if (/^eRROR_CODE(_\\d+)?$/i.test(id) || /error_code/i.test(id)) pushErrorDp(dp);\n }\n\n if (errorDp) {\n add({\n relId: this._aliasRelId('r.errorCode'),\n name: 'Error code',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: errorDp.id,\n });\n\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Fault active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return false;\n for (const edp of errorDpsForFault) {\n const v = values[edp.id];\n if (typeof v === 'number' && v !== 0) return true;\n }\n return false;\n }\n });\n }\n\n\n // --- DEPower Modbus V10.03 AC/DC charge-point aliases ---\n // The stable legacy template IDs still contain `oem` for installed-device compatibility.\n // The supplied register workbook uses one common map for AC wallboxes and DC\n // charging stations. GUN_TYPE selects AC 1-phase, AC 3-phase or DC at runtime.\n // Start/stop is not a 0/1 flag: register Charge command requires 1=start, 2=stop.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const isOemModbusV1003 = tplIdLower.includes('evcs.oem.modbusv1003.connector');\n if (isOemModbusV1003) {\n const toNum = (value) => {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'boolean') return value ? 1 : 0;\n if (typeof value === 'string') {\n const text = value.trim().replace(',', '.');\n if (!text) return undefined;\n const parsed = Number(text);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n };\n const readNumber = (values, dp) => dp ? toNum(values && values[dp.id]) : undefined;\n\n const gunTypeDp = getAnyById('gUN_TYPE');\n const connectorStateDp = getAnyById('eVSE_STATE');\n const universalStateDp = getAnyById('uNIVERSAL_CONNECTOR_STATE');\n const stationStatusDp = getAnyById('sTATION_STATUS');\n const plugStateDp = getAnyById('pLUG_STATE') || getAnyById('uNIVERSAL_CABLE_STATE');\n const errorCodeDp = getAnyById('eRROR_CODE');\n const universalErrorDp = getAnyById('uNIVERSAL_ERROR_CODE');\n const powerDp = getAnyById('aCTIVE_POWER');\n const dcCurrentDp = getAnyById('dC_CURRENT');\n const currentL1Dp = getAnyById('cURRENT_L1');\n const currentL2Dp = getAnyById('cURRENT_L2');\n const currentL3Dp = getAnyById('cURRENT_L3');\n const voltageL1Dp = getAnyById('vOLTAGE_L1');\n const voltageL2Dp = getAnyById('vOLTAGE_L2');\n const voltageL3Dp = getAnyById('vOLTAGE_L3');\n const maxCurrentDp = getAnyById('mAX_SUPPORTED_CURRENT');\n const sessionTimeDp = getAnyById('cHARGING_DURATION');\n const cableCurrentDp = getAnyById('cABLE_CURRENT_LIMIT');\n const setPowerDp = getAnyById('eV_SET_CHARGE_POWER_LIMIT');\n const chargeCommandDp = getAnyById('cHARGE_COMMAND');\n const chargingSocDp = getAnyById('cHARGING_SOC');\n const thresholdRaw = Number(this.template?.driverHints?.oemModbusV1003?.statePowerThresholdW ?? 50);\n const powerThresholdW = Number.isFinite(thresholdRaw) && thresholdRaw >= 0 ? thresholdRaw : 50;\n\n const connectorState = (values) => {\n const direct = readNumber(values, connectorStateDp);\n if (Number.isFinite(direct)) return Math.trunc(direct);\n const fallback = readNumber(values, universalStateDp);\n return Number.isFinite(fallback) ? Math.trunc(fallback) : undefined;\n };\n const errorCode = (values) => {\n const direct = readNumber(values, errorCodeDp);\n if (Number.isFinite(direct)) return Math.trunc(direct);\n const fallback = readNumber(values, universalErrorDp);\n return Number.isFinite(fallback) ? Math.trunc(fallback) : undefined;\n };\n const stateLabel = (state) => ({\n 0: 'Idle',\n 1: 'Prepare',\n 2: 'Charging',\n 3: 'Suspended by EV',\n 4: 'Finished',\n 5: 'Fault',\n 6: 'Reserved',\n 7: 'Unavailable',\n 8: 'Suspended by EVSE',\n })[state] || `Unknown (${state})`;\n\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'Connector status code',\n role: 'indicator.status',\n type: 'number',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => connectorState(values),\n });\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'Connector status',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const state = connectorState(values);\n return Number.isFinite(state) ? stateLabel(state) : '';\n },\n });\n add({\n relId: this._aliasRelId('r.available'),\n name: 'Connector available',\n role: 'indicator.available',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const station = readNumber(values, stationStatusDp);\n const state = connectorState(values);\n if (Number.isFinite(station) && Math.trunc(station) !== 0) return false;\n if (Number.isFinite(state)) return ![5, 7].includes(Math.trunc(state));\n return Number.isFinite(station) ? Math.trunc(station) === 0 : undefined;\n },\n });\n add({\n relId: this._aliasRelId('r.vehicleConnected'),\n name: 'Vehicle connected',\n role: 'indicator.connected',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const plug = readNumber(values, plugStateDp);\n if (Number.isFinite(plug)) return Math.trunc(plug) === 1;\n const state = connectorState(values);\n return Number.isFinite(state) ? [1, 2, 3, 4, 8].includes(Math.trunc(state)) : undefined;\n },\n });\n add({\n relId: this._aliasRelId('r.charging'),\n name: 'Charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const state = connectorState(values);\n if (Number.isFinite(state)) return Math.trunc(state) === 2;\n const power = readNumber(values, powerDp);\n return Number.isFinite(power) ? power > powerThresholdW : undefined;\n },\n });\n add({\n relId: this._aliasRelId('r.chargingReleased'),\n name: 'Charging released by connector state',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const state = connectorState(values);\n // Prepare only confirms that the EV/connector handshake has started. It is\n // not a positive release acknowledgement. Treat Charging and SuspendEV as\n // released; SuspendEVSE remains blocked by the station/EMS.\n return Number.isFinite(state) ? [2, 3].includes(Math.trunc(state)) : undefined;\n },\n });\n add({\n relId: this._aliasRelId('r.errorCode'),\n name: 'Connector error code',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => errorCode(values),\n });\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Connector fault',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const error = errorCode(values);\n if (Number.isFinite(error) && error !== 0) return true;\n const state = connectorState(values);\n if (Number.isFinite(state) && Math.trunc(state) === 5) return true;\n const station = readNumber(values, stationStatusDp);\n return Number.isFinite(station) ? Math.trunc(station) === 2 : false;\n },\n });\n for (const [pathName, phaseDp, label] of [\n ['r.voltageL1', voltageL1Dp, 'Voltage L1'],\n ['r.voltageL2', voltageL2Dp, 'Voltage L2'],\n ['r.voltageL3', voltageL3Dp, 'Voltage L3'],\n ]) {\n if (!phaseDp) continue;\n add({\n relId: this._aliasRelId(pathName),\n name: label,\n role: 'value.voltage',\n type: 'number',\n unit: 'V',\n rw: 'ro',\n kind: 'dp',\n dpId: phaseDp.id,\n replace: true,\n });\n }\n for (const [pathName, phaseDp, label] of [\n ['r.currentL1', currentL1Dp, 'Current L1'],\n ['r.currentL2', currentL2Dp, 'Current L2'],\n ['r.currentL3', currentL3Dp, 'Current L3'],\n ]) {\n if (!phaseDp) continue;\n add({\n relId: this._aliasRelId(pathName),\n name: label,\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: phaseDp.id,\n replace: true,\n });\n }\n\n add({\n relId: this._aliasRelId('r.currentA'),\n name: 'Actual charging current',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const gunType = readNumber(values, gunTypeDp);\n const dc = readNumber(values, dcCurrentDp);\n const phaseValues = [currentL1Dp, currentL2Dp, currentL3Dp]\n .map((dp) => readNumber(values, dp))\n .filter((value) => Number.isFinite(value) && value >= 0);\n if (Math.trunc(gunType) === 3 && Number.isFinite(dc)) return Math.max(0, dc);\n if ([1, 2].includes(Math.trunc(gunType)) && phaseValues.length) return Math.max(...phaseValues);\n const all = phaseValues.slice();\n if (Number.isFinite(dc) && dc >= 0) all.push(dc);\n return all.length ? Math.max(...all) : undefined;\n },\n });\n\n if (chargingSocDp) {\n add({\n relId: this._aliasRelId('r.soc'),\n name: 'Vehicle state of charge',\n role: 'value.battery',\n type: 'number',\n unit: '%',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const n = readNumber(values, chargingSocDp);\n if (!Number.isFinite(n)) return null;\n const soc = Math.round(n);\n // Keep the raw register visible for diagnostics, but do not pass\n // Modbus sentinel/out-of-range values into the NexoWatt UI alias.\n return soc >= 0 && soc <= 100 ? soc : null;\n },\n });\n }\n\n if (maxCurrentDp) {\n add({\n relId: this._aliasRelId('r.maxSupportedCurrentA'),\n name: 'Maximum supported current',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: maxCurrentDp.id,\n replace: true,\n });\n }\n if (sessionTimeDp) {\n add({\n relId: this._aliasRelId('r.sessionTimeS'),\n name: 'Charging session time',\n role: 'value.interval',\n type: 'number',\n unit: 's',\n rw: 'ro',\n kind: 'dp',\n dpId: sessionTimeDp.id,\n replace: true,\n });\n }\n if (cableCurrentDp) {\n add({\n relId: this._aliasRelId('r.proximityCurrentA'),\n name: 'Cable current limit',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: cableCurrentDp.id,\n replace: true,\n });\n }\n if (plugStateDp) {\n add({\n relId: this._aliasRelId('r.cableState'),\n name: 'Plug state',\n role: 'indicator',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: plugStateDp.id,\n replace: true,\n });\n }\n\n if (setPowerDp && (setPowerDp.rw === 'rw' || setPowerDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('r.powerLimitW'),\n name: 'Connector power limit',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: setPowerDp.id,\n replace: true,\n });\n add({\n relId: this._aliasRelId('ctrl.powerLimitW'),\n name: 'Connector charging power limit',\n role: 'level.power',\n type: 'number',\n unit: 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: setPowerDp.id,\n writeDpId: setPowerDp.id,\n commandOnlyAlias: true,\n preferCommandValue: true,\n replace: true,\n toDevice: (value) => {\n const n = toNum(value);\n return Number.isFinite(n) && n >= 0 ? Math.round(n) : undefined;\n },\n fromDevice: (value) => {\n const n = toNum(value);\n return Number.isFinite(n) ? n : undefined;\n },\n });\n }\n\n if (chargeCommandDp && (chargeCommandDp.rw === 'rw' || chargeCommandDp.rw === 'wo')) {\n const runAlias = {\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: chargeCommandDp.id,\n writeDpId: chargeCommandDp.id,\n commandOnlyAlias: true,\n preferCommandValue: true,\n replace: true,\n toDevice: (value) => {\n if (typeof value === 'boolean') return value ? 1 : 2;\n if (typeof value === 'string') {\n const text = value.trim().toLowerCase();\n if (['true', 'on', 'start', 'enable', 'enabled'].includes(text)) return 1;\n if (['false', 'off', 'stop', 'disable', 'disabled'].includes(text)) return 2;\n }\n const n = toNum(value);\n if (!Number.isFinite(n)) return undefined;\n if (Math.trunc(n) === 1) return 1;\n if (Math.trunc(n) === 2 || Math.trunc(n) === 0) return 2;\n return undefined;\n },\n // Command-only aliases are updated from the last command value (1/2),\n // never from the connector state. This prevents Stop=2 from being treated\n // as truthy by a generic 0/1 conversion.\n fromDevice: (value) => {\n const n = toNum(value);\n if (!Number.isFinite(n)) return undefined;\n if (Math.trunc(n) === 1) return true;\n if (Math.trunc(n) === 2) return false;\n return undefined;\n },\n };\n add({ relId: this._aliasRelId('ctrl.run'), name: 'Run / start charging', ...runAlias });\n add({ relId: this._aliasRelId('ctrl.chargeEnable'), name: 'Charging release', ...runAlias });\n }\n }\n } catch (e) {\n // Never break generic EVCS alias generation due to the OEM V10.03 mapping.\n }\n\n // --- MENNEKES AMTRON 4You 500 / 4Business 700 special aliases ---\n // The charging-point-network EMS limit consists of three registers (L1/L2/L3).\n // Expose a single user-friendly alias that writes all three registers with one FC16 block.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const mfrLower = String(this.template?.manufacturer || '').toLowerCase();\n const isMennekesAmtron = (mfrLower === 'mennekes') || tplIdLower.includes('mennekes.amtron4you500');\n if (isMennekesAmtron) {\n const toNum = (v) => {\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string') {\n const n = Number(v.trim());\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n };\n\n const ocppStatusDp = getAnyById('cHARGE_POINT_STATE');\n if (ocppStatusDp) {\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'Status text',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const n = toNum(values && values[ocppStatusDp.id]);\n if (!Number.isFinite(n)) return '';\n return ({\n 0: 'Undefined',\n 1: 'Available',\n 2: 'Preparing',\n 3: 'Charging',\n 4: 'SuspendedEVSE',\n 5: 'SuspendedEV',\n 6: 'Finishing',\n 7: 'Reserved',\n 8: 'Unavailable',\n 9: 'Faulted',\n })[Math.trunc(n)] || `Unknown (${Math.trunc(n)})`;\n }\n });\n }\n\n const vehicleStateDp = getAnyById('vEHICLE_STATE');\n if (vehicleStateDp) {\n add({\n relId: this._aliasRelId('r.vehicleStateText'),\n name: 'Vehicle state text',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const n = toNum(values && values[vehicleStateDp.id]);\n if (!Number.isFinite(n)) return '';\n return ({\n 1: 'A - no EV connected',\n 2: 'B - EV connected, not charging',\n 3: 'C - EV charging',\n 4: 'D - ventilation required',\n 5: 'E - error',\n })[Math.trunc(n)] || `Unknown (${Math.trunc(n)})`;\n }\n });\n }\n\n const netWriteDp = getAnyById('cHARGING_POINT_NETWORK_EMS_CURRENT_LIMIT');\n const netL1 = getAnyById('cHARGING_POINT_NETWORK_EMS_CURRENT_LIMIT_L1');\n const netL2 = getAnyById('cHARGING_POINT_NETWORK_EMS_CURRENT_LIMIT_L2');\n const netL3 = getAnyById('cHARGING_POINT_NETWORK_EMS_CURRENT_LIMIT_L3');\n if (netWriteDp && (netWriteDp.rw === 'rw' || netWriteDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.networkCurrentLimitA'),\n name: 'Charging point network EMS current limit',\n role: 'level.current',\n type: 'number',\n unit: 'A',\n rw: 'rw',\n kind: 'computed',\n writeDpId: netWriteDp.id,\n get: (values) => {\n const vals = [netL1, netL2, netL3]\n .map(dp => dp ? toNum(values && values[dp.id]) : undefined)\n .filter(v => Number.isFinite(v));\n if (!vals.length) return undefined;\n return Math.min(...vals);\n }\n });\n }\n\n const currentLimitDp = getAnyById('sET_CHARGING_CURRENT') || getAnyById('hEMS_CURRENT_LIMIT_A') || getAnyById('hEMS_CURRENT_LIMIT_LEGACY_0_1A') || getAnyById('hEMS_CURRENT_LIMIT_LEGACY_A');\n const powerLimitDp = getAnyById('eV_SET_CHARGE_POWER_LIMIT') || getAnyById('hEMS_POWER_LIMIT_LEGACY');\n const availabilityDp = getAnyById('cHARGE_POINT_AVAILABILITY');\n const chargingPowerAliasDp = chargingPowerDp || getAnyById('aCTIVE_POWER');\n const mennekesHints = (this.template && this.template.driverHints && this.template.driverHints.mennekes) || {};\n const runCurrentRaw = Number(mennekesHints.runCurrentA ?? mennekesHints.defaultEnableCurrentA ?? 16);\n const runCurrentA = Number.isFinite(runCurrentRaw) && runCurrentRaw > 0 ? runCurrentRaw : 16;\n const stopCurrentRaw = Number(mennekesHints.stopCurrentA ?? 0);\n const stopCurrentA = Number.isFinite(stopCurrentRaw) && stopCurrentRaw >= 0 ? stopCurrentRaw : 0;\n const powerThresholdWRaw = Number(mennekesHints.chargingPowerThresholdW ?? 50);\n const powerThresholdW = Number.isFinite(powerThresholdWRaw) && powerThresholdWRaw >= 0 ? powerThresholdWRaw : 50;\n\n if (currentLimitDp && (currentLimitDp.rw === 'rw' || currentLimitDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: 'HEMS current limit',\n role: 'level.current',\n type: 'number',\n unit: currentLimitDp.unit || 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: currentLimitDp.id,\n writeDpId: currentLimitDp.id,\n });\n\n const runAlias = {\n name: 'Charging release',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: currentLimitDp.id,\n writeDpId: currentLimitDp.id,\n toDevice: (v) => {\n const asBool = (typeof v === 'boolean') ? v : (Number.isFinite(Number(v)) ? Number(v) !== 0 : undefined);\n if (asBool === false) return stopCurrentA;\n if (asBool === true) {\n // For MENNEKES the release switch must not overwrite an already commanded\n // dynamic current limit. Min+PV/PV modes often write 6 A first and then\n // set run=true; returning a hard-coded 16 A here would cancel that 6 A\n // command. Reuse the latest desired current if present, otherwise fall\n // back to the configured release current.\n const key = String(currentLimitDp.id);\n const lastCmd = this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(key)\n ? Number(this._lastCommandedValueByDpId.get(key))\n : NaN;\n if (Number.isFinite(lastCmd) && lastCmd > 0.1) return Math.round(lastCmd);\n return runCurrentA;\n }\n return v;\n },\n fromDevice: (v) => {\n const n = Number(v);\n return Number.isFinite(n) ? n > 0.1 : undefined;\n },\n };\n add({ relId: this._aliasRelId('ctrl.run'), ...runAlias });\n add({ relId: this._aliasRelId('ctrl.chargeEnable'), ...runAlias, name: 'Charge enable' });\n add({\n relId: this._aliasRelId('r.chargingReleased'),\n name: 'Charging released by HEMS current limit',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: currentLimitDp.id,\n fromDevice: (v) => {\n const n = Number(v);\n return Number.isFinite(n) ? n > 0.1 : undefined;\n },\n });\n add({\n relId: this._aliasRelId('r.currentLimitA'),\n name: 'HEMS current limit',\n role: 'value.current',\n type: 'number',\n unit: currentLimitDp.unit || 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentLimitDp.id,\n });\n }\n\n if (powerLimitDp && (powerLimitDp.rw === 'rw' || powerLimitDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitW'),\n name: 'HEMS power limit',\n role: 'level.power',\n type: 'number',\n unit: powerLimitDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: powerLimitDp.id,\n writeDpId: powerLimitDp.id,\n });\n add({\n relId: this._aliasRelId('r.powerLimitW'),\n name: 'HEMS power limit',\n role: 'value.power',\n type: 'number',\n unit: powerLimitDp.unit || 'W',\n rw: 'ro',\n kind: 'dp',\n dpId: powerLimitDp.id,\n });\n }\n\n if (vehicleStateDp) {\n add({\n relId: this._aliasRelId('r.vehicleConnected'),\n name: 'Vehicle connected',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const n = toNum(values && values[vehicleStateDp.id]);\n if (!Number.isFinite(n)) return undefined;\n const c = Math.trunc(n);\n return c >= 2 && c <= 4;\n },\n });\n }\n\n add({\n relId: this._aliasRelId('r.charging'),\n name: 'Charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const status = ocppStatusDp ? toNum(values && values[ocppStatusDp.id]) : undefined;\n if (status === 3) return true;\n const veh = vehicleStateDp ? toNum(values && values[vehicleStateDp.id]) : undefined;\n if (veh === 3) return true;\n const p = chargingPowerAliasDp ? toNum(values && values[chargingPowerAliasDp.id]) : undefined;\n if (Number.isFinite(p)) return p > powerThresholdW;\n if (Number.isFinite(status)) return false;\n return undefined;\n },\n });\n\n if (availabilityDp || ocppStatusDp) {\n add({\n relId: this._aliasRelId('r.available'),\n name: 'Charge point available',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const a = availabilityDp ? toNum(values && values[availabilityDp.id]) : undefined;\n if (Number.isFinite(a)) return Math.trunc(a) === 1;\n const s = ocppStatusDp ? toNum(values && values[ocppStatusDp.id]) : undefined;\n if (Number.isFinite(s)) return ![8, 9].includes(Math.trunc(s));\n return undefined;\n },\n });\n }\n\n const safeCurrentDp = getAnyById('sAFE_CURRENT');\n if (safeCurrentDp && (safeCurrentDp.rw === 'rw' || safeCurrentDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.safeCurrentA'),\n name: 'Safe current on HEMS timeout',\n role: 'level.current',\n type: 'number',\n unit: safeCurrentDp.unit || 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: safeCurrentDp.id,\n writeDpId: safeCurrentDp.id,\n });\n }\n\n const timeoutDp = getAnyById('cOMMUNICATION_TIMEOUT');\n if (timeoutDp && (timeoutDp.rw === 'rw' || timeoutDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.communicationTimeoutS'),\n name: 'HEMS communication timeout',\n role: 'level.timer',\n type: 'number',\n unit: timeoutDp.unit || 's',\n rw: 'rw',\n kind: 'dp',\n dpId: timeoutDp.id,\n writeDpId: timeoutDp.id,\n });\n }\n\n const hemsConfigDp = getAnyById('hEMS_CONFIGURATION');\n if (hemsConfigDp) {\n add({\n relId: this._aliasRelId('r.hemsReadWriteEnabled'),\n name: 'HEMS read/write enabled',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => toNum(values && values[hemsConfigDp.id]) === 2,\n });\n }\n\n const hemsCommDp = getAnyById('hEMS_COMMUNICATION_STATUS');\n if (hemsCommDp) {\n add({\n relId: this._aliasRelId('r.hemsCommunicationTimeout'),\n name: 'HEMS communication timeout active',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => toNum(values && values[hemsCommDp.id]) === 1,\n });\n }\n\n\n }\n } catch (e) {\n // Never break alias generation due to special-case logic\n }\n\n\n // --- ABL EVCC2/3 (eMH1) special aliases (Modbus ASCII) ---\n // The EVCC2/3 API does not accept an ampere value at register 0x0014. It accepts\n // IEC 61851 PWM duty cycle in 0.1 % units. NexoWatt therefore keeps amperes at\n // the stable EOS alias and converts them before writing sET_ICMAX_DUTY_CYCLE_PCT.\n // 100 % is the documented normal pause/wait command (\"no current available\").\n // Register 0x0005 remains an expert/service state-transition command only.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const mfrLower = String(this.template?.manufacturer || '').toLowerCase();\n const isAbl = (mfrLower === 'abl') || tplIdLower.startsWith('evcs.abl.');\n if (isAbl) {\n const icmaxDutyPctDp = getAnyById('iCMAX_DUTY_CYCLE_PCT');\n const setIcmaxDutyPctDp = getAnyById('sET_ICMAX_DUTY_CYCLE_PCT');\n\n const evseStateDpAbl = getAnyById('eVSE_STATE');\n\n const toNum = (v) => {\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'boolean') return v ? 1 : 0;\n if (typeof v === 'string') {\n const normalized = v.trim().replace(',', '.');\n if (!normalized) return undefined;\n const direct = Number(normalized);\n if (Number.isFinite(direct)) return direct;\n const match = normalized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (!match) return undefined;\n const n = Number(match[0]);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n };\n const round1 = (v) => {\n if (typeof v !== 'number' || !Number.isFinite(v)) return v;\n return Math.round((v + 1e-9) * 10) / 10;\n };\n // Truncate, rather than round up, so the advertised maximum current never\n // exceeds the ampere limit requested by the EMS. This also reproduces the\n // vendor example 10 A -> 16.6 % -> raw register value 166 exactly.\n const floor1 = (v) => {\n if (typeof v !== 'number' || !Number.isFinite(v)) return v;\n return Math.floor((v + 1e-9) * 10) / 10;\n };\n\n const isAblActiveDutyPct = (value) => {\n const pct = toNum(value);\n return Number.isFinite(pct) && pct >= 10 && pct <= 96;\n };\n\n // Safe direct-PWM alias normalization. Normal analogue charging is 10..96 %;\n // 100 % means no current available. Values in the reserved gaps are mapped to\n // pause instead of accidentally releasing an undefined current.\n const normalizeAblDutyPct = (value) => {\n const pctIn = toNum(value);\n if (!Number.isFinite(pctIn)) return value;\n if (pctIn < 10 || pctIn > 96) return 100;\n return floor1(pctIn);\n };\n\n // IEC 61851 current -> PWM conversion used by ABL register 0x0014.\n // 0 A or any sub-6-A request is represented as 100 % (wait/pause).\n const ablCurrentToDutyPct = (value) => {\n const aIn = toNum(value);\n if (!Number.isFinite(aIn)) return value;\n if (aIn < 6) return 100;\n\n const a = Math.min(80, aIn);\n if (a <= 51) {\n return Math.min(85, Math.max(10, floor1(a / 0.6)));\n }\n\n const highPct = (a / 2.5) + 64;\n // IEC 61851 has a discontinuity between the two formula ranges. For a\n // request below 52.75 A, 85.1 % would advertise more current than requested;\n // hold at the safe 51-A boundary (85 %) until the high range is reachable.\n if (highPct <= 85) return 85;\n return Math.min(96, floor1(highPct));\n };\n\n const ablDutyPctToCurrentA = (value) => {\n const pctIn = toNum(value);\n if (!Number.isFinite(pctIn)) return value;\n if (!isAblActiveDutyPct(pctIn)) return 0;\n\n // 85 % belongs to the 0.6 A/% range. The high-current formula starts\n // strictly above 85 %.\n const a = (pctIn > 85)\n ? (2.5 * (pctIn - 64))\n : (0.6 * pctIn);\n return round1(Math.max(0, a));\n };\n\n const getAblResumeDutyPct = () => {\n if (!setIcmaxDutyPctDp) return 10;\n const key = String(setIcmaxDutyPctDp.id);\n const candidates = [\n this._ablLastActiveDutyPctByDpId && this._ablLastActiveDutyPctByDpId.get(key),\n this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.get(key),\n ];\n for (const candidate of candidates) {\n if (isAblActiveDutyPct(candidate)) return floor1(toNum(candidate));\n }\n // Safe minimum charging release: 10 % = 6 A.\n return 10;\n };\n\n const ablRunToDutyPct = (value) => {\n if (typeof value === 'boolean') return value ? getAblResumeDutyPct() : 100;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n if (['true', 'on', 'yes', 'ein', '1'].includes(normalized)) return getAblResumeDutyPct();\n if (['false', 'off', 'no', 'aus', '0'].includes(normalized)) return 100;\n }\n const n = toNum(value);\n if (Number.isFinite(n)) return n > 0 ? getAblResumeDutyPct() : 100;\n return value;\n };\n\n // Expose a readable state string for UIs / scripts\n if (evseStateDpAbl) {\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'Status text',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n if (!values) return '';\n const n = toNum(values[evseStateDpAbl.id]);\n if (!Number.isFinite(n)) return '';\n const code = (Math.trunc(n) & 0xFF);\n const map = {\n 0xA1: 'A1 Waiting for EV',\n 0xB1: 'B1 EV is asking for charging',\n 0xB2: 'B2 EV has the permission to charge',\n 0xC2: 'C2 EV is charged/charging',\n 0xC3: 'C3 Reduced current (error)',\n 0xC4: 'C4 Reduced current (imbalance)',\n 0xE0: 'E0 Outlet disabled',\n 0xE1: 'E1 Production test',\n 0xE2: 'E2 EVCC setup mode',\n 0xE3: 'E3 Bus idle',\n 0xF1: 'F1 Welding (contactor)',\n 0xF2: 'F2 Internal error',\n 0xF3: 'F3 DC residual current detected',\n 0xF4: 'F4 Upstream communication timeout',\n 0xF5: 'F5 Lock of socket failed',\n 0xF6: 'F6 CS out of range',\n 0xF7: 'F7 State D requested by EV',\n 0xF8: 'F8 CP out of range',\n 0xF9: 'F9 Overcurrent detected',\n 0xFA: 'F10 Temperature outside limits',\n 0xFB: 'F11 Unintended opened contact',\n };\n const label = map[code];\n const hex = code.toString(16).toUpperCase().padStart(2, '0');\n return label ? label : `Unknown (0x${hex})`;\n }\n });\n }\n\n const modbusSettingsRawDp = getAnyById('mODBUS_SETTINGS_RAW');\n\n if (modbusSettingsRawDp) {\n add({\n relId: this._aliasRelId('r.modbusSettingsRaw'),\n name: 'Modbus settings raw',\n role: 'value',\n type: 'number',\n rw: 'ro',\n kind: 'dp',\n dpId: modbusSettingsRawDp.id,\n });\n\n const decodeAblModbusSettings = (values) => {\n if (!values) return null;\n const rawNum = toNum(values[modbusSettingsRawDp.id]);\n if (!Number.isFinite(rawNum)) return null;\n const raw = Math.trunc(rawNum) & 0xFFFF;\n const stopBitsCode = (raw >>> 6) & 0x03;\n const parityCode = (raw >>> 4) & 0x03;\n const baudCode = raw & 0x0F;\n\n const stopBits = (stopBitsCode === 0) ? 1 : ((stopBitsCode === 3) ? 2 : null);\n const parity = ({ 0: 'none', 1: 'odd', 2: 'even' })[parityCode] || 'invalid';\n const baudRate = ({ 5: 9600, 6: 19200, 7: 38400, 8: 57600 })[baudCode] || null;\n\n return { raw, stopBitsCode, parityCode, baudCode, stopBits, parity, baudRate };\n };\n\n add({\n relId: this._aliasRelId('r.modbusStopBits'),\n name: 'Modbus stop bits',\n role: 'value',\n type: 'number',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const decoded = decodeAblModbusSettings(values);\n return decoded ? decoded.stopBits : undefined;\n }\n });\n\n add({\n relId: this._aliasRelId('r.modbusBaudRate'),\n name: 'Modbus baud rate',\n role: 'value',\n type: 'number',\n unit: 'Bd',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const decoded = decodeAblModbusSettings(values);\n return decoded ? decoded.baudRate : undefined;\n }\n });\n\n add({\n relId: this._aliasRelId('r.modbusParity'),\n name: 'Modbus parity',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const decoded = decodeAblModbusSettings(values);\n return decoded ? decoded.parity : '';\n }\n });\n\n add({\n relId: this._aliasRelId('r.modbusSettingsText'),\n name: 'Modbus settings',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const decoded = decodeAblModbusSettings(values);\n if (!decoded) return '';\n const baud = decoded.baudRate ?? `code:${decoded.baudCode}`;\n const stop = decoded.stopBits ?? `code:${decoded.stopBitsCode}`;\n const parity = decoded.parity || `code:${decoded.parityCode}`;\n return `${baud} / ${parity} / 8 / ${stop}`;\n }\n });\n }\n\n const currentL1Dp = getAnyById('cURRENT_L1');\n const currentL2Dp = getAnyById('cURRENT_L2');\n const currentL3Dp = getAnyById('cURRENT_L3');\n const currentDpsAbl = [currentL1Dp, currentL2Dp, currentL3Dp].filter(Boolean);\n const nominalPhaseVoltageV = 230;\n const getPhaseCurrentsA = (values) => {\n if (!values || !currentDpsAbl.length) return undefined;\n let seenAnyProperty = false;\n const currentsA = [];\n for (const dp of currentDpsAbl) {\n if (!Object.prototype.hasOwnProperty.call(values, dp.id)) continue;\n seenAnyProperty = true;\n const n = toNum(values[dp.id]);\n if (Number.isFinite(n) && n >= 0) currentsA.push(n);\n }\n if (!seenAnyProperty || currentsA.length === 0) return undefined;\n return currentsA;\n };\n const getPhaseCurrentSumA = (values) => {\n const currentsA = getPhaseCurrentsA(values);\n if (!currentsA) return undefined;\n return round1(currentsA.reduce((sum, value) => sum + value, 0));\n };\n const getActualChargingCurrentA = (values) => {\n const currentsA = getPhaseCurrentsA(values);\n if (!currentsA) return undefined;\n // ABL/IEC current limits are specified per phase. For one- and three-phase\n // vehicles the highest measured phase is therefore the comparable live value.\n return round1(Math.max(...currentsA));\n };\n\n if (currentDpsAbl.length) {\n if (currentL1Dp) add({\n relId: this._aliasRelId('r.currentL1'),\n name: 'Current L1',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentL1Dp.id,\n replace: true,\n });\n if (currentL2Dp) add({\n relId: this._aliasRelId('r.currentL2'),\n name: 'Current L2',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentL2Dp.id,\n replace: true,\n });\n if (currentL3Dp) add({\n relId: this._aliasRelId('r.currentL3'),\n name: 'Current L3',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentL3Dp.id,\n replace: true,\n });\n\n add({\n relId: this._aliasRelId('r.currentA'),\n name: 'Actual charging current (highest phase)',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'computed',\n get: (values) => getActualChargingCurrentA(values),\n });\n\n // Compatibility alias: this used to add L1+L2+L3 and therefore showed\n // 16.5 A for a balanced 3 x 5.5 A charge. Amperes must not be summed when\n // comparing the live current with the per-phase charging-current setpoint.\n add({\n relId: this._aliasRelId('r.currentTotalA'),\n name: 'Actual charging current (highest phase)',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => getActualChargingCurrentA(values),\n });\n\n // Keep the arithmetic phase-current sum available only as a diagnostic and\n // as the basis for the estimated power calculation below.\n add({\n relId: this._aliasRelId('r.currentPhaseSumA'),\n name: 'Phase-current sum (power calculation)',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'computed',\n get: (values) => getPhaseCurrentSumA(values),\n });\n }\n\n // The ABL EVCC2/3 API subset exposes current per phase, but no direct power register.\n // Derive a stable charging-power alias from the summed phase currents using 230 V per phase.\n // This matches single-phase and 3-phase AC charging well enough for UI/display purposes.\n if (!chargingPowerDp && currentDpsAbl.length) {\n add({\n relId: this._aliasRelId('r.power'),\n name: 'Charging power',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const phaseSumA = getPhaseCurrentSumA(values);\n if (!Number.isFinite(phaseSumA)) return undefined;\n return Math.round(phaseSumA * nominalPhaseVoltageV);\n }\n });\n\n add({\n relId: this._aliasRelId('r.powerEstimated'),\n name: 'Charging power (estimated)',\n role: 'value.power',\n type: 'number',\n unit: 'W',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const phaseSumA = getPhaseCurrentSumA(values);\n if (!Number.isFinite(phaseSumA)) return undefined;\n return Math.round(phaseSumA * nominalPhaseVoltageV);\n }\n });\n }\n\n // Control: EOS provides amperes; the runtime writes PWM duty cycle to 0x0014.\n if (icmaxDutyPctDp && setIcmaxDutyPctDp) {\n add({\n relId: this._aliasRelId('r.currentLimitPct'),\n name: 'Applied PWM current limit',\n role: 'value',\n type: 'number',\n unit: '%',\n rw: 'ro',\n kind: 'dp',\n dpId: icmaxDutyPctDp.id,\n replace: true,\n });\n\n add({\n relId: this._aliasRelId('r.currentLimitA'),\n name: 'Applied charging current limit',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: icmaxDutyPctDp.id,\n fromDevice: ablDutyPctToCurrentA,\n replace: true,\n });\n\n add({\n relId: this._aliasRelId('r.waitingForCurrent'),\n name: 'Waiting for current release',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const pct = toNum(values && values[icmaxDutyPctDp.id]);\n return Number.isFinite(pct) ? pct >= 99.9 : undefined;\n },\n });\n\n add({\n relId: this._aliasRelId('r.chargingReleased'),\n name: 'Charging current released',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const pct = toNum(values && values[icmaxDutyPctDp.id]);\n return Number.isFinite(pct) ? isAblActiveDutyPct(pct) : undefined;\n },\n });\n\n // Expert/direct control in duty-cycle percent. The raw datapoint remains\n // available, but this stable alias accepts only 10..96 % or 100 % pause.\n add({\n relId: this._aliasRelId('ctrl.currentLimitPct'),\n name: 'Charging current limit (PWM duty cycle)',\n role: 'level',\n type: 'number',\n unit: '%',\n rw: 'rw',\n kind: 'dp',\n dpId: icmaxDutyPctDp.id,\n writeDpId: setIcmaxDutyPctDp.id,\n toDevice: normalizeAblDutyPct,\n preferCommandValue: true,\n replace: true,\n });\n\n // Primary NexoWatt EOS interface: write amperes, convert to ABL PWM percent.\n // Examples: 0 A -> 100 %, 6 A -> 10 %, 10 A -> 16.6 %, 16 A -> 26.6 %.\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: 'Charging current limit',\n role: 'level.current',\n type: 'number',\n unit: 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: icmaxDutyPctDp.id,\n writeDpId: setIcmaxDutyPctDp.id,\n toDevice: ablCurrentToDutyPct,\n fromDevice: ablDutyPctToCurrentA,\n preferCommandValue: true,\n replace: true,\n });\n\n // Normal pause/resume is performed through Icmax, not through the service\n // state register 0x0005: false -> 100 %, true -> restore last active duty.\n const runAlias = {\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: icmaxDutyPctDp.id,\n writeDpId: setIcmaxDutyPctDp.id,\n toDevice: ablRunToDutyPct,\n fromDevice: (value) => isAblActiveDutyPct(value),\n preferCommandValue: true,\n replace: true,\n };\n\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run / current release',\n ...runAlias,\n });\n add({\n relId: this._aliasRelId('ctrl.chargeEnable'),\n name: 'Charging current release',\n ...runAlias,\n });\n }\n }\n } catch (e) {\n // Never break alias generation due to special-case logic\n }\n\n // --- Weidmüller Charge Wallbox Business CH-W-B special aliases ---\n // The documented control interface separates the requested Ethernet release\n // (coil 400) from the actual aggregate release state (coil 436). Keep those\n // paths separate so aliases.ctrl.run reports the charger-side result instead\n // of merely echoing the last command.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const manufacturerLower = String(this.template?.manufacturer || '').toLowerCase();\n const modelLower = String(this.template?.model || '').toLowerCase();\n const isWeidmuellerBusiness =\n tplIdLower.includes('evcs.weidmueller.chargewallboxbusiness') ||\n ((manufacturerLower.includes('weidmüller') || manufacturerLower.includes('weidmueller')) &&\n modelLower.includes('charge wallbox business'));\n\n if (isWeidmuellerBusiness) {\n const evStateDp = getAnyById('eVSE_STATE');\n const proximityDp = getAnyById('pROXIMITY_CURRENT');\n const chargingTimeDp = getAnyById('cHARGING_TIME');\n const voltageL1Dp = getAnyById('vOLTAGE_L1');\n const voltageL2Dp = getAnyById('vOLTAGE_L2');\n const voltageL3Dp = getAnyById('vOLTAGE_L3');\n const currentL1Dp = getAnyById('cURRENT_L1');\n const currentL2Dp = getAnyById('cURRENT_L2');\n const currentL3Dp = getAnyById('cURRENT_L3');\n const pwmCurrentDp = getAnyById('pWM_CURRENT');\n const setCurrentDp = getAnyById('sET_CHARGING_CURRENT');\n const releaseCommandDp = getAnyById('sET_ENABLE');\n const releasedDp = getAnyById('cHARGING_RELEASED');\n const rfidReaderDp = getAnyById('rFID_READER_ENABLE');\n const rfidUidDp = getAnyById('rFID_CARD_UID');\n const firmwareDp = getAnyById('fIRMWARE_VERSION');\n\n const toNumber = (value) => {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'boolean') return value ? 1 : 0;\n if (typeof value === 'string') {\n const normalized = value.trim().replace(',', '.');\n if (!normalized) return undefined;\n const direct = Number(normalized);\n if (Number.isFinite(direct)) return direct;\n const match = normalized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number(match[0]);\n if (Number.isFinite(parsed)) return parsed;\n }\n }\n return undefined;\n };\n\n const evStateLetter = (value) => {\n if (typeof value === 'string') {\n const match = value.toUpperCase().match(/[A-F]/);\n if (match) return match[0];\n }\n const n = toNumber(value);\n if (!Number.isFinite(n)) return '';\n const raw = Math.trunc(n) & 0xFFFF;\n const low = raw & 0xFF;\n const high = (raw >>> 8) & 0xFF;\n if (low >= 65 && low <= 70) return String.fromCharCode(low);\n if (high >= 65 && high <= 70) return String.fromCharCode(high);\n if (raw >= 0 && raw <= 5) return String.fromCharCode(65 + raw);\n return '';\n };\n\n const stateInfoByLetter = {\n A: { code: 0, text: 'A - No vehicle connected', connected: false, charging: false, available: true, fault: false },\n B: { code: 1, text: 'B - Vehicle connected, not charging', connected: true, charging: false, available: true, fault: false },\n C: { code: 2, text: 'C - Vehicle charging', connected: true, charging: true, available: true, fault: false },\n D: { code: 3, text: 'D - Vehicle charging, ventilation required', connected: true, charging: true, available: true, fault: false },\n E: { code: 4, text: 'E - Error', connected: false, charging: false, available: false, fault: true },\n F: { code: 5, text: 'F - Error', connected: false, charging: false, available: false, fault: true },\n };\n\n const statusStates = {\n 0: 'A - No vehicle connected',\n 1: 'B - Vehicle connected, not charging',\n 2: 'C - Vehicle charging',\n 3: 'D - Vehicle charging, ventilation required',\n 4: 'E - Error',\n 5: 'F - Error',\n };\n\n const stateInfo = (values) => {\n if (!evStateDp || !values) return null;\n const letter = evStateLetter(values[evStateDp.id]);\n return letter && stateInfoByLetter[letter] ? { letter, ...stateInfoByLetter[letter] } : null;\n };\n\n if (evStateDp) {\n add({\n relId: this._aliasRelId('r.statusCode'),\n name: 'EV status code',\n role: 'indicator.status',\n type: 'number',\n states: statusStates,\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.code : undefined;\n },\n });\n\n add({\n relId: this._aliasRelId('r.statusText'),\n name: 'EV status',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.text : 'Unknown';\n },\n });\n\n add({\n relId: this._aliasRelId('r.evState'),\n name: 'IEC 61851 EV state',\n role: 'text',\n type: 'string',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.letter : '';\n },\n });\n\n add({\n relId: this._aliasRelId('r.vehicleConnected'),\n name: 'Vehicle connected',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.connected : undefined;\n },\n });\n\n add({\n relId: this._aliasRelId('r.available'),\n name: 'Wallbox available',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.available : undefined;\n },\n });\n\n add({\n relId: this._aliasRelId('alarm.fault'),\n name: 'Wallbox fault',\n role: 'indicator.alarm',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const info = stateInfo(values);\n return info ? info.fault : undefined;\n },\n });\n }\n\n add({\n relId: this._aliasRelId('r.charging'),\n name: 'Charging active',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'computed',\n replace: true,\n get: (values) => {\n const info = stateInfo(values);\n if (info && info.charging) return true;\n const power = chargingPowerDp ? toNumber(values && values[chargingPowerDp.id]) : undefined;\n if (Number.isFinite(power)) return power > 50;\n return info ? info.charging : undefined;\n },\n });\n\n if (proximityDp) {\n add({ relId: this._aliasRelId('r.proximityCurrentA'), name: 'Proximity cable current', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: proximityDp.id });\n }\n if (chargingTimeDp) {\n add({ relId: this._aliasRelId('r.sessionTimeS'), name: 'Charging session time', role: 'value.interval', type: 'number', unit: 's', rw: 'ro', kind: 'dp', dpId: chargingTimeDp.id });\n }\n\n if (voltageL1Dp) add({ relId: this._aliasRelId('r.voltageL1'), name: 'Voltage L1', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: voltageL1Dp.id, replace: true });\n if (voltageL2Dp) add({ relId: this._aliasRelId('r.voltageL2'), name: 'Voltage L2', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: voltageL2Dp.id, replace: true });\n if (voltageL3Dp) add({ relId: this._aliasRelId('r.voltageL3'), name: 'Voltage L3', role: 'value.voltage', type: 'number', unit: 'V', rw: 'ro', kind: 'dp', dpId: voltageL3Dp.id, replace: true });\n if (currentL1Dp) add({ relId: this._aliasRelId('r.currentL1'), name: 'Current L1', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: currentL1Dp.id, replace: true });\n if (currentL2Dp) add({ relId: this._aliasRelId('r.currentL2'), name: 'Current L2', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: currentL2Dp.id, replace: true });\n if (currentL3Dp) add({ relId: this._aliasRelId('r.currentL3'), name: 'Current L3', role: 'value.current', type: 'number', unit: 'A', rw: 'ro', kind: 'dp', dpId: currentL3Dp.id, replace: true });\n\n const currentReadDp = pwmCurrentDp || setCurrentDp;\n if (currentReadDp) {\n add({\n relId: this._aliasRelId('r.currentLimitA'),\n name: 'Applied charging current limit',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'dp',\n dpId: currentReadDp.id,\n fromDevice: (value) => toNumber(value),\n replace: true,\n });\n }\n\n if (setCurrentDp) {\n const normalizeCurrentCommand = (value) => {\n const n = toNumber(value);\n if (!Number.isFinite(n)) return value;\n if (n <= 0) return 0;\n const clamped = Math.min(32, Math.max(6, n));\n return Math.round(clamped * 10) / 10;\n };\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: 'Charging current limit',\n role: 'level.current',\n type: 'number',\n unit: 'A',\n rw: 'rw',\n kind: 'dp',\n dpId: currentReadDp ? currentReadDp.id : setCurrentDp.id,\n writeDpId: setCurrentDp.id,\n toDevice: normalizeCurrentCommand,\n fromDevice: (value) => toNumber(value),\n replace: true,\n });\n }\n\n if (releasedDp) {\n add({\n relId: this._aliasRelId('r.chargingReleased'),\n name: 'Charging released by wallbox',\n role: 'indicator',\n type: 'boolean',\n rw: 'ro',\n kind: 'dp',\n dpId: releasedDp.id,\n fromDevice: (value) => !!value,\n replace: true,\n });\n }\n\n if (releaseCommandDp && releasedDp) {\n const releaseAlias = {\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: releasedDp.id,\n writeDpId: releaseCommandDp.id,\n toDevice: (value) => !!value,\n fromDevice: (value) => !!value,\n replace: true,\n };\n add({ relId: this._aliasRelId('ctrl.run'), name: 'Run / charging release', ...releaseAlias });\n add({ relId: this._aliasRelId('ctrl.chargeEnable'), name: 'Charging release', ...releaseAlias });\n }\n\n if (rfidReaderDp) {\n add({\n relId: this._aliasRelId('ctrl.rfidReaderEnabled'),\n name: 'Enable RFID reader',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: rfidReaderDp.id,\n writeDpId: rfidReaderDp.id,\n commandOnlyAlias: true,\n preferCommandValue: true,\n toDevice: (value) => !!value,\n fromDevice: (value) => !!value,\n });\n }\n\n if (rfidUidDp) {\n add({ relId: this._aliasRelId('r.rfidCardUid'), name: 'Last RFID card UID', role: 'text', type: 'string', rw: 'ro', kind: 'dp', dpId: rfidUidDp.id });\n }\n if (firmwareDp) {\n add({ relId: this._aliasRelId('r.firmwareVersion'), name: 'Firmware version', role: 'text', type: 'string', rw: 'ro', kind: 'dp', dpId: firmwareDp.id });\n }\n }\n } catch (e) {\n // Never break generic EVCS alias generation because of a vendor-specific mapping.\n }\n\n // Control: current limit (A) (best-effort)\n // The OEM V10.03 protocol exposes a real connector power setpoint but no\n // connector-current command. Its universal FALLBACK_CURRENT register is only\n // the safety value used after a communication timeout and must never be exposed\n // as the live EOS charging-current setpoint.\n const currentTemplateIdLower = String(this.template?.id || '').toLowerCase();\n const suppressGenericCurrentLimit = currentTemplateIdLower.includes('evcs.oem.modbusv1003.connector');\n const currentLimitDp = suppressGenericCurrentLimit ? null : (\n getAnyById('sET_CHARGING_CURRENT', 'cHARGE_CURRENT', 'cHARGING_CURRENT', 'currentUser_mA', 'aPPLY_CHARGE_CURRENT_LIMIT') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n /current/i.test(String(dp.id || '')) &&\n !/timeout/i.test(String(dp.id || '')) &&\n !/failsafe/i.test(String(dp.id || ''))\n )\n );\n\n if (currentLimitDp) {\n const unit = (currentLimitDp.unit === 'mA') ? 'A' : (currentLimitDp.unit || 'A');\n const isMilliAmp = currentLimitDp.unit === 'mA';\n\n add({\n relId: this._aliasRelId('ctrl.currentLimitA'),\n name: 'Charging current limit',\n role: 'level.current',\n type: 'number',\n unit,\n rw: 'rw',\n kind: 'dp',\n dpId: currentLimitDp.id,\n writeDpId: currentLimitDp.id,\n toDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return isMilliAmp ? Math.round(n * 1000) : n;\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return v;\n return isMilliAmp ? (n / 1000) : n;\n }\n });\n }\n\n // Control: power limit (W) (best-effort)\n const powerLimitDp =\n getAnyById('eV_SET_CHARGE_POWER_LIMIT', 'aPPLY_CHARGE_POWER_LIMIT', 'set_station_max_power') ||\n findByIdRe(/set_c\\d+_max_power/i) ||\n findByIdRe(/set_.*max_power/i);\n\n if (powerLimitDp && (powerLimitDp.rw === 'rw' || powerLimitDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.powerLimitW'),\n name: 'Charging power limit',\n role: 'level.power',\n type: 'number',\n unit: powerLimitDp.unit || 'W',\n rw: 'rw',\n kind: 'dp',\n dpId: powerLimitDp.id,\n writeDpId: powerLimitDp.id,\n });\n }\n // Control: run/stop (enable/disable) (best-effort)\n // Some EV chargers use a \"control_command\" holding register where:\n // 3 = stop charging, 4 = start charging.\n // In that case we expose ctrl.run as boolean and map to those command values.\n const controlCommandDp =\n getAnyById('cONTROL_COMMAND', 'control_command') ||\n findByIdRe(/control_command/i);\n\n if (controlCommandDp && statusDp) {\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (enable/start)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n // Read from status code (more accurate), write to control command register\n dpId: statusDp.id,\n writeDpId: controlCommandDp.id,\n toDevice: (v) => {\n if (typeof v === 'boolean') return v ? 4 : 3;\n return v;\n },\n fromDevice: (v) => {\n const n = Number(v);\n if (!Number.isFinite(n)) return undefined;\n // EVSE_State (SolaX HAC): 1=Preparing,2=Charging,7/8=Suspended,11=StartDelay,12=Pause,13=Stopping\n return [1, 2, 7, 8, 11, 12, 13].includes(n);\n }\n });\n } else {\n const enableDp =\n getAnyById('sET_ENABLE', 'enableUser', 'sTART_CANCEL_CHARGING_SESSION') ||\n this._findFirstDatapoint(dp =>\n (dp.rw === 'rw' || dp.rw === 'wo') &&\n (/enable/i.test(String(dp.id || '')) || /start/i.test(String(dp.id || '')) || /stop/i.test(String(dp.id || '')))\n );\n\n if (enableDp) {\n add({\n relId: this._aliasRelId('ctrl.run'),\n name: 'Run (enable/start)',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: enableDp.id,\n writeDpId: enableDp.id,\n toDevice: (v) => {\n // Many EVCS implementations use 0/1 integer flags for enable/start.\n if (typeof v === 'boolean') return v ? 1 : 0;\n return v;\n },\n fromDevice: (v) => {\n if (typeof v === 'number') return v !== 0;\n if (typeof v === 'boolean') return v;\n return undefined;\n }\n });\n }\n }\n\n // Control: unlock plug (best-effort)\n\n const unlockDp = getAnyById('sET_UNLOCK_PLUG');\n if (unlockDp && (unlockDp.rw === 'rw' || unlockDp.rw === 'wo')) {\n add({\n relId: this._aliasRelId('ctrl.unlockPlug'),\n name: 'Unlock plug',\n role: 'switch',\n type: 'boolean',\n rw: 'rw',\n kind: 'dp',\n dpId: unlockDp.id,\n writeDpId: unlockDp.id,\n toDevice: (v) => (v ? 1 : 0),\n fromDevice: (v) => {\n if (typeof v === 'number') return v !== 0;\n if (typeof v === 'boolean') return v;\n return undefined;\n }\n });\n }\n }\n\n // Canonical current fallback for EV chargers. Some legacy templates expose\n // only per-phase currents; v1 still needs one comparable current value without\n // creating a new state in the old aliases.* namespace.\n if (this.aliasDeviceClass === 'evCharger') {\n const legacyPathOf = (def) => {\n const marker = '.aliases.';\n const text = String(def && def.relId || '');\n const pos = text.indexOf(marker);\n return pos >= 0 ? text.slice(pos + marker.length) : '';\n };\n const alreadyHasCurrent = defs.some(def => {\n const path = legacyPathOf(def);\n return path === 'r.currentA' || path === 'r.currentTotalA';\n });\n if (!alreadyHasCurrent) {\n const phaseDefs = ['r.currentL1', 'r.currentL2', 'r.currentL3']\n .map(path => defs.find(def => legacyPathOf(def) === path))\n .filter(Boolean);\n if (phaseDefs.length) {\n addStandardSource({\n relId: this._aliasRelId('r.currentA'),\n name: 'Actual current (highest phase)',\n role: 'value.current',\n type: 'number',\n unit: 'A',\n rw: 'ro',\n kind: 'computed',\n get: (values) => {\n const candidates = [];\n for (const def of phaseDefs) {\n if (!def || def.kind !== 'dp' || !def.dpId) continue;\n if (!values || !Object.prototype.hasOwnProperty.call(values, def.dpId)) continue;\n let value = values[def.dpId];\n if (typeof def.fromDevice === 'function') value = def.fromDevice(value);\n const n = Number(value);\n if (Number.isFinite(n) && n >= 0) candidates.push(n);\n }\n return candidates.length ? Math.max(...candidates) : undefined;\n },\n });\n }\n }\n }\n\n // VARTA raw values use opposite power signs to EOS. Override only these\n // eight new profiles; existing manufacturer definitions stay unchanged.\n for (const def of buildVartaAliases(this)) add(def);\n for (const def of buildVartaExtendedAliases(this)) add(def);\n for (const def of buildDeyeAliases(this)) add(def);\n\n // Build the strict, versioned Alias Contract v1 namespace. Unlike the historic aliases,\n // aliases.v1 has fixed paths, types, roles and SI-oriented units. The NexoWatt UI should\n // use this namespace for automatic discovery and mapping.\n const standard = buildStandardAliasDefinitions({\n baseId: this.baseId,\n template: this.template,\n cfg: this.cfg,\n legacyDefs: defs.concat(standardOnlyDefs),\n getDpById: (id) => this._getDpById(id),\n });\n this.aliasContractInfo = standard;\n this.aliasDeviceClass = standard.deviceClass;\n for (const def of standard.definitions) add(def);\n\n return defs;\n }\n\n\n\n\n async registerDynamicAlias(def, options = {}) {\n if (!def || !def.relId) return null;\n const relId = String(def.relId);\n const existing = this.aliasByStateRelId.get(relId);\n if (existing) return existing;\n\n await this._ensureAliasPathChannels(relId);\n const common = {\n name: def.name || relId.split('.').slice(-1)[0],\n type: def.type || 'string',\n role: def.role || 'state',\n read: def.rw !== 'wo',\n write: def.rw === 'rw' || def.rw === 'wo',\n };\n if (def.unit) common.unit = def.unit;\n if (def.states && typeof def.states === 'object') common.states = def.states;\n\n const native = {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAlias: true,\n dynamic: true,\n aliasKind: def.kind,\n dpId: def.dpId,\n writeDpId: def.writeDpId,\n };\n if (def.aliasContractVersion) {\n native.aliasContractVersion = def.aliasContractVersion;\n native.aliasContractPath = def.aliasContractPath;\n native.capability = def.capability;\n native.deviceClass = this.aliasDeviceClass;\n }\n\n await this.adapter.setObjectNotExistsAsync(relId, { type: 'state', common, native });\n await this.adapter.extendObjectAsync(relId, { common, native }).catch(() => {});\n\n this.aliasByStateRelId.set(relId, def);\n this.aliasDefs.push(def);\n\n if (def.aliasContractVersion) {\n mergeStandardDefinition(this.aliasContractInfo, def);\n this._scheduleAliasContractMetadataRefresh();\n } else if (!options.skipStandardMirror) {\n const sourcePath = legacyAliasPath(relId);\n if (sourcePath && !sourcePath.startsWith('meta.')) {\n const canonicalPath = canonicalAliasPath(this.aliasDeviceClass, sourcePath);\n const sourceForStandard = {\n ...def,\n relId: this._aliasRelId(canonicalPath),\n };\n const standardDef = cloneStandardDefinition(sourceForStandard, {\n baseId: this.baseId,\n deviceClass: this.aliasDeviceClass,\n getDpById: (id) => this._getDpById(id),\n standardNamespace: ALIAS_STANDARD_NAMESPACE,\n canonicalPath,\n });\n if (standardDef) {\n await this.registerDynamicAlias(standardDef, { skipStandardMirror: true });\n }\n }\n }\n\n return def;\n }\n\n _scheduleAliasContractMetadataRefresh() {\n if (this._aliasMetadataRefreshTimer) {\n try { clearTimeout(this._aliasMetadataRefreshTimer); } catch (_) {}\n }\n this._aliasMetadataRefreshTimer = setTimeout(() => {\n this._aliasMetadataRefreshTimer = null;\n this._initAliasContractMetadata().catch((error) => {\n this.adapter.log.debug(\n `[${this.cfg.id}] alias contract metadata refresh failed: ${error && error.message ? error.message : error}`\n );\n });\n }, 50);\n }\n\n async _initAliasObjects() {\n // Build and validate alias definitions\n const defs = this._buildAliasDefinitions();\n if (!Array.isArray(defs) || !defs.length) return;\n\n for (const def of defs) {\n if (!def || !def.relId) continue;\n await this._ensureAliasPathChannels(def.relId);\n\n const common = {\n name: def.name || def.relId.split('.').slice(-1)[0],\n type: def.type || 'string',\n role: def.role || 'state',\n read: def.rw !== 'wo',\n write: def.rw === 'rw' || def.rw === 'wo',\n };\n if (common.write && getVartaProfile(this.template)) common.write = this._vartaDatapointAllowsWrite(def.writeDpId || def.dpId);\n if (def.unit) common.unit = def.unit;\n if (def.states && typeof def.states === 'object') common.states = def.states;\n\n const native = {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAlias: true,\n aliasKind: def.kind,\n dpId: def.dpId,\n writeDpId: def.writeDpId,\n };\n if (def.aliasContractVersion) {\n native.aliasContractVersion = def.aliasContractVersion;\n native.aliasContractPath = def.aliasContractPath;\n native.capability = def.capability;\n native.deviceClass = this.aliasDeviceClass;\n }\n\n await this.adapter.setObjectNotExistsAsync(def.relId, { type: 'state', common, native });\n\n // Keep alias object meta-data (e.g. unit/role) in sync across updates.\n // Otherwise users would have to delete alias objects manually when templates change.\n await this.adapter.extendObjectAsync(def.relId, { common, native }).catch(() => {});\n\n this.aliasByStateRelId.set(def.relId, def);\n this.aliasDefs.push(def);\n }\n await this._reconcileDisabledVartaAliases();\n }\n\n _vartaDatapointAllowsWrite(dpId, tableVersion = this._vartaMetadataTableVersion) {\n const profile = getVartaProfile(this.template);\n if (!profile || (Number.isInteger(tableVersion) && tableVersion !== 14)) return false;\n if (!this._vartaWriteDefinitions) {\n this._vartaWriteDefinitions = new Map([...registersForProfile(profile), ...extendedRegistersForProfile(profile)]\n .filter(def => def.writable).map(def => [def.id, def]));\n }\n const def = this._vartaWriteDefinitions.get(String(dpId));\n if (!def) return false;\n if (def.extended && this.cfg.vartaExtendedEnabled === false) return false;\n if (def.frequency && this.cfg.vartaFrequencyControlEnabled !== true) return false;\n // The public writable registers are scale factors. Control permission must\n // never imply SF permission (or vice versa), including extended SF fields.\n return !def.extended || def.isScaleFactor\n ? this.cfg.vartaAllowScaleFactorWrites === true\n : this.cfg.vartaAllowControlWrites === true;\n }\n\n async _reconcileDisabledVartaAliases() {\n if (!getVartaProfile(this.template) || typeof this.adapter.getObjectAsync !== 'function') return;\n // Enumerate only this profile's known controls, without changing configured\n // definitions or creating controls absent from the current configuration.\n const candidates = buildVartaExtendedAliases({\n template: this.template,\n cfg: { ...this.cfg, vartaExtendedEnabled: true, vartaAllowControlWrites: true, vartaFrequencyControlEnabled: true },\n dpById: this.dpById,\n _aliasRelId: aliasPath => this._aliasRelId(aliasPath),\n });\n for (const def of candidates) {\n if (def.rw !== 'rw' && def.rw !== 'wo') continue;\n const standardPath = canonicalAliasPath(this.aliasDeviceClass, legacyAliasPath(def.relId));\n for (const relId of [def.relId, `${this.baseId}.aliases.${ALIAS_STANDARD_NAMESPACE}.${standardPath}`]) {\n if (this.aliasByStateRelId.has(relId)) continue;\n const object = await this.adapter.getObjectAsync(relId);\n if (object?.type !== 'state' || object.native?.isAlias !== true || object.native?.deviceId !== this.cfg.id) continue;\n if (object.common?.write !== false) await this.adapter.extendObjectAsync(relId, { common: { write: false } });\n }\n }\n }\n\n async _initAliasContractMetadata() {\n let info = this.aliasContractInfo || {\n schemaVersion: ALIAS_SCHEMA_VERSION,\n namespace: ALIAS_STANDARD_NAMESPACE,\n deviceClass: this.aliasDeviceClass,\n capabilities: [],\n missingRequired: [],\n };\n if (getVartaProfile(this.template) && this._vartaReadOnlyTable === true) {\n // Keep the configured definitions intact for a later verified table-14\n // snapshot. Published capabilities describe the observed device table.\n info = { ...info, capabilities: (info.capabilities || []).filter(capability => !String(capability).startsWith('write.')) };\n }\n const manifest = buildAliasManifest(info, this.template, this.cfg);\n const capabilitiesJson = JSON.stringify(manifest.capabilities || []);\n const missingRequiredJson = JSON.stringify(manifest.missingRequired || []);\n const manifestJson = JSON.stringify(manifest);\n\n const states = [\n { path: 'schemaVersion', name: 'Alias schema version', type: 'number', role: 'value', value: ALIAS_SCHEMA_VERSION },\n { path: 'deviceClass', name: 'Canonical device class', type: 'string', role: 'text', value: manifest.deviceClass },\n { path: 'namespace', name: 'Canonical alias namespace', type: 'string', role: 'text', value: ALIAS_STANDARD_NAMESPACE },\n { path: 'capabilities', name: 'Capabilities (JSON)', type: 'string', role: 'json', value: capabilitiesJson },\n { path: 'capabilityCount', name: 'Capability count', type: 'number', role: 'value', value: manifest.capabilities.length },\n { path: 'missingRequired', name: 'Missing required aliases (JSON)', type: 'string', role: 'json', value: missingRequiredJson },\n { path: 'templateId', name: 'Template ID', type: 'string', role: 'text', value: manifest.templateId },\n { path: 'category', name: 'Template category', type: 'string', role: 'text', value: manifest.category },\n { path: 'manufacturer', name: 'Manufacturer', type: 'string', role: 'text', value: manifest.manufacturer },\n { path: 'model', name: 'Model', type: 'string', role: 'text', value: manifest.model },\n { path: 'manifest', name: 'Alias Contract manifest (JSON)', type: 'string', role: 'json', value: manifestJson },\n ];\n\n for (const state of states) {\n const relId = this._aliasRelId(`meta.${state.path}`);\n await this._ensureAliasPathChannels(relId);\n const common = {\n name: state.name,\n type: state.type,\n role: state.role,\n read: true,\n write: false,\n };\n const native = {\n deviceId: this.cfg.id,\n templateId: this.cfg.templateId,\n isAliasMetadata: true,\n aliasContractVersion: ALIAS_SCHEMA_VERSION,\n deviceClass: manifest.deviceClass,\n };\n await this.adapter.setObjectNotExistsAsync(relId, { type: 'state', common, native });\n await this.adapter.extendObjectAsync(relId, { common, native }).catch(() => {});\n await this._setStateCached(relId, state.value, true);\n }\n\n const nativeContract = {\n aliasSchemaVersion: ALIAS_SCHEMA_VERSION,\n aliasNamespace: ALIAS_STANDARD_NAMESPACE,\n aliasStandardPath: `aliases.${ALIAS_STANDARD_NAMESPACE}`,\n deviceClass: manifest.deviceClass,\n capabilities: manifest.capabilities,\n missingRequiredAliases: manifest.missingRequired,\n };\n await this.adapter.extendObjectAsync(this.baseId, { native: nativeContract }).catch(() => {});\n await this.adapter.extendObjectAsync(`${this.baseId}.aliases`, { native: nativeContract }).catch(() => {});\n await this.adapter.extendObjectAsync(`${this.baseId}.aliases.${ALIAS_STANDARD_NAMESPACE}`, {\n common: { name: `Alias Contract v${ALIAS_SCHEMA_VERSION}` },\n native: nativeContract,\n }).catch(() => {});\n\n if (manifest.missingRequired.length) {\n this.adapter.log.warn(\n `[${this.cfg.id}] Alias Contract v${ALIAS_SCHEMA_VERSION} is missing required aliases for ${manifest.deviceClass}: ${manifest.missingRequired.join(', ')}`\n );\n }\n }\n\n async _updateDepowerControlDiagnostic(values, ctx = {}) {\n const profile = this.template?.driverHints?.oemModbusV1003;\n if (!profile) return;\n const id = profile.connectorPowerDpId || 'eV_SET_CHARGE_POWER_LIMIT';\n const readback = values && values[id];\n if (ctx.connected === false || typeof readback !== 'number' || !Number.isFinite(readback)) return;\n const requested = this._lastCommandedValueByDpId?.get(id);\n const requestedW = typeof requested === 'number' && Number.isFinite(requested) ? requested : null;\n const pending = this._writeQueue?.has(id) === true;\n const status = requestedW === null ? 'no_command'\n : pending ? 'pending' : readback === requestedW ? 'readback_matches' : 'readback_differs';\n await this._setStateCached(`${this.baseId}.info.depowerControl`, JSON.stringify({\n status, requestedW, readbackW: readback,\n lastWriteAt: this._lastWriteByDpId?.get(id) || null,\n readbackAt: Date.now(),\n }), true);\n }\n\n async _updateVartaTableCapabilities(values) {\n if (!getVartaProfile(this.template)) return;\n const version = values && values.tABLE_VERSION;\n if (!Number.isInteger(version) || version === this._vartaMetadataTableVersion) return;\n const readOnly = version !== 14;\n this._vartaReadOnlyTable = readOnly;\n const native = { vartaTableVersion: version, vartaTableAllowsWrites: !readOnly };\n\n // Retain raw/legacy/v1 state IDs and their configured dispatch definitions.\n // Hiding unavailable write controls is presentation metadata; every physical\n // write still requires the driver's fresh table-14 identity verification.\n for (const dp of this.getDatapoints()) {\n if (dp.rw !== 'rw' && dp.rw !== 'wo') continue;\n await this.adapter.extendObjectAsync(this.relStateId(dp), { common: { write: this._vartaDatapointAllowsWrite(dp.id, version) }, native });\n }\n for (const def of this.aliasDefs || []) {\n if (!def || (def.rw !== 'rw' && def.rw !== 'wo')) continue;\n await this.adapter.extendObjectAsync(def.relId, { common: { write: this._vartaDatapointAllowsWrite(def.writeDpId || def.dpId, version) }, native });\n }\n await this._initAliasContractMetadata();\n this._vartaMetadataTableVersion = version;\n }\n\n async _updateAliases(values, ctx) {\n const readContextGeneration = this._qualifiedAliasGeneration;\n await this._updateVartaTableCapabilities(values).catch(error => {\n this.adapter.log.debug(`[${this.cfg.id}] VARTA table capability metadata update failed: ${error && error.message ? error.message : error}`);\n });\n await this._updateDepowerControlDiagnostic(values, ctx);\n if (!Array.isArray(this.aliasDefs) || !this.aliasDefs.length) return;\n const v = values || {};\n const c = ctx || {};\n\n // On communication errors the caller intentionally passes an empty values object.\n // Do not recompute live data aliases (SOC, power, temperatures, alarms, ...) from an\n // empty snapshot, otherwise a short Modbus timeout turns the last valid value into null.\n // Communication aliases still have to update so the UI can show the real connection state.\n const noValues = !v || Object.keys(v).length === 0;\n const connectionOnlyUpdate = noValues && (c.connected === false || !!getVartaProfile(this.template) || this._isFeneconHomeEssTemplate());\n const isConnectionAlias = (relId) => {\n const id = String(relId || '');\n return /\\.aliases(?:\\.[^.]+)?\\.comm\\.(connected|lastError)$/.test(id) ||\n /\\.aliases(?:\\.[^.]+)?\\.alarm\\.offline$/.test(id);\n };\n const resetAblEmh1LiveMeasurements = this._shouldResetAblEmh1LiveMeasurements(v, c);\n\n for (const def of this.aliasDefs) {\n if (!def || !def.relId) continue;\n if (resetAblEmh1LiveMeasurements && this._isAblEmh1LiveMeasurementAlias(def.relId)) {\n await this._setStateCached(\n def.relId,\n 0,\n true,\n this._liveAliasRefreshOptions(def.relId, v, c),\n );\n continue;\n }\n if (connectionOnlyUpdate && !isConnectionAlias(def.relId) && !def.requiredReadContext) continue;\n // DEPower command memory is filled when a request is queued. Polling must\n // never turn an unsent/rejected request into a successful acknowledgement.\n if (this.template?.driverHints?.oemModbusV1003 && def.commandOnlyAlias === true) continue;\n\n let outVal;\n let sampleSourceIds = [];\n\n if (def.requiredReadContext) {\n if (readContextGeneration !== this._qualifiedAliasGeneration) continue;\n const requirement = def.requiredReadContext;\n const hasTarget = Object.prototype.hasOwnProperty.call(v, def.dpId);\n const hasContext = Object.prototype.hasOwnProperty.call(v, requirement.dpId);\n const previousSampleAt = this._qualifiedAliasSamples.get(def.relId);\n const now = Date.now();\n const freshPair = c.connected !== false && c.diagnosticsOnly !== true &&\n String(this.cfg.protocol || '').startsWith('modbus') && hasTarget && hasContext &&\n hasSameReadResponse(v, def.dpId, requirement.dpId) &&\n typeof v[def.dpId] === 'number' && Number.isFinite(v[def.dpId]) &&\n typeof v[requirement.dpId] === 'number' && v[requirement.dpId] === requirement.value;\n if (freshPair) {\n this._qualifiedAliasSamples.set(def.relId, now);\n sampleSourceIds.push(requirement.dpId);\n } else {\n const incompletePair = (hasTarget || hasContext) && c.diagnosticsOnly !== true;\n const expired = previousSampleAt === undefined || now < previousSampleAt ||\n now - previousSampleAt > this._qualifiedAliasMaxAgeMs;\n if (c.connected === false || incompletePair || expired) {\n this._qualifiedAliasSamples.delete(def.relId);\n await this._setQualifiedAliasValue(def.relId, null, readContextGeneration);\n }\n // An unrelated fast poll keeps the previous timestamp until expiry;\n // it never lends fresh evidence to the last slow mode/target pair.\n continue;\n }\n }\n\n if (def.kind === 'dp') {\n if (!def.dpId) continue;\n\n let raw;\n const commandKey = String(def.writeDpId || def.dpId);\n const hasCommandValue = !!(def.preferCommandValue && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(commandKey));\n if (hasCommandValue) {\n raw = this._lastCommandedValueByDpId.get(commandKey);\n } else {\n if (def.commandOnlyAlias === true) {\n // Command aliases represent the value we want to send, not necessarily the\n // charger's volatile readback. Do not overwrite them from polling with\n // adjacent/default read values such as 0 A or 1 phase.\n continue;\n }\n if (!Object.prototype.hasOwnProperty.call(v, def.dpId)) {\n // Write-only datapoints won't be present in the poll result. In this case we keep\n // the last commanded value (state stays as-is).\n continue;\n }\n raw = v[def.dpId];\n sampleSourceIds.push(def.dpId);\n }\n\n if (typeof def.fromDevice === 'function') {\n outVal = def.fromDevice(raw);\n if (outVal === undefined) continue;\n } else {\n outVal = raw;\n }\n } else if (def.kind === 'computed') {\n if (typeof def.get !== 'function') continue;\n try {\n if (isEnergyFreshnessAlias(this.aliasDeviceClass, legacyAliasPath(def.relId))) {\n const observed = captureAliasSources(v, snapshot => def.get(snapshot, c));\n outVal = observed.value;\n sampleSourceIds = observed.sourceIds;\n } else {\n outVal = def.get(v, c);\n }\n } catch (e) {\n // Never let one broken computed alias kill the device update loop\n if (!this._aliasErrTs) this._aliasErrTs = {};\n const now = Date.now();\n const last = this._aliasErrTs[def.relId] || 0;\n if (now - last > 60000) {\n this._aliasErrTs[def.relId] = now;\n const msg = (e && e.message) ? e.message : String(e);\n this.adapter.log.warn(`[${this.cfg.id}] Alias compute failed for ${def.relId}: ${msg}`);\n }\n continue;\n }\n if (outVal === undefined) continue;\n } else {\n continue;\n }\n\n const refreshOptions = this._liveAliasRefreshOptions(def.relId, v, c, sampleSourceIds);\n if (def.requiredReadContext) {\n await this._setQualifiedAliasValue(def.relId, outVal, readContextGeneration, refreshOptions);\n } else {\n await this._setStateCached(def.relId, outVal, true, refreshOptions);\n }\n }\n }\n\n async _invalidateQualifiedAliases() {\n const generation = ++this._qualifiedAliasGeneration;\n this._qualifiedAliasSamples.clear();\n // A confirmed stop must finish after an already submitted readback write;\n // otherwise its late completion could resurrect evidence from the old poll.\n await Promise.all([...this._qualifiedAliasPendingWrites]);\n if (generation !== this._qualifiedAliasGeneration) return;\n for (const def of this.aliasDefs || []) {\n if (def.requiredReadContext) await this._setStateCached(def.relId, null, true);\n }\n }\n\n async _setQualifiedAliasValue(relId, value, generation, options = undefined) {\n if (generation !== this._qualifiedAliasGeneration) return;\n const pending = this._setStateCached(relId, value, true, options);\n this._qualifiedAliasPendingWrites.add(pending);\n try { await pending; } finally { this._qualifiedAliasPendingWrites.delete(pending); }\n }\n\n async _handleMqttSnapshot(values, meta) {\n const context = meta || {};\n if (context.diagnosticsOnly === true) {\n // Metadata and error envelopes can change aliases without proving live\n // telemetry. Preserve transport errors and the existing heartbeat state.\n const lastError = String(this._stateCache.get(`${this.baseId}.info.lastError`)?.val || '');\n await this._updateAliases(values || {}, { connected: this._hbOnline === true, lastError, diagnosticsOnly: true }).catch(() => {});\n return;\n }\n const connected = context.connected !== false;\n const explicitError = String(context.error || '').trim();\n const lastError = explicitError || (connected ? '' : 'MQTT data stale or disconnected');\n\n await this._setStateCached(`${this.baseId}.info.connection`, connected, true);\n if (lastError) {\n // A broker can accept the MQTT connection while denying subscriptions or\n // while the gateway publishes no data. Preserve those protocol-level\n // diagnostics even though the TCP/MQTT transport itself is connected.\n await this._setStateCached(`${this.baseId}.info.lastError`, lastError, true);\n } else {\n await this._setStateCached(`${this.baseId}.info.lastError`, '', true);\n }\n\n await this._updateAliases(values || {}, { connected, lastError }).catch(() => {});\n }\n\n async _handleMqttConnectionState(connected, errorMessage) {\n const isConnected = !!connected;\n if (isConnected) {\n await this._setStateCached(`${this.baseId}.info.connection`, true, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, '', true);\n // Transport connectivity and data freshness are separate: heartbeat/online is\n // raised only by an actual MQTT message in _tickHeartbeatFromIncomingData().\n await this._updateAliases({}, { connected: true, lastError: '' }).catch(() => {});\n return;\n }\n\n const message = String(errorMessage || 'MQTT disconnected');\n await this._setStateCached(`${this.baseId}.info.connection`, false, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, message, true);\n await this._setHeartbeatOnline(false, message).catch(() => {});\n await this._updateAliases({}, { connected: false, lastError: message }).catch(() => {});\n }\n\n _createDriver() {\n const proto = this.cfg.protocol;\n if (getDeyeProfile(this.template)) return new DeyeModbusDriver(this.adapter, this.cfg, this.template, this.global);\n if (getVartaProfile(this.template)) {\n return new VartaModbusDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'modbusTcp' || proto === 'modbusRtu' || proto === 'modbusAscii') {\n return new ModbusDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'mbus') {\n return new MbusDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'onewire') {\n return new OneWireDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'speedwire') {\n return new SpeedwireDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'mqtt') {\n // MQTT driver needs mapping dp -> state id\n return new MqttDriver(\n this.adapter,\n this.cfg,\n this.template,\n this.global,\n (dp) => this.relStateId(dp),\n (dp) => this._getRoundingDecimals(dp),\n () => { this._tickHeartbeatFromIncomingData().catch(() => {}); },\n (values, meta) => this._handleMqttSnapshot(values, meta),\n (connected, errorMessage) => this._handleMqttConnectionState(connected, errorMessage)\n );\n }\n if (proto === 'canbus') {\n // CANbus driver needs mapping dp -> state id + baseId for info.* states\n return new CanbusDriver(\n this.adapter,\n this.cfg,\n this.template,\n this.global,\n (dp) => this.relStateId(dp),\n (dp) => this._getRoundingDecimals(dp),\n this.baseId,\n () => { this._tickHeartbeatFromIncomingData().catch(() => {}); }\n );\n }\n if (proto === 'kostalTcp') {\n return new KostalTcpDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'kostalRs485') {\n return new KostalRs485Driver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'http') {\n return new HttpDriver(this.adapter, this.cfg, this.template, this.global);\n }\n if (proto === 'taCmi') {\n return new TaCmiDriver(this.adapter, this.cfg, this.template, this.global, this);\n }\n if (proto === 'udp') {\n return new UdpDriver(this.adapter, this.cfg, this.template, this.global);\n }\n throw new Error(`Unsupported protocol: ${proto}`);\n }\n\n /** @param {{backgroundInitialPoll?: boolean}} [options] */\n async start({ backgroundInitialPoll = false } = {}) {\n if (this.started) return;\n this.started = true;\n const lifecycleGeneration = ++this._lifecycleGeneration;\n\n if (this.cfg.enabled === false) {\n await this._invalidateQualifiedAliases();\n this.adapter.log.info(`[${this.cfg.id}] disabled - skipping`);\n return;\n }\n\n this.driver = this._createDriver();\n const startupDriver = this.driver;\n const current = () => this.started && this._lifecycleGeneration === lifecycleGeneration && this.driver === startupDriver;\n await this._invalidateQualifiedAliases();\n if (!current()) return;\n /** @param {() => Promise<void>} operation */\n const runInitial = async operation => {\n if (!backgroundInitialPoll) { await operation(); return; }\n // Hosted metadata readiness is independent of the first network response.\n // Retain the original promise so stop can cancel the transport and drain it.\n const pending = Promise.resolve().then(operation).catch(() => {\n if (current()) this.adapter.log.warn(`[${this.cfg.id}] EOS_DEVICES_INITIAL_POLL_FAILED; inspect device connection status`);\n });\n this._initialPollPromise = pending;\n void pending.then(() => { if (this._initialPollPromise === pending) this._initialPollPromise = null; });\n };\n\n // Heartbeat session init: start \"offline\" until we receive *real* data.\n // (We still keep the counter monotonic across restarts.)\n await this._loadHeartbeatStateFromDb().catch(() => {});\n this._hbLastSeen = 0;\n this._hbLastSourceStamp = 0;\n this._hbLastWriteAt = 0;\n this._hbOnline = false;\n await this._setStateCached(this._hbRelId('online'), false, true);\n await this._setStateCached(this._hbRelId('lastSeenMs'), 0, true);\n await this._resetAblEmh1LiveMeasurements();\n if (!current()) return;\n\n // Event-driven protocols (no polling)\n if (this.cfg.protocol === 'mqtt' || this.cfg.protocol === 'canbus') {\n this._liveAliasRefreshMs = this._computeLiveAliasRefreshMs({ isEventDriven: true });\n // Initialize before connect: the driver may already report a connection,\n // subscription failure or live values while connect() is still resolving.\n // Never overwrite those results with a synthetic success/empty error.\n await this._setStateCached(`${this.baseId}.info.connection`, false, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, '', true);\n await this._updateAliases({}, { connected: false, lastError: '' }).catch(() => {});\n await runInitial(async () => {\n if (!current()) return;\n try {\n await startupDriver.connect(this.getDatapoints());\n } catch (e) {\n if (current()) await this._setError(e);\n }\n if (!current()) return;\n // Heartbeat timeout for push protocols\n this._hbTimeoutMs = this._computeHeartbeatTimeoutMs({ isEventDriven: true });\n this._startHeartbeatChecker();\n });\n\n // Both event-driven drivers own their actual transport status; heartbeat\n // remains tied to received device data.\n return;\n }\n\n // polling (most protocols)\n const allDps = this.getDatapoints();\n\n const normMs = (v) => {\n const n = Number(v);\n return (Number.isFinite(n) && n > 0) ? n : 0;\n };\n\n // Highest priority: per-device UI override\n const cfgPollMs = normMs(this.cfg.pollIntervalMs);\n\n // Template-specific recommendation (useful when global poll interval is slow)\n const tplPollMs =\n normMs(this.template?.driverHints?.pollIntervalMs) ||\n normMs(this.template?.pollIntervalMs) ||\n 0;\n\n // Global default from adapter instance\n const globalPollMs = normMs(this.global.pollIntervalMs);\n\n // Optional split polling: fast subset every X ms + full refresh every Y ms.\n // This keeps key control signals (e.g. PV/grid/battery power) highly responsive\n // without spamming the device with a full register map on every cycle.\n const tplPolling = (this.template && this.template.driverHints) ? this.template.driverHints.polling : null;\n\n let fastIntervalMs = cfgPollMs || normMs(tplPolling && tplPolling.fastIntervalMs) || tplPollMs || globalPollMs || 5000;\n const forcedFastIntervalMs = normMs(tplPolling && (\n tplPolling.forceFastIntervalMs ??\n tplPolling.enforcedFastIntervalMs ??\n tplPolling.fixedFastIntervalMs\n ));\n if (forcedFastIntervalMs > 0) fastIntervalMs = forcedFastIntervalMs;\n const fixedFastCadence = !!(tplPolling && (\n tplPolling.fixedFastCadence === true ||\n tplPolling.fixedCadence === true ||\n tplPolling.startToStartCadence === true\n ));\n let slowIntervalMs = normMs(tplPolling && tplPolling.slowIntervalMs);\n\n let fastDps = allDps;\n let slowDps = allDps;\n let useSplitPolling = false;\n\n if (tplPolling && Array.isArray(tplPolling.fastDpIds) && tplPolling.fastDpIds.length) {\n const idSet = new Set(tplPolling.fastDpIds.map(x => String(x)));\n // BMS numeric limits are live control inputs, not static metadata. Keep\n // their already mapped read sources on the existing fast schedule only.\n for (const def of this.aliasDefs || []) {\n if (def.kind === 'dp' && def.rw === 'ro' && def.dpId &&\n ['r.allowedChargePower', 'r.allowedDischargePower'].includes(legacyAliasPath(def.relId))) {\n idSet.add(String(def.dpId));\n }\n }\n fastDps = allDps.filter(dp => dp && idSet.has(String(dp.id)));\n useSplitPolling = (fastDps.length > 0) && (slowIntervalMs > 0);\n }\n\n // Optional safe slow subset. Templates with very large register maps can keep fast live\n // values stable and avoid optional/reserved register ranges that some devices reject.\n if (tplPolling && Array.isArray(tplPolling.slowDpIds) && tplPolling.slowDpIds.length) {\n const slowIdSet = new Set(tplPolling.slowDpIds.map(x => String(x)));\n const filteredSlowDps = allDps.filter(dp => dp && slowIdSet.has(String(dp.id)));\n if (filteredSlowDps.length > 0) slowDps = filteredSlowDps;\n }\n\n const clampInterval = (ms) => {\n const n = normMs(ms);\n return Math.max(250, n || 0);\n };\n\n fastIntervalMs = clampInterval(fastIntervalMs);\n if (useSplitPolling) slowIntervalMs = clampInterval(slowIntervalMs);\n this._liveAliasRefreshMs = this._computeLiveAliasRefreshMs({ fastIntervalMs, isEventDriven: false });\n this._qualifiedAliasSamples.clear();\n this._qualifiedAliasMaxAgeMs = (useSplitPolling ? slowIntervalMs : fastIntervalMs) + 10000;\n\n // Heartbeat timeout derived from polling interval (unless overridden).\n this._hbTimeoutMs = this._computeHeartbeatTimeoutMs({ fastIntervalMs, isEventDriven: false });\n this._startHeartbeatChecker();\n\n // Optional write throttling & command cadence scheduling (template hinted).\n //\n // SolaX Modbus specs recommend a minimum 1s interval between instructions; enabling a 1Hz command cadence\n // lets us interleave reads (e.g. every 3s) and writes (1Hz) without overloading or locking up the device.\n const tplModbusHints = this.template?.driverHints?.modbus;\n\n const writeThrottleMs = normMs(tplModbusHints && (tplModbusHints.writeThrottleMs || tplModbusHints.writeIntervalMs));\n const writeMaxPerTickRaw = Number(tplModbusHints && tplModbusHints.writeMaxPerTick);\n\n this._writeThrottleMs = (writeThrottleMs > 0) ? clampInterval(writeThrottleMs) : 0;\n this._writeQueueEnabled = this._writeThrottleMs > 0;\n this._writeQueueMaxPerTick = (Number.isFinite(writeMaxPerTickRaw) && writeMaxPerTickRaw > 0) ? Math.max(1, Math.floor(writeMaxPerTickRaw)) : 1;\n\n const isModbus = String(this.cfg.protocol || '').startsWith('modbus');\n const commandCadenceRaw = normMs(tplModbusHints && tplModbusHints.commandCadenceMs);\n this._commandCadenceMs = (isModbus && commandCadenceRaw > 0) ? clampInterval(commandCadenceRaw) : 0;\n this._useCommandCadenceScheduler = this._commandCadenceMs > 0;\n\n // Reset per-start runtime state\n this._writeQueue.clear();\n this._lastSuccessfulQueuedValueByDpId.clear();\n this._writeBusy = false;\n\n // Optional: restore last control setpoints on start/reconnect (template hinted).\n // We capture the current dp state values *before* the first poll overwrites them,\n // so upgrades keep their last setpoint even if the device rebooted.\n try {\n this._restoreCfg = this._getRestoreSetpointsConfig();\n const ids = (this._restoreCfg && Array.isArray(this._restoreCfg.dpIds)) ? this._restoreCfg.dpIds : [];\n this._restoreDpIds = new Set((ids || []).map(v => String(v)).filter(v => v && v.trim()));\n this._restoreFallback = new Map();\n\n if (this._restoreCfg && this._restoreDpIds.size) {\n for (const dpId of this._restoreDpIds) {\n const dp = this._getDpById(dpId);\n if (!dp) continue;\n const st = await this.adapter.getStateAsync(this.relStateId(dp)).catch(() => null);\n if (st && st.val !== null && st.val !== undefined) {\n this._restoreFallback.set(String(dp.id), st.val);\n }\n }\n }\n } catch (e) {\n this.adapter.log.debug(`[${this.cfg.id}] restore-setpoints init failed: ${e && e.message ? e.message : e}`);\n this._restoreCfg = null;\n this._restoreDpIds = new Set();\n this._restoreFallback = new Map();\n }\n\n\n const doPoll = async (dps) => {\n if (!current()) return;\n const pollDps = Array.isArray(dps) ? dps : allDps;\n try {\n const wasOk = this._connOk;\n const values = await startupDriver.readDatapoints(pollDps);\n if (!current()) return;\n const hasData = values && typeof values === 'object' && Object.entries(values).some(([id, value]) =>\n this.dpById.has(id) && value !== null && value !== undefined &&\n (typeof value !== 'number' || Number.isFinite(value))\n );\n if (!hasData) throw new Error('Read completed without usable device datapoints');\n this._connOk = true;\n\n // Restore persistent control setpoints once after a successful (re)connect.\n // This helps if the device resets its setpoints after a reboot (e.g. PV export limit).\n if (!wasOk) {\n try { this._scheduleRestoreSetpoints('reconnect'); } catch (_) {}\n }\n\n await this._setStateCached(`${this.baseId}.info.connection`, true, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, '', true);\n\n // Heartbeat tick: mark device alive only when we received real data.\n // Special case Speedwire: only tick when a NEW telegram arrived (driver.lastSeen changed).\n try {\n const proto = String(this.cfg?.protocol || '').toLowerCase();\n if (proto === 'speedwire') {\n const stamp = Number(this.driver?.lastSeen || 0);\n const staleMs = Number(this.driver?.staleTimeoutMs || this.cfg?.connection?.staleTimeoutMs || 30000);\n const age = stamp > 0 ? (Date.now() - stamp) : Number.POSITIVE_INFINITY;\n // Only tick if the telegram is still considered fresh.\n if (stamp > 0 && (!Number.isFinite(staleMs) || staleMs <= 0 || age <= staleMs)) {\n await this._tickHeartbeatFromIncomingData(stamp);\n }\n } else {\n await this._tickHeartbeatFromIncomingData();\n }\n } catch (_) {\n // ignore\n }\n\n for (const [dpId, rawVal] of Object.entries(values)) {\n if (!current()) return;\n const dp = this.dpById.get(dpId);\n if (!dp) continue;\n\n let val = rawVal;\n\n // Unit-specific normalization (no address changes, only value formatting)\n // VARTA public 14 has an explicit 0.01 Hz unit. Do not run generic\n // frequency auto-correction over already decoded manufacturer data.\n if (!getVartaProfile(this.template) && !getDeyeProfile(this.template)) val = normalizeValueByUnit(val, dp);\n\n // Rounding of numeric values (avoid Modbus scaling artefacts, keep consistent UI output).\n const decimals = this._getRoundingDecimals(dp);\n if (typeof val === 'number' && Number.isFinite(val) && typeof decimals === 'number' && decimals >= 0 && decimals <= 10) {\n val = roundTo(val, decimals);\n }\n\n // Ensure aliases get the same processed value (unit conversion happens in the driver, rounding here).\n values[dpId] = val;\n\n const relId = this.relStateId(dp);\n await this._setStateCached(relId, val, true);\n }\n\n if (current()) await this._updateAliases(values, { connected: true, lastError: '' });\n } catch (e) {\n if (current()) await this._setError(e);\n }\n };\n\n // Initial poll: by default refresh the slow/full set once.\n // Some devices close the Modbus session on optional/unsupported registers; templates can\n // start with the fast set first so core data comes online immediately.\n const initialFastOnly = !!(tplPolling && (tplPolling.initialFastOnly === true || String(tplPolling.initialFastOnly).toLowerCase() === 'true'));\n const initializePolling = async () => {\n await doPoll(initialFastOnly ? fastDps : slowDps);\n if (!current()) return;\n\n // Self-scheduling poll loop (prevents overlaps/backlog and keeps cadence stable).\n this._pollLoopActive = true;\n\n const self = this;\n let nextFastAt = Date.now() + fastIntervalMs;\n let nextSlowAt = useSplitPolling ? (Date.now() + slowIntervalMs) : Number.POSITIVE_INFINITY;\n\n let loopFn = null;\n\n function scheduleNext(delay) {\n if (!current() || !self._pollLoopActive) return;\n const d = Math.max(0, Number(delay) || 0);\n if (self.pollTimer) {\n clearTimeout(self.pollTimer);\n self.pollTimer = null;\n }\n self.pollTimer = setTimeout(() => {\n if (loopFn) loopFn().catch(() => {});\n }, Math.max(fixedFastCadence ? 25 : 250, d));\n }\n\n async function pollLoop() {\n if (!current() || !self._pollLoopActive || !self.driver) return;\n\n const cycleStartedAt = Date.now();\n const now = cycleStartedAt;\n const runSlow = useSplitPolling && now >= nextSlowAt;\n\n // Default profiles schedule from completion to avoid catch-up loops. Fast closed-loop\n // profiles may opt into a fixed start-to-start cadence. If a poll overruns its target,\n // the self-scheduling loop still never overlaps; it simply continues as soon as safe.\n if (runSlow) {\n await doPoll(slowDps);\n } else {\n await doPoll(fastDps);\n }\n\n const finishedAt = Date.now();\n const nextFastBaseAt = fixedFastCadence ? cycleStartedAt : finishedAt;\n if (runSlow) {\n nextSlowAt = finishedAt + slowIntervalMs;\n nextFastAt = Math.max(finishedAt, nextFastBaseAt + fastIntervalMs);\n } else {\n nextFastAt = Math.max(finishedAt, nextFastBaseAt + fastIntervalMs);\n }\n\n if (!current() || !self._pollLoopActive || !self.driver) return;\n\n const nextAt = Math.min(nextFastAt, nextSlowAt);\n scheduleNext(nextAt - Date.now());\n }\n\n let writeCyclesSincePoll = 0;\n async function cadenceLoop() {\n if (!current() || !self._pollLoopActive || !self.driver) return;\n\n const cycleStartedAt = Date.now();\n const now = cycleStartedAt;\n const runSlow = useSplitPolling && now >= nextSlowAt;\n const runFast = now >= nextFastAt;\n\n const hasQueuedWrites = !!(self._writeQueue && self._writeQueue.size > 0);\n const nextWrite = hasQueuedWrites ? self._pickNextQueuedWrite() : null;\n const queued = nextWrite && nextWrite[1];\n // A new zero power/current command gets one extra slot before a due read.\n // Repeated already-sent zero commands must not keep an offline/freshness\n // stop loop from obtaining the measurements needed to recover safely.\n const urgentStop = queued && queued.deviceValue === 0 && !queued.meta?.isPreWrite &&\n ['W', 'kW', 'A'].includes(queued.dp?.unit) &&\n self._lastSuccessfulQueuedValueByDpId.get(String(queued.dp.id)) !== 0;\n const readDue = runSlow || runFast;\n const writeBeforeRead = !readDue || writeCyclesSincePoll === 0 || (urgentStop && writeCyclesSincePoll < 2);\n\n // Preserve the configured command spacing and the queue's pre-write /\n // coalescing rules, but bound read starvation when EMS writes every tick.\n if (hasQueuedWrites && writeBeforeRead) {\n const maxWrites = Math.max(1, Number(self._writeQueueMaxPerTick || 1));\n for (let i = 0; i < maxWrites; i++) {\n await self._flushWriteQueueOnce();\n if (!self._writeQueue || self._writeQueue.size === 0) break;\n }\n writeCyclesSincePoll++;\n } else if (runSlow) {\n await doPoll(slowDps);\n writeCyclesSincePoll = 0;\n const finishedAt = Date.now();\n const nextFastBaseAt = fixedFastCadence ? cycleStartedAt : finishedAt;\n nextSlowAt = finishedAt + slowIntervalMs;\n nextFastAt = Math.max(finishedAt, nextFastBaseAt + fastIntervalMs);\n } else if (runFast) {\n await doPoll(fastDps);\n writeCyclesSincePoll = 0;\n const finishedAt = Date.now();\n const nextFastBaseAt = fixedFastCadence ? cycleStartedAt : finishedAt;\n nextFastAt = Math.max(finishedAt, nextFastBaseAt + fastIntervalMs);\n }\n\n if (!current() || !self._pollLoopActive || !self.driver) return;\n scheduleNext(self._commandCadenceMs);\n }\n\n // Decide which scheduler to use\n loopFn = self._useCommandCadenceScheduler ? cadenceLoop : pollLoop;\n\n if (self._useCommandCadenceScheduler) {\n // Tick-based cadence scheduler (e.g., 1000ms) to stay within strict Modbus timing constraints.\n scheduleNext(self._commandCadenceMs);\n } else {\n // Start after the fast interval (initial full refresh has already happened).\n scheduleNext(nextFastAt - Date.now());\n\n // If writes are throttled via queue and we do not use the cadence scheduler, start the write loop.\n if (self._writeQueueEnabled) self._startWriteLoop();\n }\n\n // Optional template-defined Modbus watchdog auto-writes (e.g., TESVOLT VK interface).\n await this._startAutoWatchdogs();\n if (!current()) return;\n // Seed watchdog/keepalive command memory from persistent command aliases after restarts.\n await this._seedSetpointKeepaliveFromCommandAliases().catch(e => {\n this.adapter.log.debug(`[${this.cfg.id}] SetpointKeepalive seed failed: ${e && e.message ? e.message : e}`);\n });\n if (!current()) return;\n await this._startSetpointKeepalive();\n if (!current()) return;\n await this._startSungrowExternalEmsHeartbeat();\n };\n await runInitial(initializePolling);\n }\n\n _isVartaLogicalWriteError(error) {\n if (!getVartaProfile(this.template)) return false;\n // These codes describe command rejection or failed confirmation after valid\n // responses, not a broken transport. Invalid/short responses, cancellation\n // after reset, and network errors deliberately remain outside this list.\n return new Set([\n 'E_VARTA_LIMIT_CLASS', 'E_VARTA_WRITE_LOCKED', 'E_VARTA_FREQUENCY_LOCKED',\n 'E_VARTA_READ_ONLY', 'E_VARTA_WRITE_VALUE', 'E_VARTA_WRITE_BUSY',\n 'E_VARTA_WRITE_UNAVAILABLE', 'E_VARTA_WRITE_DISCOVERY_PENDING',\n 'E_VARTA_COMMAND_EXPIRED', 'E_VARTA_SUPERSEDED', 'E_VARTA_NOT_READY',\n 'E_VARTA_AUTH', 'E_VARTA_WRITE_VERIFY', 'E_VARTA_WRITE_IDENTITY', 'E_VARTA_LIMIT_INACTIVE',\n ]).has(String(error?.code || ''));\n }\n\n async _setError(e) {\n const err = e || {};\n const code = (err && err.code) ? String(err.code) : '';\n let msg = (err && err.message) ? err.message : String(err);\n const lower = String(msg).toLowerCase();\n\n if (getVartaProfile(this.template) && code === 'E_VARTA_SUPERSEDED') {\n // Replacing an unsent command is normal coalescing, not a device fault.\n // Keep any real diagnostic intact and do not acknowledge the old request.\n const now = Date.now();\n if (this._vartaLastSupersededDebugAt === undefined || now - this._vartaLastSupersededDebugAt >= 60000) {\n this._vartaLastSupersededDebugAt = now;\n this.adapter.log.debug(`[${this.cfg.id}] E_VARTA_SUPERSEDED: A queued command was replaced by a newer request; the superseded request was not acknowledged.`);\n }\n return;\n }\n\n if (this._isSuppressedUnsupportedWriteError(err)) {\n try { this._handleSuppressedUnsupportedWrite(err, err && err.nexowattDpId ? String(err.nexowattDpId) : ''); } catch (_) {}\n await this._setStateCached(`${this.baseId}.info.connection`, !!this._connOk, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, msg, true);\n return;\n }\n\n const tplIdLowerForError = String(this.template?.id || '').toLowerCase();\n const mfrLowerForError = String(this.template?.manufacturer || '').toLowerCase();\n const isAlfenForError = mfrLowerForError === 'alfen' || tplIdLowerForError.includes('alfen');\n\n const transportCodes = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'ERR_SOCKET_CLOSED',\n 'E_MODBUS_OPERATION_TIMEOUT',\n 'E_MODBUS_CONNECT_TIMEOUT',\n 'E_MODBUS_BUSY_STALE',\n ]);\n const isTransport = transportCodes.has(code) || lower.includes('port not open') || lower.includes('timed out') || lower.includes('timeout');\n const isWriteOperation = String(err && (err.nexowattOperation || err.operation || '')).toLowerCase() === 'write';\n if (isWriteOperation && !isTransport && this._looksLikePermanentModbusWriteReject(msg)) {\n try { this._markWriteTemporarilyUnsupported(err && err.nexowattDpId ? String(err.nexowattDpId) : '', msg); } catch (_) {}\n }\n const readErrorGraceMs = this._normalizeMs(\n this.template?.driverHints?.modbus?.readErrorGraceMs ??\n this.template?.driverHints?.readErrorGraceMs ??\n this.cfg?.connection?.readErrorGraceMs\n );\n const recentHeartbeat = readErrorGraceMs > 0 && this._hbLastSeen > 0 && (Date.now() - Number(this._hbLastSeen)) <= readErrorGraceMs;\n const invalidVartaResponse = !!getVartaProfile(this.template) && code === 'E_VARTA_RESPONSE';\n const keepConnectionState = !invalidVartaResponse && !isTransport &&\n (isWriteOperation || this._isVartaLogicalWriteError(err) || recentHeartbeat);\n\n // A rejected write value/register is not the same as a lost TCP/Modbus connection.\n // Likewise, a single non-transport read rejection shortly after a successful heartbeat\n // should not make a busy wallbox flap online/offline. Transport errors still mark the\n // device offline immediately, and repeated read failures go offline once the grace expires.\n if (!keepConnectionState) this._connOk = false;\n\n const host = this.cfg?.connection?.host;\n const port = Number(this.cfg?.connection?.port || 502);\n\n const addHint = (hint) => {\n if (!hint) return;\n // Avoid hint duplication on repeated retries.\n if (msg.includes(`| Hint:`) && msg.includes(hint)) return;\n msg = `${msg} | Hint: ${hint}`;\n };\n\n // --- Transport-layer hints ---\n if (code === 'ECONNREFUSED') {\n if (isAlfenForError) {\n addHint(\n `TCP connection to ${host || 'device'}:${port} was refused. ` +\n `For Alfen ACE this usually means the Modbus server is disabled/restarting, Active Load Balancing/EMS is not active, ` +\n `the charger temporarily refuses additional clients, or another Modbus client still holds one of the limited TCP sessions.`\n );\n } else {\n addHint(\n `TCP connection to ${host || 'device'}:${port} was refused. ` +\n `This usually means the Modbus TCP server is disabled on the device, the IP/port is wrong, ` +\n `or a firewall/ACL actively rejects the connection. ` +\n `For SMA: ensure SMA Modbus/SunSpec Modbus is enabled and verify whether you must connect to a Data Manager instead of the inverter.`\n );\n }\n } else if (code === 'ETIMEDOUT') {\n addHint(\n `TCP connection timed out (no response). This typically indicates packet filtering (firewall), wrong IP/route, ` +\n `or that port ${port} is not reachable from the ioBroker host.`\n );\n } else if (code === 'ENOTFOUND') {\n addHint(`Host name could not be resolved. Check the Host/IP field.`);\n } else if (code === 'EHOSTUNREACH' || code === 'ENETUNREACH') {\n addHint(`Network unreachable. Check routing/VLAN/gateway and that the device is powered on.`);\n }\n\n // --- Modbus-layer hints (best-effort) ---\n\n // modbus-serial commonly reports this when the underlying TCP socket/serial port is closed\n if (lower.includes('port not open')) {\n addHint(\n `The Modbus client port is not open (socket/serial closed). ` +\n `If this is Modbus TCP, the device or network likely closed the connection; the adapter will reconnect automatically. ` +\n `If this is Modbus RTU, check the serial path/permissions and whether the USB/RS485 adapter is still present.`\n );\n }\n if (lower.includes('illegal data address') || lower.includes('exception code') || lower.includes('illegal function')) {\n const isAlfen = isAlfenForError;\n\n if (isAlfen) {\n addHint(\n `Alfen-specific: the canonical template uses the official ACE protocol addresses (document register minus 1) and fixed Unit-IDs. ` +\n `After exception 2 the driver also probes the direct table-address compatibility layout (for Max Current: UID1/2 FC16@1210). ` +\n `If both @1209 and @1210 are rejected, the charger is answering but maximum-current writes are not exposed/enabled in the current ACE configuration.`\n );\n if (lower.includes('set_charging_current') || lower.includes('fc16@1209') || lower.includes('fc16@1210') || lower.includes('1199-1214')) {\n addHint(\n `Open ACE Advanced Settings, enable Allow writing maximum currents and Enable sockets, keep Active Load Balancing/Data Source=Energy Management System, and set TCP/IP EMS Control Mode=Socket for Unit-ID 1. ` +\n `If the charger firmware/profile does not support these registers, the adapter can read meter power but cannot release/control charging through Modbus.`\n );\n }\n } else {\n const mfr = String(this.cfg?.manufacturer || this.template?.manufacturer || '').toUpperCase();\n const tpl = String(this.template?.id || this.cfg?.templateId || '');\n if (getVartaProfile(this.template)) {\n addHint(\n `VARTA table 14: verify the selected model, table version and extended-register support. ` +\n `Frequency-control registers require activation by VARTA. Only documented FC3/FC6 addresses are used; ` +\n `no address-offset probing or FC16 fallback. Pextra is additional power, not an absolute power setpoint.`\n );\n } else if (getDeyeProfile(this.template)) {\n addHint('DEYE: verify hybrid family, firmware, RTU address and 9600 8N1. Literal addresses only; no offset probing. Remote power commands remain unavailable.');\n } else if (mfr === 'KEBA' || /keba/i.test(tpl)) {\n addHint(\n `KEBA-specific: P40 Modbus TCP normally uses Unit-ID 255. ` +\n `The P40 also rejects reads that cross unsupported register gaps, so use the KEBA P40 safe template/profile and keep Address-Offset at 0.`\n );\n } else if (mfr === 'FENECON' || /fenecon/i.test(tpl)) {\n addHint(\n `FENECON-specific: the TCP connection is working, but this register group is not supported by the selected FENECON profile. ` +\n `Verify Home/Commercial/Mini/DESS template, Unit-ID and Address-Offset 0.`\n );\n } else {\n addHint(\n `Modbus responded but the register address/function is invalid. ` +\n `Check Address-Offset (often -1 vs 0), ensure the correct vendor template/profile, and verify Unit-ID.`\n );\n }\n }\n }\n if (lower.includes('illegal data value') || lower.includes('exception 3')) {\n if (getVartaProfile(this.template)) {\n addHint(`VARTA FC6: check the selected model, write permissions, live scale factor and register value range. UG is negative and OG positive; nonzero limits must meet the confirmed residential/commercial minimum. No alternate write function or automatic retry is used.`);\n } else addHint(\n `Modbus accepted the connection but rejected the written value/register combination. ` +\n `Check the writable mode on the device, value range, Unit-ID, and whether 32-bit values are written as one complete FC16 block.`\n );\n }\n if (lower.includes('timed out') && code !== 'ETIMEDOUT') {\n addHint(\n `Modbus timeout. If TCP connects but reads time out, check Unit-ID, allowed Modbus clients, and whether another client (e.g., Data Manager/SCADA) is already connected.`\n );\n }\n\n // --- Speedwire (UDP multicast) hints ---\n if (code === 'E_SPEEDWIRE_NO_DATA' || code === 'E_SPEEDWIRE_STALE' || lower.includes('speedwire')) {\n addHint(\n `Speedwire uses UDP multicast (typically 239.12.255.254:9522). ` +\n `Ensure the ioBroker host is in the same L2 network, multicast is not blocked, and your switch/router supports IGMP (v2). ` +\n `In virtualized setups (Docker/LXC/VM), ensure multicast traffic reaches the container/VM (bridge/host-networking).`\n );\n }\n\n // SMA Energy Meter note (common pitfall): it is Speedwire-based, not Modbus TCP on port 502.\n if (code === 'ECONNREFUSED' && String(this.cfg?.manufacturer || '').toUpperCase() === 'SMA' && String(this.cfg?.category || '').toUpperCase() === 'METER') {\n addHint(\n `If this is an SMA Energy Meter: it usually does NOT provide a Modbus TCP server on port 502. ` +\n `Use the Speedwire (UDP) protocol/template instead, or connect to Sunny Home Manager/Data Manager if you need Modbus.`\n );\n }\n\n \n // For transport layer errors we proactively close the driver so the next poll triggers a clean reconnect.\n try {\n if (isTransport && this.driver && typeof this.driver.disconnect === 'function') {\n // Force-close the stale transport before the next poll schedules a reconnect. Awaiting here\n // avoids races where a late disconnect closes a freshly opened TCP socket.\n if (getVartaProfile(this.template) || getDeyeProfile(this.template)) {\n // Dedicated drivers: terminal disconnect cancels the endpoint scheduler. A transient\n // network failure must reset only transport, retaining poll/reconnect.\n await this.driver.resetTransport().catch(() => {});\n } else {\n await this.driver.disconnect().catch(() => {});\n }\n\n // If we lost transport, re-apply any required pre-writes after reconnect.\n if (this._preWriteLastTsByTrigger) this._preWriteLastTsByTrigger.clear();\n }\n } catch (_) {\n // ignore\n }\n\n // Throttle repetitive error logs (same message) to avoid flooding the log.\n const now = Date.now();\n const throttleMs = Number(this.global.errorLogThrottleMs || 30000);\n const shouldLog = (msg !== this._lastErrorLogMsg) || (!this._lastErrorLogTs) || ((now - this._lastErrorLogTs) > throttleMs);\n if (shouldLog) {\n this._lastErrorLogMsg = msg;\n this._lastErrorLogTs = now;\n this.adapter.log.warn(`[${this.cfg.id}] ${msg}`);\n }\n\n await this._setStateCached(`${this.baseId}.info.connection`, !!this._connOk, true);\n await this._setStateCached(`${this.baseId}.info.lastError`, msg, true);\n await this._updateAliases({}, { connected: !!this._connOk, lastError: msg }).catch(() => {});\n }\n\n async stop() {\n ++this._lifecycleGeneration;\n this.started = false;\n const initialPoll = this._initialPollPromise;\n this._pollLoopActive = false;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.watchdogTimer) {\n clearInterval(this.watchdogTimer);\n this.watchdogTimer = null;\n }\n if (this.watchdogStartTimer) {\n clearTimeout(this.watchdogStartTimer);\n this.watchdogStartTimer = null;\n }\n\n // Stop optional setpoint keepalive\n if (this._setpointKeepaliveTimer) {\n try { clearInterval(this._setpointKeepaliveTimer); } catch (_) {}\n this._setpointKeepaliveTimer = null;\n }\n this._setpointKeepaliveBusy = false;\n\n // Stop optional Sungrow External-EMS heartbeat auto-refresh\n if (this._sungrowHeartbeatTimer) {\n try { clearInterval(this._sungrowHeartbeatTimer); } catch (_) {}\n this._sungrowHeartbeatTimer = null;\n }\n if (this._sungrowHeartbeatStartTimer) {\n try { clearTimeout(this._sungrowHeartbeatStartTimer); } catch (_) {}\n this._sungrowHeartbeatStartTimer = null;\n }\n this._sungrowHeartbeatBusy = false;\n\n // Stop optional post-write confirmation repeats\n if (this._postWriteRepeatTimersByDpId && this._postWriteRepeatTimersByDpId.size) {\n for (const timer of this._postWriteRepeatTimersByDpId.values()) {\n try { clearTimeout(timer); } catch (_) {}\n }\n this._postWriteRepeatTimersByDpId.clear();\n }\n\n // Stop optional setpoint restore scheduler\n if (this._restoreTimer) {\n try { clearTimeout(this._restoreTimer); } catch (_) {}\n this._restoreTimer = null;\n }\n this._restoreBusy = false;\n\n\n // Stop heartbeat checker\n if (this._hbCheckTimer) {\n try { clearInterval(this._hbCheckTimer); } catch (_) {}\n this._hbCheckTimer = null;\n }\n if (this._aliasMetadataRefreshTimer) {\n try { clearTimeout(this._aliasMetadataRefreshTimer); } catch (_) {}\n this._aliasMetadataRefreshTimer = null;\n }\n // Mark offline on stop (fail-safe)\n for (const relId of this._hbRelIds('online')) {\n await this._setStateCached(relId, false, true);\n }\n this._hbOnline = false;\n\n // Stop optional write loop and clear queued writes\n await this._invalidateQualifiedAliases();\n try {\n this._writeQueueEnabled = false;\n this._stopWriteLoop();\n if (this._writeQueue) this._writeQueue.clear();\n this._writeBusy = false;\n } catch (e) {\n // ignore\n }\n if (this.driver) {\n try { await this.driver.disconnect(); } catch (e) { /* ignore */ }\n this.driver = null;\n }\n if (initialPoll) await initialPoll;\n this.started = false;\n }\n\n _recordWrite(dpId, opts = {}) {\n if (!dpId) return;\n const key = String(dpId);\n const now = Date.now();\n try {\n this._lastWriteByDpId.set(key, now);\n // A successful direct/user write already refreshes the device-side validity timer.\n // Let the cyclic keepalive count from that real write; otherwise the adapter can\n // write again too early and then leave a gap that is too long for a charger watchdog.\n if (this._setpointKeepaliveLastWriteByDpId) this._setpointKeepaliveLastWriteByDpId.set(key, now);\n } catch (e) {\n // ignore\n }\n\n // Mutually exclusive setpoints (e.g. Sungrow signed/charge/discharge helpers)\n // must not let an older delayed repeat overwrite the newest user command.\n try { this._cancelExclusiveSetpointPeerPostRepeats(key); } catch (_) {}\n\n if (!opts || opts.skipPostWriteRepeat !== true) {\n try { this._schedulePostWriteRepeat(key); } catch (_) {}\n }\n }\n\n _looksLikePermanentModbusWriteReject(msg) {\n return /modbus\\s+exception\\s+(2|3)\\b|illegal\\s+data\\s+(address|value)|register\\s+not\\s+supported|cannot\\s+be\\s+written/i.test(String(msg || ''));\n }\n\n _isSuppressedUnsupportedWriteError(e) {\n if (!e) return false;\n const code = String(e.code || '');\n return code === 'E_NEXOWATT_WRITE_UNSUPPORTED' || e.nexowattSuppressWarn === true || e.nexowattUnsupportedWrite === true;\n }\n\n _isAlfenTemplate() {\n const tplId = String(this.template?.id || '').toLowerCase();\n const mfr = String(this.template?.manufacturer || this.cfg?.manufacturer || '').toLowerCase();\n return mfr === 'alfen' || tplId.includes('alfen');\n }\n\n _isFeneconHomeEssTemplate() {\n return this.template?.id === 'ess.fenecon.FeneconHomeEssImpl';\n }\n\n\n _getAlfenHints() {\n const top = (this.template && this.template.alfen && typeof this.template.alfen === 'object') ? this.template.alfen : {};\n const driver = (this.template && this.template.driverHints && this.template.driverHints.alfen && typeof this.template.driverHints.alfen === 'object') ? this.template.driverHints.alfen : {};\n const modbus = (this.template && this.template.driverHints && this.template.driverHints.modbus && this.template.driverHints.modbus.alfen && typeof this.template.driverHints.modbus.alfen === 'object') ? this.template.driverHints.modbus.alfen : {};\n return Object.assign({}, top, driver, modbus);\n }\n\n _handleAlfenRejectedControlWrite(e, dpId) {\n const msg = (e && e.message) ? String(e.message) : String(e);\n const id = String(dpId || e?.nexowattDpId || '');\n if (id) this._markWriteTemporarilyUnsupported(id, msg);\n if (id) this._logSkippedUnsupportedWrite(id);\n // Keep Alfen meter polling clean: unsupported/not-enabled EMS control is a feature\n // state of the charger, not a transport error and not a reason to flood warn logs.\n }\n\n _handleSuppressedUnsupportedWrite(e, dpId) {\n const id = String(dpId || e?.nexowattDpId || '');\n if (id) this._markWriteTemporarilyUnsupported(id, e && e.message ? e.message : String(e));\n if (id) this._logSkippedUnsupportedWrite(id);\n }\n\n _unsupportedWriteCooldownMs() {\n const modHints = this.template?.driverHints?.modbus || {};\n const raw = Number(modHints.unsupportedWriteCooldownMs ?? modHints.writeRejectBackoffMs ?? modHints.setpointKeepaliveUnsupportedBackoffMs ?? 0);\n return Number.isFinite(raw) && raw > 0 ? raw : 0;\n }\n\n _markWriteTemporarilyUnsupported(dpId, msg) {\n if (!dpId) return;\n const cooldownMs = this._unsupportedWriteCooldownMs();\n if (!cooldownMs) return;\n try {\n this._setpointKeepaliveUnsupportedUntilByDpId.set(String(dpId), Date.now() + cooldownMs);\n } catch (_) {}\n }\n\n _clearWriteTemporarilyUnsupported(dpId) {\n if (!dpId) return;\n try {\n this._setpointKeepaliveUnsupportedUntilByDpId.delete(String(dpId));\n } catch (_) {}\n }\n\n _isWriteTemporarilyUnsupported(dpId) {\n if (!dpId) return false;\n try {\n const until = Number(this._setpointKeepaliveUnsupportedUntilByDpId.get(String(dpId)) || 0);\n return !!(until && Date.now() < until);\n } catch (_) {\n return false;\n }\n }\n\n _logSkippedUnsupportedWrite(dpId) {\n if (!dpId) return;\n const now = Date.now();\n const key = String(dpId);\n const last = Number(this._unsupportedWriteSkipLogTsByDpId.get(key) || 0);\n if (last && (now - last) < 60000) return;\n this._unsupportedWriteSkipLogTsByDpId.set(key, now);\n const until = Number(this._setpointKeepaliveUnsupportedUntilByDpId.get(key) || 0);\n const remainS = until > now ? Math.ceil((until - now) / 1000) : 0;\n this.adapter.log.debug(`[${this.cfg.id}] Write ${key} skipped temporarily because the device rejected this register/value recently${remainS ? `; retry in ~${remainS}s` : ''}.`);\n }\n\n _isWriteQueueEnabled() {\n return !!(this._writeQueueEnabled && this._writeThrottleMs > 0);\n }\n\n _alfenMirrorCommandDpIds(dpId) {\n if (!this._isAlfenTemplate || !this._isAlfenTemplate()) return [];\n // 0.5.124: do not mirror user command memory automatically. Field data showed\n // UID2 and UID200 are often not enabled (SCN_MAX_CURRENT_ENABLE=0, Socket-2\n // returns illegal address). Mirroring kept stale 16 A / 1-phase values alive and\n // produced misleading warning spam. Socket-2 and SCN datapoints remain manually\n // writable; only the public aliases now control the selected primary socket.\n return [];\n }\n\n _rememberAlfenMirrorCommandValues(dpId, valueToRemember, opts = {}) {\n if (!this._isAlfenTemplate || !this._isAlfenTemplate()) return;\n const mirrors = this._alfenMirrorCommandDpIds(dpId);\n if (!mirrors.length) return;\n const now = Date.now();\n const markEverWritten = opts.markEverWritten !== false;\n for (const mirrorId of mirrors) {\n try {\n const mirrorDp = this._getDpById(mirrorId);\n if (!mirrorDp || !(mirrorDp.rw === 'rw' || mirrorDp.rw === 'wo')) continue;\n const key = String(mirrorDp.id);\n if (this._lastCommandedValueByDpId) this._lastCommandedValueByDpId.set(key, valueToRemember);\n // For All-IDs mode the physical primary write may only be Socket 1, while\n // the device actually accounts for SCN values. Mark mirror targets as\n // eligible for watchdog refresh as soon as the primary command exists; the\n // write itself is still best-effort and unsupported IDs back off normally.\n if (markEverWritten && this._lastWriteByDpId) this._lastWriteByDpId.set(key, now - 60000);\n if (this._setpointKeepaliveLastWriteByDpId) this._setpointKeepaliveLastWriteByDpId.set(key, 0);\n } catch (_) {\n // ignore one broken optional mirror target\n }\n }\n }\n\n _rememberCommandedValue(dpId, deviceValue) {\n if (!dpId) return;\n const key = String(dpId);\n try {\n let valueToRemember = deviceValue;\n // Normalize numeric command strings like \"16 A\" / \"3 phases\" before they are\n // used by the Alfen watchdog. Non-numeric strings remain unchanged.\n const n = (typeof this._parseNumberWithUnits === 'function') ? this._parseNumberWithUnits(deviceValue) : undefined;\n if (Number.isFinite(n)) valueToRemember = n;\n if (this._lastCommandedValueByDpId) this._lastCommandedValueByDpId.set(key, valueToRemember);\n\n // Preserve only an active ABL Icmax PWM command. A later 100 % pause must not\n // erase the value that ctrl.run/ctrl.chargeEnable should restore on resume.\n try {\n const tplIdLower = String(this.template?.id || '').toLowerCase();\n const mfrLower = String(this.template?.manufacturer || '').toLowerCase();\n const isAblEmh1 = (mfrLower === 'abl') || tplIdLower.startsWith('evcs.abl.');\n if (isAblEmh1 && key.toLowerCase() === 'set_icmax_duty_cycle_pct') {\n const pct = Number(valueToRemember);\n if (Number.isFinite(pct) && pct >= 10 && pct <= 96 && this._ablLastActiveDutyPctByDpId) {\n this._ablLastActiveDutyPctByDpId.set(key, Math.floor((pct + 1e-9) * 10) / 10);\n }\n }\n } catch (_) {}\n\n // A new user command must be picked up by watchdog immediately, even if the\n // physical Modbus write is queued or has to be retried.\n if (this._setpointKeepaliveLastWriteByDpId) this._setpointKeepaliveLastWriteByDpId.set(key, 0);\n this._rememberAlfenMirrorCommandValues(key, valueToRemember, { markEverWritten: true });\n } catch (_) {\n // ignore\n }\n }\n\n\n _enqueuePreWritesForDp(dpId) {\n // In throttled mode we enqueue pre-writes as separate queued writes, so we keep a strict\n // one-modbus-command-per-cadence behaviour (SolaX doc: >=1s between instructions).\n const plan = this._getPreWritesForDp(dpId);\n if (!plan.length) return;\n\n const triggerKey = String(dpId).toLowerCase();\n const now = Date.now();\n const cooldownMs = plan.reduce((m, s) => Math.max(m, Number(s.cooldownMs || 0)), 0);\n\n const lastTs = this._preWriteLastTsByTrigger.get(triggerKey) || 0;\n if (cooldownMs > 0 && lastTs && now - lastTs < cooldownMs) return;\n\n for (const step of plan) {\n const stepId = String(step.dpId);\n const stepDp = this._getDpById(stepId);\n if (!stepDp) continue;\n if (!(stepDp.rw === 'rw' || stepDp.rw === 'wo')) continue;\n\n // Don't override an already queued user-write for the same datapoint.\n if (this._writeQueue.has(String(stepDp.id))) continue;\n\n this._writeQueue.set(String(stepDp.id), {\n dp: stepDp,\n deviceValue: step.value,\n ackByRelId: new Map(),\n attempts: 0,\n meta: {\n isPreWrite: true,\n preWriteTriggerKey: triggerKey,\n preWriteCooldownMs: cooldownMs,\n },\n });\n }\n }\n\n _enqueueWrite(ackRelId, dp, deviceValue, ackVal, meta = {}) {\n if (!dp || !dp.id) return;\n\n const bypassUnsupportedCooldown = !!(meta && meta.bypassUnsupportedCooldown === true);\n if (!bypassUnsupportedCooldown && this._isWriteTemporarilyUnsupported(dp.id)) {\n this._logSkippedUnsupportedWrite(dp.id);\n return;\n }\n\n const key = String(dp.id);\n const isAutomaticRefresh = !!(meta && (meta.isSetpointKeepalive === true || meta.isPostWriteRepeat === true || meta.isPreWrite === true));\n\n // A new manual command in a mutually exclusive setpoint group invalidates older\n // queued/repeat commands from the other members of the group. This prevents a\n // previous Sungrow charge setpoint from firing a few seconds later and overwriting\n // a fresh discharge command (and vice versa).\n if (!isAutomaticRefresh) {\n try { this._dropQueuedExclusiveSetpointPeers(key); } catch (_) {}\n try { this._cancelExclusiveSetpointPeerPostRepeats(key); } catch (_) {}\n }\n\n // Treat user/script commands as the authoritative desired value immediately, even when\n // the real Modbus write is queued/throttled. Without this, an Alfen watchdog refresh can\n // still repeat the previous 16 A command and overwrite a newly queued Min+PV 6 A command\n // before the queue has flushed it to the charger.\n if (!isAutomaticRefresh) {\n this._rememberCommandedValue(key, deviceValue);\n }\n\n // Ensure required pre-writes are queued first (if any).\n this._enqueuePreWritesForDp(dp.id);\n\n let entry = this._writeQueue.get(key);\n if (!entry) {\n entry = {\n dp,\n deviceValue,\n ackByRelId: new Map(),\n attempts: 0,\n meta: Object.assign({}, meta || {}),\n };\n this._writeQueue.set(key, entry);\n } else {\n const existingMeta = entry.meta || {};\n const existingAutomatic = !!(existingMeta.isSetpointKeepalive || existingMeta.isPostWriteRepeat || existingMeta.isPreWrite);\n const incomingAutomatic = !!isAutomaticRefresh;\n const incomingUserCommand = !!(meta && meta.isUserCommand === true);\n const existingUserCommand = !!(existingMeta && existingMeta.isUserCommand === true);\n\n // Never let an automatic watchdog/pre-write replace a still queued manual alias write.\n // This was visible on Alfen as: user writes phaseMode=3/currentLimit=6, then the next\n // keepalive tick re-queued stale phase=1 or 16 A before the user write had reached Modbus.\n if (incomingAutomatic && (existingUserCommand || !existingAutomatic)) {\n return;\n }\n\n // An in-flight writer owns the previous entry. Replacing it by identity\n // keeps a newer command alive even when the older I/O later succeeds/fails.\n entry = {\n dp,\n deviceValue,\n ackByRelId: new Map(),\n attempts: 0,\n meta: Object.assign({}, meta || {}, {\n isUserCommand: existingUserCommand || incomingUserCommand,\n }),\n };\n this._writeQueue.set(key, entry);\n }\n\n if (ackRelId) {\n entry.ackByRelId.set(String(ackRelId), ackVal);\n }\n\n // If we are NOT using a command-cadence poll loop, start a dedicated write loop.\n if (this._isWriteQueueEnabled() && !this._useCommandCadenceScheduler) {\n this._startWriteLoop();\n }\n }\n\n _pickNextQueuedWrite() {\n if (!this._writeQueue || this._writeQueue.size === 0) return null;\n\n // Priority: pre-writes first\n for (const [k, v] of this._writeQueue.entries()) {\n if (v?.meta?.isPreWrite) return [k, v];\n }\n\n const it = this._writeQueue.entries().next();\n if (it.done) return null;\n return it.value;\n }\n\n async _flushWriteQueueOnce() {\n if (!this._isWriteQueueEnabled() || this._writeBusy) return;\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n if (!this._writeQueue || this._writeQueue.size === 0) return;\n\n this._writeBusy = true;\n let picked = null;\n try {\n picked = this._pickNextQueuedWrite();\n if (!picked) return;\n const [key, entry] = picked;\n if (!entry || !entry.dp) {\n this._writeQueue.delete(key);\n return;\n }\n\n const result = await this.driver.writeDatapoint(entry.dp, entry.deviceValue);\n this._recordWrite(entry.dp.id, { skipPostWriteRepeat: entry.meta?.skipPostWriteRepeat === true });\n const effectiveValue = result && Object.prototype.hasOwnProperty.call(result, 'effectiveValue')\n ? result.effectiveValue : entry.deviceValue;\n this._lastSuccessfulQueuedValueByDpId.set(String(entry.dp.id), effectiveValue);\n const isCurrent = () => this._writeQueue.get(key) === entry;\n if (!isCurrent()) return;\n\n // Persist last setpoint for restore-on-start/reconnect (best-effort)\n await this._persistSetpointValueIfNeeded(entry.dp, effectiveValue).catch(() => {});\n if (!isCurrent()) return;\n\n // Best-effort: keep underlying datapoint + other alias states in sync.\n await this._ackWrittenValue(entry.dp, effectiveValue, isCurrent);\n\n // Ack any states that were written by a user/script (dp state and/or alias state).\n if (entry.ackByRelId && entry.ackByRelId.size) {\n for (const [relId, val] of entry.ackByRelId.entries()) {\n if (!isCurrent()) return;\n // _ackWrittenValue already applies the alias conversion to a clamped\n // effective value. Do not overwrite that with the original request.\n if (effectiveValue === entry.deviceValue) await this._setStateCached(relId, val, true);\n }\n }\n\n // Mark prewrite as done (to avoid repeating it too often).\n if (entry.meta?.isPreWrite && entry.meta.preWriteTriggerKey) {\n this._preWriteLastTsByTrigger.set(String(entry.meta.preWriteTriggerKey), Date.now());\n }\n\n if (isCurrent()) this._writeQueue.delete(key);\n } catch (e) {\n // A failed old transaction must not remove or penalize its replacement.\n if (picked && this._writeQueue.get(picked[0]) !== picked[1]) {\n await this._setError(e);\n return;\n }\n if (this._isSuppressedUnsupportedWriteError(e)) {\n if (picked) {\n const [key, entry] = picked;\n if (entry && entry.dp) this._handleSuppressedUnsupportedWrite(e, entry.dp.id);\n if (this._writeQueue) this._writeQueue.delete(key);\n }\n return;\n }\n if (picked) {\n const [key, entry] = picked;\n if (entry) {\n entry.attempts = (entry.attempts || 0) + 1;\n const msg = (e && e.message) ? String(e.message) : String(e);\n const looksPermanent = /modbus\\s+exception\\s+(2|3)\\b|illegal\\s+data\\s+(address|value)|register\\s+not\\s+supported|cannot\\s+be\\s+written/i.test(msg);\n if (this._isAlfenTemplate() && looksPermanent) {\n this._writeQueue.delete(key);\n if (entry.dp && entry.dp.id) this._handleAlfenRejectedControlWrite(e, entry.dp.id);\n // Automatic validity refreshes remain quiet, but a manual command must leave\n // a visible diagnostic in info.lastError. Previously Alfen FC16 exception 2/3\n // was swallowed here, so ioBroker looked as if the command had been accepted.\n if (entry.meta && entry.meta.isUserCommand === true) {\n await this._setError(e).catch(() => {});\n }\n return;\n }\n const modHints = this.template?.driverHints?.modbus || {};\n const permanentAttemptsRaw = Number(modHints.permanentWriteErrorRetryAttempts ?? 1);\n const permanentAttempts = Number.isFinite(permanentAttemptsRaw) && permanentAttemptsRaw > 0 ? permanentAttemptsRaw : 1;\n const maxAttempts = looksPermanent ? permanentAttempts : 10;\n if (entry.attempts >= maxAttempts) {\n this._writeQueue.delete(key);\n if (looksPermanent) {\n const cooldownMsRaw = Number(modHints.unsupportedWriteCooldownMs ?? 0);\n const cooldownMs = Number.isFinite(cooldownMsRaw) && cooldownMsRaw > 0 ? cooldownMsRaw : 0;\n if (cooldownMs > 0 && entry.dp && entry.dp.id) {\n this._markWriteTemporarilyUnsupported(entry.dp.id, msg);\n }\n }\n }\n }\n }\n await this._setError(e);\n } finally {\n this._writeBusy = false;\n }\n }\n\n _startWriteLoop() {\n if (this._writeTimer || !this._isWriteQueueEnabled() || this._useCommandCadenceScheduler) return;\n const intervalMs = this._writeThrottleMs;\n if (!intervalMs || intervalMs < 250) return;\n\n const self = this;\n const loop = async () => {\n if (!self._isWriteQueueEnabled() || self._useCommandCadenceScheduler) return;\n await self._flushWriteQueueOnce().catch(() => {});\n self._writeTimer = setTimeout(loop, intervalMs);\n };\n this._writeTimer = setTimeout(loop, intervalMs);\n }\n\n _stopWriteLoop() {\n if (this._writeTimer) {\n clearTimeout(this._writeTimer);\n this._writeTimer = null;\n }\n }\n\n async _rejectUnavailableVartaWrite() {\n if (!getVartaProfile(this.template)) return false;\n let availability;\n if (this.driver && typeof this.driver.getWriteAvailability === 'function') {\n // The driver observes the version before the full paced read finishes.\n // Its current availability therefore outranks older object metadata.\n availability = this.driver.getWriteAvailability();\n } else if (Number.isInteger(this._vartaMetadataTableVersion)) {\n availability = { available: this._vartaMetadataTableVersion === 14, tableVersion: this._vartaMetadataTableVersion };\n }\n if (!availability || availability.available !== false) return false;\n\n const version = Number.isInteger(availability.tableVersion) ? availability.tableVersion : null;\n const reasonKey = version === null ? 'unknown' : `table-${version}`;\n const reason = version === null\n ? 'VARTA table version is not confirmed yet; wait for monitoring to confirm table 14 before sending commands.'\n : `VARTA table ${version}: write commands are unavailable; only verified table 14 permits writes.`;\n const message = `E_VARTA_WRITE_UNAVAILABLE: ${reason}`;\n const now = Date.now();\n if (!this._vartaBlockedWriteLogTimes) this._vartaBlockedWriteLogTimes = new Map();\n const lastLog = this._vartaBlockedWriteLogTimes.get(reasonKey);\n if (lastLog === undefined || now - lastLog >= 60000) {\n // Values and alias paths intentionally do not form part of the key, so\n // a controller alternating zero/nonzero commands cannot flood the log.\n if (!this._vartaBlockedWriteLogTimes.has(reasonKey) && this._vartaBlockedWriteLogTimes.size >= 8) {\n this._vartaBlockedWriteLogTimes.delete(this._vartaBlockedWriteLogTimes.keys().next().value);\n }\n this._vartaBlockedWriteLogTimes.set(reasonKey, now);\n this.adapter.log.warn(`[${this.cfg.id}] ${message} Repeated rejections for this reason are logged at most once per 60 seconds.`);\n }\n\n // Report a rejected command without treating it as a communication outage,\n // changing measured values, or acknowledging the requested command as done.\n // Coalesce simultaneous rejected commands into one diagnostic update.\n let diagnostic = this._vartaBlockedWriteDiagnostic;\n if (!diagnostic || diagnostic.reasonKey !== reasonKey) {\n diagnostic = { reasonKey, promise: (async () => {\n await this._setStateCached(`${this.baseId}.info.lastError`, message, true);\n for (const def of this.aliasDefs || []) {\n if (def && /\\.aliases(?:\\.v1)?\\.comm\\.lastError$/.test(def.relId)) {\n await this._setStateCached(def.relId, message, true);\n }\n }\n })() };\n this._vartaBlockedWriteDiagnostic = diagnostic;\n }\n await diagnostic.promise;\n if (this._vartaBlockedWriteDiagnostic === diagnostic) this._vartaBlockedWriteDiagnostic = null;\n return true;\n }\n\n async handleStateChange(fullId, state) {\n if (!state || state.ack) return;\n // Convert full id -> relative id\n const relPrefix = this.adapter.namespace + '.';\n const relId = fullId.startsWith(relPrefix) ? fullId.substring(relPrefix.length) : fullId;\n\n // An external/user write changed the state to ack=false. Drop the cached value so the\n // follow-up ack=true write is not suppressed as \"unchanged\".\n try { this._stateCache.delete(relId); } catch (_) {}\n\n // 1) alias write handling (stable interface)\n const aliasDef = this.aliasByStateRelId.get(relId);\n if (aliasDef) {\n if (!(aliasDef.rw === 'rw' || aliasDef.rw === 'wo')) return;\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n\n // Keep the alias target outside the try block. A later direct datapoint variable named\n // \"dp\" exists in this function; referencing it from the alias catch block hits the JS\n // temporal-dead-zone and crashed the adapter on rejected alias writes.\n let aliasTargetDp = null;\n try {\n if (getVartaProfile(this.template) && await this._rejectUnavailableVartaWrite()) return;\n const targetId = aliasDef.writeDpId || aliasDef.dpId;\n aliasTargetDp = this._getDpById(targetId);\n if (!aliasTargetDp) throw new Error(`Alias target datapoint not found: ${targetId}`);\n\n // Direct user/script writes must not be suppressed by a previous automatic\n // keepalive rejection. Especially with Alfen ACE this caused writable aliases\n // to appear dead for the cooldown window.\n const toDev = (typeof aliasDef.toDevice === 'function') ? aliasDef.toDevice(state.val) : state.val;\n if (toDev === undefined || toDev === null) {\n // Command-button aliases can intentionally ignore the inactive/false edge\n // (e.g. KEBA P40 fast charging can only be activated, not deactivated, via Modbus).\n await this._setStateCached(relId, state.val, true);\n return;\n }\n\n let mirrorSignedDp = null;\n let mirrorSignedVal;\n if (aliasDef.mirrorSignedDpId) {\n mirrorSignedDp = this._getDpById(aliasDef.mirrorSignedDpId);\n if (mirrorSignedDp) {\n mirrorSignedVal = (typeof aliasDef.toMirrorDevice === 'function') ? aliasDef.toMirrorDevice(state.val) : toDev;\n this._rememberCommandedValue(mirrorSignedDp.id, mirrorSignedVal);\n }\n }\n\n // Alfen ACE: remember the command before it is sent so the 5s watchdog cannot\n // overwrite a freshly typed alias value with an older restored value while the\n // Modbus write is still pending. This is especially important for phaseMode,\n // where stale info.setpoints.cHARGE_USING_PHASES=1 previously forced 1-phase\n // operation again after a manual 3-phase command.\n if (this._isAlfenTemplate() && aliasTargetDp && (String(aliasTargetDp.id) === 'sET_CHARGING_CURRENT' || String(aliasTargetDp.id) === 'cHARGE_USING_PHASES')) {\n try {\n this._lastCommandedValueByDpId.set(String(aliasTargetDp.id), toDev);\n this._clearWriteTemporarilyUnsupported(aliasTargetDp.id);\n } catch (_) {}\n }\n\n // For sensitive devices (e.g. SolaX), coalesce/throttle writes instead of sending them immediately.\n // VARTA and FENECON Home have no keepalive requiring an optimistic\n // command. Rejected writes must not later be acknowledged from polling.\n if (!getVartaProfile(this.template) && !this._isFeneconHomeEssTemplate()) this._rememberCommandedValue(aliasTargetDp.id, toDev);\n\n if (this._isWriteQueueEnabled()) {\n this._enqueueWrite(relId, aliasTargetDp, toDev, state.val, { bypassUnsupportedCooldown: true, isUserCommand: true });\n return;\n }\n\n // Optional pre-writes (template hinted), e.g. writing a control mode before an active power setpoint.\n await this._maybeExecutePreWritesForDp(aliasTargetDp.id);\n const writeResult = await this.driver.writeDatapoint(aliasTargetDp, toDev);\n const effectiveToDev = writeResult && writeResult.effectiveValue !== undefined\n ? writeResult.effectiveValue\n : toDev;\n this._rememberCommandedValue(aliasTargetDp.id, effectiveToDev);\n\n // Track that this datapoint was actively written (used for watchdog fail-safe).\n this._recordWrite(aliasTargetDp.id);\n\n // Persist last setpoint for restore-on-start/reconnect (best-effort)\n await this._persistSetpointValueIfNeeded(aliasTargetDp, effectiveToDev).catch(() => {});\n\n // Most drivers apply the requested value unchanged. A driver may return an\n // effective/clamped engineering value (TESVOLT dynamic power limits). In that\n // case acknowledge the actual command while preserving alias direction semantics.\n let aliasAckValue = state.val;\n if (writeResult && writeResult.effectiveValue !== undefined && !Object.is(effectiveToDev, toDev)) {\n if (typeof aliasDef.fromDevice === 'function') aliasAckValue = aliasDef.fromDevice(effectiveToDev);\n else if (typeof aliasDef.toDevice !== 'function') aliasAckValue = effectiveToDev;\n }\n await this._setStateCached(relId, aliasAckValue, true);\n\n // best-effort: keep underlying datapoint + other alias states in sync with the written raw value\n await this._ackWrittenValue(aliasTargetDp, effectiveToDev);\n if (mirrorSignedDp) {\n await this._ackWrittenValue(mirrorSignedDp, mirrorSignedVal);\n }\n\n return;\n } catch (e) {\n // A fresh identity check may discover a read-only table after admission.\n // Keep that rejection a control diagnostic, never a liveness failure.\n if (getVartaProfile(this.template) && await this._rejectUnavailableVartaWrite()) return;\n if (this._isSuppressedUnsupportedWriteError(e)) {\n this._handleSuppressedUnsupportedWrite(e, aliasTargetDp && aliasTargetDp.id ? aliasTargetDp.id : undefined);\n return;\n }\n const msg = (e && e.message) ? String(e.message) : String(e);\n if (this._isAlfenTemplate() && this._looksLikePermanentModbusWriteReject(msg)) {\n this._handleAlfenRejectedControlWrite(e, aliasTargetDp && aliasTargetDp.id ? aliasTargetDp.id : undefined);\n // Surface explicit user-command failures. Keepalive/post-repeat failures are\n // handled separately and remain throttled to avoid log flooding.\n await this._setError(e).catch(() => {});\n return;\n }\n if (this._looksLikePermanentModbusWriteReject(msg)) {\n this._markWriteTemporarilyUnsupported(aliasTargetDp && aliasTargetDp.id ? aliasTargetDp.id : undefined, msg);\n }\n await this._setError(e).catch(() => {});\n return;\n }\n }\n\n // 2) regular datapoint write handling\n const dp = this.dpByStateRelId.get(relId);\n if (!dp) return;\n if (!(dp.rw === 'rw' || dp.rw === 'wo')) return;\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n\n try {\n if (getVartaProfile(this.template) && await this._rejectUnavailableVartaWrite()) return;\n // Direct user/script writes must not be suppressed by a previous automatic\n // keepalive rejection. Let the actual device response decide.\n if (!getVartaProfile(this.template) && !this._isFeneconHomeEssTemplate()) this._rememberCommandedValue(dp.id, state.val);\n\n // For sensitive devices (e.g. SolaX), coalesce/throttle writes instead of sending them immediately.\n if (this._isWriteQueueEnabled()) {\n this._enqueueWrite(relId, dp, state.val, state.val, { bypassUnsupportedCooldown: true, isUserCommand: true });\n return;\n }\n\n // Optional pre-writes (template hinted), e.g. writing a control mode before an active power setpoint.\n await this._maybeExecutePreWritesForDp(dp.id);\n const writeResult = await this.driver.writeDatapoint(dp, state.val);\n const effectiveValue = writeResult && writeResult.effectiveValue !== undefined\n ? writeResult.effectiveValue\n : state.val;\n this._rememberCommandedValue(dp.id, effectiveValue);\n\n // Track that this datapoint was actively written (used for watchdog fail-safe).\n this._recordWrite(dp.id);\n\n // Persist last setpoint for restore-on-start/reconnect (best-effort)\n await this._persistSetpointValueIfNeeded(dp, effectiveValue).catch(() => {});\n\n // ack the written value\n await this._setStateCached(relId, effectiveValue, true);\n } catch (e) {\n if (getVartaProfile(this.template) && await this._rejectUnavailableVartaWrite()) return;\n if (this._isSuppressedUnsupportedWriteError(e)) {\n this._handleSuppressedUnsupportedWrite(e, dp && dp.id ? dp.id : undefined);\n return;\n }\n const msg = (e && e.message) ? String(e.message) : String(e);\n if (this._isAlfenTemplate() && this._looksLikePermanentModbusWriteReject(msg)) {\n this._handleAlfenRejectedControlWrite(e, dp && dp.id ? dp.id : undefined);\n await this._setError(e).catch(() => {});\n return;\n }\n if (this._looksLikePermanentModbusWriteReject(msg)) this._markWriteTemporarilyUnsupported(dp && dp.id ? dp.id : undefined, msg);\n await this._setError(e).catch(() => {});\n }\n }\n\n\n _getAutoWatchdogConfig() {\n const hints = this.template?.driverHints?.modbus;\n const cfg = hints?.autoWatchdog || hints?.autoWatchdogs || hints?.watchdog;\n if (!cfg) return null;\n\n if (cfg === true) {\n // Boolean true is ambiguous without dpIds; require explicit list\n return null;\n }\n\n const enabled = (cfg.enabled !== false);\n if (!enabled) return null;\n\n const periodMs = Number(cfg.periodMs ?? cfg.intervalMs ?? 60000);\n const startDelayMs = Number(cfg.startDelayMs ?? 1000);\n const sequenceMin = Number(cfg.sequenceMin ?? 1);\n const sequenceMax = Number(cfg.sequenceMax ?? 1000);\n\n const activeForMsRaw = Number(cfg.activeForMs ?? cfg.activeWindowMs ?? cfg.activeAfterWriteMs ?? 0);\n const activeForMs = (Number.isFinite(activeForMsRaw) && activeForMsRaw > 0) ? activeForMsRaw : null;\n\n const globalActivation = Array.isArray(cfg.activateOnWriteDpIds || cfg.activationDpIds)\n ? (cfg.activateOnWriteDpIds || cfg.activationDpIds)\n : [];\n const globalActivationDpIds = globalActivation.map(v => String(v)).filter(v => v && v.trim());\n\n // Targets can be defined as:\n // - cfg.targets: [ { dpId, activateOnWriteDpIds }, ... ]\n // - cfg.dpIds: [ 'DP1', 'DP2', ... ] (legacy)\n // - cfg as array: [ 'DP1', ... ] (legacy)\n const rawTargets = Array.isArray(cfg.targets)\n ? cfg.targets\n : Array.isArray(cfg.dpIds)\n ? cfg.dpIds\n : Array.isArray(cfg)\n ? cfg\n : [];\n\n const targets = [];\n for (const t of rawTargets) {\n if (!t) continue;\n if (typeof t === 'string' || typeof t === 'number') {\n const dpId = String(t);\n if (!dpId.trim()) continue;\n targets.push({ dpId, activationDpIds: globalActivationDpIds });\n continue;\n }\n if (typeof t === 'object') {\n const dpId = String(t.dpId ?? t.watchdogDpId ?? t.id ?? '');\n if (!dpId.trim()) continue;\n const act = Array.isArray(t.activateOnWriteDpIds || t.activationDpIds || t.activeOnWriteDpIds)\n ? (t.activateOnWriteDpIds || t.activationDpIds || t.activeOnWriteDpIds)\n : globalActivationDpIds;\n const activationDpIds = (act || []).map(v => String(v)).filter(v => v && v.trim());\n targets.push({ dpId, activationDpIds });\n }\n }\n if (!targets.length) return null;\n\n // Optional: Disable a control register when setpoints are no longer refreshed (fail-safe).\n let disable = null;\n const disableWhenInactive = cfg.disableWhenInactive === true;\n if (disableWhenInactive) {\n const disableDpId = String(cfg.disableDpId ?? '').trim();\n const disableValue = (cfg.disableValue !== undefined) ? cfg.disableValue : 0;\n const disableAfterMsRaw = Number(cfg.disableAfterMs ?? activeForMsRaw ?? 0);\n const disableAfterMs = (Number.isFinite(disableAfterMsRaw) && disableAfterMsRaw > 0) ? disableAfterMsRaw : null;\n const disableActRaw = Array.isArray(cfg.disableActivationDpIds)\n ? cfg.disableActivationDpIds\n : [];\n const disableActivationDpIds = disableActRaw.map(v => String(v)).filter(v => v && v.trim());\n if (disableDpId && disableAfterMs && disableActivationDpIds.length) {\n disable = {\n dpId: disableDpId,\n value: disableValue,\n afterMs: disableAfterMs,\n activationDpIds: disableActivationDpIds,\n };\n }\n }\n\n return {\n periodMs: Number.isFinite(periodMs) ? periodMs : 60000,\n startDelayMs: Number.isFinite(startDelayMs) ? startDelayMs : 1000,\n sequenceMin: Number.isFinite(sequenceMin) ? sequenceMin : 1,\n sequenceMax: Number.isFinite(sequenceMax) ? sequenceMax : 1000,\n activeForMs,\n targets,\n disable,\n };\n }\n\n async _startAutoWatchdogs() {\n // Only applies to Modbus devices\n const proto = this.cfg?.protocol;\n if (proto !== 'modbusTcp' && proto !== 'modbusRtu') return;\n\n const cfg = this._getAutoWatchdogConfig();\n if (!cfg) return;\n\n if (this.watchdogTimer || this.watchdogStartTimer) return;\n\n // Resolve writable watchdog datapoints\n const targets = [];\n for (const t of cfg.targets) {\n const dpId = t?.dpId;\n if (!dpId) continue;\n const dp = this._getDpById(dpId);\n if (!dp) {\n this.adapter.log.debug(`[${this.cfg.id}] AutoWatchdog: datapoint not found: ${dpId}`);\n continue;\n }\n if (!(dp.rw === 'rw' || dp.rw === 'wo')) {\n this.adapter.log.debug(`[${this.cfg.id}] AutoWatchdog: datapoint not writable: ${dpId}`);\n continue;\n }\n targets.push({ dp, activationDpIds: Array.isArray(t.activationDpIds) ? t.activationDpIds : [] });\n }\n\n if (!targets.length) return;\n\n // Optional fail-safe: disable a control register when setpoints are no longer refreshed.\n let disable = null;\n if (cfg.disable && cfg.disable.dpId) {\n const dp = this._getDpById(cfg.disable.dpId);\n if (dp && (dp.rw === 'rw' || dp.rw === 'wo')) {\n disable = {\n dp,\n value: cfg.disable.value,\n afterMs: cfg.disable.afterMs,\n activationDpIds: Array.isArray(cfg.disable.activationDpIds) ? cfg.disable.activationDpIds : [],\n };\n }\n }\n\n const periodMs = Math.max(10000, Number(cfg.periodMs || 60000));\n const startDelayMs = Math.max(0, Number(cfg.startDelayMs || 1000));\n\n const minVal = Math.trunc(Number(cfg.sequenceMin || 1));\n const maxValRaw = Math.trunc(Number(cfg.sequenceMax || 1000));\n const maxVal = Number.isFinite(maxValRaw) && maxValRaw >= minVal ? maxValRaw : 1000;\n\n // Initialize counter so the first tick yields minVal\n if (!Number.isFinite(this._watchdogCounter) || this._watchdogCounter < minVal || this._watchdogCounter > maxVal) {\n this._watchdogCounter = minVal - 1;\n }\n\n const tick = async () => {\n if (this._watchdogBusy) return;\n this._watchdogBusy = true;\n try {\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n if (!this._connOk) return; // only when connected\n\n // Avoid colliding with ongoing read polls\n if (this.driver && this.driver._busy) return;\n\n const now = Date.now();\n\n // Fail-safe: disable VK control if no recent setpoint updates (and if it was ever used).\n if (disable && disable.afterMs && disable.activationDpIds.length) {\n const hasEver = disable.activationDpIds.some(id => this._lastWriteByDpId.has(String(id)));\n const recent = disable.activationDpIds.some(id => {\n const ts = this._lastWriteByDpId.get(String(id));\n return ts && (now - ts) <= disable.afterMs;\n });\n\n if (hasEver && recent) {\n this._autoWatchdogControlEverActive = true;\n this._autoWatchdogControlDisabled = false;\n }\n\n if (hasEver && this._autoWatchdogControlEverActive && !recent && !this._autoWatchdogControlDisabled) {\n try {\n await this.driver.writeDatapoint(disable.dp, disable.value);\n this._recordWrite(disable.dp.id);\n await this._ackWrittenValue(disable.dp, disable.value);\n this._autoWatchdogControlDisabled = true;\n this.adapter.log.info(`[${this.cfg.id}] AutoWatchdog fail-safe: wrote ${disable.dp.id}=${disable.value}`);\n } catch (e) {\n this.adapter.log.debug(`[${this.cfg.id}] AutoWatchdog fail-safe write error: ${e && e.message ? e.message : e}`);\n }\n }\n }\n\n // Determine which watchdogs are active.\n const activeTargets = [];\n for (const t of targets) {\n const activationDpIds = t.activationDpIds || [];\n if (!cfg.activeForMs || !activationDpIds.length) {\n activeTargets.push(t);\n continue;\n }\n let isActive = false;\n for (const id of activationDpIds) {\n const ts = this._lastWriteByDpId.get(String(id));\n if (ts && (now - ts) <= cfg.activeForMs) {\n isActive = true;\n break;\n }\n }\n if (isActive) activeTargets.push(t);\n }\n\n if (!activeTargets.length) return;\n\n // Ramp min..max (loop)\n let next = this._watchdogCounter + 1;\n if (next > maxVal) next = minVal;\n this._watchdogCounter = next;\n\n for (const t of activeTargets) {\n await this.driver.writeDatapoint(t.dp, next);\n this._recordWrite(t.dp.id);\n await this._ackWrittenValue(t.dp, next);\n }\n this.adapter.log.debug(`[${this.cfg.id}] AutoWatchdog tick -> ${next} (targets=${activeTargets.map(x => x.dp.id).join(',')})`);\n } catch (e) {\n // Best-effort: do not spam warnings; poll loop will surface transport errors.\n this.adapter.log.debug(`[${this.cfg.id}] AutoWatchdog error: ${e && e.message ? e.message : e}`);\n } finally {\n this._watchdogBusy = false;\n }\n };\n\n // Fire once shortly after start, then periodically\n this.watchdogStartTimer = setTimeout(() => { tick(); }, startDelayMs);\n this.watchdogTimer = setInterval(() => { tick(); }, periodMs);\n\n this.adapter.log.info(`[${this.cfg.id}] AutoWatchdog enabled: dpIds=[${targets.map(t => t.dp.id).join(', ')}], periodMs=${periodMs}, activeForMs=${cfg.activeForMs || 0}`);\n }\n\n\n _getRestoreSetpointsConfig() {\n const proto = this.cfg?.protocol;\n if (proto !== 'modbusTcp' && proto !== 'modbusRtu' && proto !== 'modbusAscii') return null;\n\n const hints = this.template?.driverHints?.modbus;\n if (!hints) return null;\n\n let cfg = hints.restoreSetpointsOnStart || hints.restoreSetpoints || hints.restoreOnStart || null;\n if (!cfg) return null;\n\n // Allow boolean shorthand: true => enabled with defaults\n if (cfg === true) cfg = {};\n\n if (!cfg || typeof cfg !== 'object') return null;\n if (cfg.enabled === false) return null;\n\n const dpIdsRaw = Array.isArray(cfg.dpIds)\n ? cfg.dpIds\n : Array.isArray(cfg.targets)\n ? cfg.targets\n : [];\n\n const dpIds = (dpIdsRaw || []).map(v => String(v)).filter(v => v && v.trim());\n if (!dpIds.length) return null;\n\n const delayMsRaw = Number(cfg.delayMs ?? cfg.startDelayMs ?? 1500);\n const delayMs = Number.isFinite(delayMsRaw) ? Math.max(0, delayMsRaw) : 1500;\n\n const storeOnWrite = (cfg.storeOnWrite !== false);\n const useFallbackFromDpState = (cfg.useFallbackFromDpState !== false);\n\n const maxRetriesRaw = Number(cfg.maxRetries ?? 6);\n const maxRetries = Number.isFinite(maxRetriesRaw) ? Math.max(0, Math.trunc(maxRetriesRaw)) : 6;\n\n const retryMsRaw = Number(cfg.retryMs ?? cfg.retryIntervalMs ?? 5000);\n const retryMs = Number.isFinite(retryMsRaw) ? Math.max(1000, retryMsRaw) : 5000;\n\n const logLevel = String(cfg.logLevel ?? cfg.restoreLogLevel ?? 'info').toLowerCase();\n\n return {\n dpIds,\n delayMs,\n storeOnWrite,\n useFallbackFromDpState,\n maxRetries,\n retryMs,\n logLevel,\n exclusiveGroups: this._normalizeExclusiveSetpointGroups(cfg.exclusiveGroups || cfg.exclusiveSetpointGroups || []),\n };\n }\n\n _setpointMemoryRelId(dpId) {\n return `${this.baseId}.info.setpoints.${String(dpId)}`;\n }\n\n async _ensureSetpointMemoryObjects(dp) {\n if (!dp || !dp.id) return;\n\n // Ensure channel exists once\n if (!this._setpointsInfoReady) {\n await this.adapter.setObjectNotExistsAsync(`${this.baseId}.info.setpoints`, {\n type: 'channel',\n common: { name: 'Setpoints' },\n native: {},\n }).catch(() => {});\n this._setpointsInfoReady = true;\n }\n\n const id = this._setpointMemoryRelId(dp.id);\n\n // Determine ioBroker type (fallback to number for setpoints)\n const t = (dp.type === 'boolean') ? 'boolean' : (dp.type === 'string') ? 'string' : 'number';\n\n await this.adapter.setObjectNotExistsAsync(id, {\n type: 'state',\n common: {\n name: dp.name ? `Last setpoint: ${dp.name}` : `Last setpoint: ${dp.id}`,\n type: t,\n role: 'state',\n read: true,\n write: false,\n unit: dp.unit || undefined,\n },\n native: {\n dpId: dp.id,\n },\n }).catch(() => {});\n }\n\n async _persistSetpointValueIfNeeded(dp, deviceValue) {\n const cfg = this._restoreCfg;\n if (!cfg || cfg.storeOnWrite === false) return;\n if (!dp || !dp.id) return;\n if (!this._restoreDpIds || !this._restoreDpIds.has(String(dp.id))) return;\n\n if (deviceValue === null || deviceValue === undefined) return;\n\n // Normalize values to keep ioBroker state type stable\n let out = deviceValue;\n if (dp.type === 'boolean') {\n out = !!deviceValue;\n } else if (dp.type === 'string') {\n out = String(deviceValue);\n } else {\n const n = Number(deviceValue);\n if (!Number.isFinite(n)) return;\n out = n;\n }\n\n await this._ensureSetpointMemoryObjects(dp);\n await this._setStateCached(this._setpointMemoryRelId(dp.id), out, true);\n }\n\n _scheduleRestoreSetpoints(reason = '') {\n const cfg = this._restoreCfg;\n if (!cfg || !Array.isArray(cfg.dpIds) || !cfg.dpIds.length) return;\n\n // Avoid stacking timers\n if (this._restoreTimer) return;\n\n const delayMs = Math.max(0, Number(cfg.delayMs || 0));\n const maxRetries = Math.max(0, Number(cfg.maxRetries || 0));\n const retryMs = Math.max(1000, Number(cfg.retryMs || 5000));\n\n let attempts = 0;\n\n const run = async () => {\n // Don't collide with ongoing restore attempt\n if (this._restoreBusy) return;\n\n // Wait until we are connected\n if (!this._connOk) {\n attempts++;\n if (attempts <= maxRetries) {\n this._restoreTimer = setTimeout(() => {\n this._restoreTimer = null;\n run().catch(() => {});\n }, retryMs);\n }\n return;\n }\n\n await this._restoreSetpointsOnce(reason).catch(() => {});\n };\n\n this._restoreTimer = setTimeout(() => {\n this._restoreTimer = null;\n run().catch(() => {});\n }, delayMs);\n }\n\n _normalizeExclusiveSetpointGroups(rawGroups) {\n if (!Array.isArray(rawGroups)) return [];\n const groups = [];\n for (const group of rawGroups) {\n const arr = Array.isArray(group)\n ? group\n : (group && typeof group === 'object' && Array.isArray(group.dpIds))\n ? group.dpIds\n : (group && typeof group === 'object' && Array.isArray(group.targets))\n ? group.targets\n : [];\n const ids = arr.map(v => String(v || '').trim()).filter(Boolean);\n const uniq = [];\n for (const id of ids) if (!uniq.includes(id)) uniq.push(id);\n if (uniq.length > 1) groups.push(uniq);\n }\n return groups;\n }\n\n _applyExclusiveSetpointGroupsToCandidates(candidates, groups) {\n if (!Array.isArray(candidates) || !candidates.length || !Array.isArray(groups) || !groups.length) return candidates;\n\n const byId = new Map();\n for (const c of candidates) {\n if (!c || !c.dp || !c.dp.id) continue;\n byId.set(String(c.dp.id), c);\n }\n\n const drop = new Set();\n for (const group of groups) {\n const present = group.map(id => byId.get(String(id))).filter(Boolean);\n if (present.length <= 1) continue;\n\n // Restore/refresh only the newest setpoint in a mutually exclusive control group.\n // This is important for chargers like MENNEKES where current-limit, power-limit,\n // legacy and network-limit registers are alternative control paths. Restoring all\n // old states after reconnect can overwrite the intended active mode.\n let keep = present[0];\n for (const c of present.slice(1)) {\n const ts = Number(c.ts || 0);\n const keepTs = Number(keep.ts || 0);\n if (ts > keepTs) keep = c;\n }\n for (const c of present) {\n if (c !== keep) drop.add(String(c.dp.id));\n }\n }\n\n if (!drop.size) return candidates;\n return candidates.filter(c => c && c.dp && !drop.has(String(c.dp.id)));\n }\n\n _applyExclusiveSetpointGroupsToKeepaliveTargets(targets, groups) {\n if (!Array.isArray(targets) || !targets.length || !Array.isArray(groups) || !groups.length) return targets;\n\n const byId = new Map();\n for (const t of targets) {\n if (!t || !t.setpointDpId) continue;\n byId.set(String(t.setpointDpId), t);\n }\n\n const drop = new Set();\n for (const group of groups) {\n const present = group.map(id => byId.get(String(id))).filter(Boolean);\n if (present.length <= 1) continue;\n\n let keep = null;\n let keepTs = -1;\n for (const t of present) {\n const ts = Number(this._lastWriteByDpId.get(String(t.setpointDpId)) || 0);\n // Only a datapoint that was actually written can become the active refresh target.\n if (ts > keepTs) {\n keepTs = ts;\n keep = t;\n }\n }\n\n // If nothing in this group was ever written, keep the group untouched. The existing\n // requireEverWritten check will skip all targets without making this look unsupported.\n if (!keep || keepTs <= 0) continue;\n\n for (const t of present) {\n if (t !== keep) drop.add(String(t.setpointDpId));\n }\n }\n\n if (!drop.size) return targets;\n return targets.filter(t => t && !drop.has(String(t.setpointDpId)));\n }\n\n\n _getRuntimeExclusiveSetpointGroups() {\n const hints = this.template?.driverHints?.modbus || {};\n const raw = hints.exclusiveSetpointGroups ||\n hints.mutuallyExclusiveSetpointGroups ||\n hints.exclusiveControlGroups ||\n (hints.restoreSetpointsOnStart && (hints.restoreSetpointsOnStart.exclusiveGroups || hints.restoreSetpointsOnStart.exclusiveSetpointGroups)) ||\n (hints.restoreSetpoints && (hints.restoreSetpoints.exclusiveGroups || hints.restoreSetpoints.exclusiveSetpointGroups)) ||\n [];\n return this._normalizeExclusiveSetpointGroups(raw);\n }\n\n _getExclusiveSetpointPeers(dpId) {\n const key = String(dpId || '');\n if (!key) return [];\n const groups = this._getRuntimeExclusiveSetpointGroups();\n const peers = [];\n for (const group of groups) {\n if (!Array.isArray(group) || !group.includes(key)) continue;\n for (const id of group) {\n const s = String(id || '');\n if (s && s !== key && !peers.includes(s)) peers.push(s);\n }\n }\n return peers;\n }\n\n _cancelExclusiveSetpointPeerPostRepeats(dpId) {\n const peers = this._getExclusiveSetpointPeers(dpId);\n if (!peers.length || !this._postWriteRepeatTimersByDpId) return;\n for (const peer of peers) {\n try {\n const timer = this._postWriteRepeatTimersByDpId.get(peer);\n if (timer) clearTimeout(timer);\n this._postWriteRepeatTimersByDpId.delete(peer);\n } catch (_) {}\n }\n }\n\n _dropQueuedExclusiveSetpointPeers(dpId) {\n const peers = this._getExclusiveSetpointPeers(dpId);\n if (!peers.length || !this._writeQueue) return;\n for (const peer of peers) {\n try { this._writeQueue.delete(peer); } catch (_) {}\n }\n }\n\n async _restoreSetpointsOnce(reason = '') {\n const cfg = this._restoreCfg;\n if (!cfg || !Array.isArray(cfg.dpIds) || !cfg.dpIds.length) return;\n if (this._restoreBusy) return;\n\n this._restoreBusy = true;\n try {\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n if (!this._connOk) return;\n if (this.driver && this.driver._busy) return; // avoid colliding with ongoing read polls\n\n let candidates = [];\n\n for (const rawId of cfg.dpIds) {\n const dpId = String(rawId || '');\n if (!dpId) continue;\n\n const dp = this._getDpById(dpId);\n if (!dp) continue;\n if (!(dp.rw === 'rw' || dp.rw === 'wo')) continue;\n\n // Prefer persisted memory (info.setpoints.*). Fallback to pre-poll captured dp state if configured.\n let val = undefined;\n let ts = 0;\n\n const mem = await this.adapter.getStateAsync(this._setpointMemoryRelId(dp.id)).catch(() => null);\n if (mem && mem.val !== null && mem.val !== undefined) {\n val = mem.val;\n ts = Number(mem.ts || mem.lc || 0) || 0;\n }\n\n if ((val === undefined) && cfg.useFallbackFromDpState !== false) {\n if (this._restoreFallback && this._restoreFallback.has(String(dp.id))) {\n val = this._restoreFallback.get(String(dp.id));\n const st = await this.adapter.getStateAsync(this.relStateId(dp)).catch(() => null);\n ts = Number(st && (st.ts || st.lc) || 0) || 0;\n }\n }\n\n if (val === null || val === undefined) continue;\n\n // Normalize\n if (dp.type === 'boolean') {\n val = !!val;\n } else if (dp.type === 'string') {\n val = String(val);\n } else {\n const n = Number(val);\n if (!Number.isFinite(n)) continue;\n val = n;\n }\n\n candidates.push({ dp, val, ts });\n }\n\n candidates = this._applyExclusiveSetpointGroupsToCandidates(candidates, cfg.exclusiveGroups || []);\n\n const actions = [];\n const queueing = this._isWriteQueueEnabled();\n for (const c of candidates) {\n const { dp, val } = c;\n // Write (best-effort)\n if (queueing) {\n this._enqueueWrite(null, dp, val, val);\n } else {\n await this.driver.writeDatapoint(dp, val);\n this._recordWrite(dp.id);\n await this._ackWrittenValue(dp, val);\n }\n\n await this._persistSetpointValueIfNeeded(dp, val).catch(() => {});\n actions.push(`${dp.id}=${val}`);\n }\n\n if (actions.length) {\n const prefix = queueing ? 'Queued setpoint restore' : 'Restored setpoints';\n const msg = `[${this.cfg.id}] ${prefix}${reason ? ` (${reason})` : ''}: ${actions.join(', ')}`;\n const lvl = String(cfg.logLevel || 'info').toLowerCase();\n if (lvl === 'silent' || lvl === 'none' || lvl === 'off') {\n // intentionally quiet\n } else if (lvl === 'debug') {\n this.adapter.log.debug(msg);\n } else if (lvl === 'warn' || lvl === 'warning') {\n this.adapter.log.warn(msg);\n } else {\n this.adapter.log.info(msg);\n }\n } else {\n this.adapter.log.debug(`[${this.cfg.id}] No setpoints to restore${reason ? ` (${reason})` : ''}.`);\n }\n } catch (e) {\n this.adapter.log.debug(`[${this.cfg.id}] Restore setpoints error: ${e && e.message ? e.message : e}`);\n } finally {\n this._restoreBusy = false;\n }\n }\n\n _getPostWriteRepeatConfig() {\n const proto = this.cfg?.protocol;\n if (proto !== 'modbusTcp' && proto !== 'modbusRtu' && proto !== 'modbusAscii') return null;\n\n const hints = this.template?.driverHints?.modbus;\n if (!hints) return null;\n\n let cfg = hints.postWriteRepeat || hints.repeatAfterWrite || hints.confirmWriteAfterIdle || null;\n if (!cfg) return null;\n if (cfg === true) cfg = {};\n if (!cfg || typeof cfg !== 'object') return null;\n if (cfg.enabled === false) return null;\n\n const rawTargets = Array.isArray(cfg.targets)\n ? cfg.targets\n : Array.isArray(cfg.dpIds)\n ? cfg.dpIds\n : (cfg.dpId || cfg.setpointDpId)\n ? [cfg]\n : [];\n\n const targets = [];\n for (const raw of rawTargets) {\n const t = (raw && typeof raw === 'object') ? raw : { dpId: raw };\n const dpId = String(t.dpId || t.setpointDpId || '').trim();\n if (!dpId) continue;\n const delayRaw = Number(t.delayMs ?? t.repeatAfterMs ?? t.idleMs ?? cfg.delayMs ?? cfg.repeatAfterMs ?? cfg.idleMs ?? 5000);\n const delayMs = Number.isFinite(delayRaw) && delayRaw > 0 ? Math.max(1000, delayRaw) : 5000;\n targets.push({\n dpId,\n delayMs,\n useLastCommandValue: (t.useLastCommandValue !== false && cfg.useLastCommandValue !== false),\n logLevel: String(t.logLevel ?? cfg.logLevel ?? 'debug').toLowerCase(),\n });\n }\n\n if (!targets.length) return null;\n return { targets };\n }\n\n _getPostWriteRepeatTarget(dpId) {\n const cfg = this._getPostWriteRepeatConfig();\n if (!cfg || !Array.isArray(cfg.targets)) return null;\n const key = String(dpId || '');\n return cfg.targets.find(t => String(t.dpId) === key) || null;\n }\n\n _schedulePostWriteRepeat(dpId) {\n const target = this._getPostWriteRepeatTarget(dpId);\n if (!target) return;\n\n const key = String(dpId);\n if (!key) return;\n\n if (this._postWriteRepeatTimersByDpId && this._postWriteRepeatTimersByDpId.has(key)) {\n try { clearTimeout(this._postWriteRepeatTimersByDpId.get(key)); } catch (_) {}\n this._postWriteRepeatTimersByDpId.delete(key);\n }\n\n const baseTs = Number(this._lastWriteByDpId.get(key) || Date.now());\n const delayMs = Math.max(1000, Number(target.delayMs || 5000));\n\n const timer = setTimeout(async () => {\n try {\n if (this._postWriteRepeatTimersByDpId) this._postWriteRepeatTimersByDpId.delete(key);\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n if (!this._connOk) return;\n if (this._isWriteTemporarilyUnsupported(key)) return;\n\n // Only repeat if no newer write for this datapoint has happened since the timer was armed.\n const latestTs = Number(this._lastWriteByDpId.get(key) || 0);\n if (latestTs && latestTs !== baseTs) return;\n\n const dp = this._getDpById(key);\n if (!dp || !(dp.rw === 'rw' || dp.rw === 'wo')) return;\n\n let val;\n if (target.useLastCommandValue !== false && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(key)) {\n val = this._lastCommandedValueByDpId.get(key);\n } else {\n const st = await this.adapter.getStateAsync(this.relStateId(dp)).catch(() => null);\n if (!st || st.val === undefined || st.val === null) return;\n val = st.val;\n }\n\n if (val === undefined || val === null) return;\n if (dp.type !== 'boolean' && dp.type !== 'string') {\n const n = Number(val);\n if (!Number.isFinite(n)) return;\n val = n;\n } else if (dp.type === 'boolean') {\n val = !!val;\n }\n\n if (this._isWriteQueueEnabled()) {\n this._enqueueWrite(null, dp, val, val, { skipPostWriteRepeat: true, isPostWriteRepeat: true });\n } else {\n await this.driver.writeDatapoint(dp, val);\n this._recordWrite(dp.id, { skipPostWriteRepeat: true });\n await this._ackWrittenValue(dp, val);\n }\n\n const msg = `[${this.cfg.id}] PostWriteRepeat: repeated ${key}=${val} after ${delayMs} ms idle`;\n const lvl = String(target.logLevel || 'debug').toLowerCase();\n if (lvl === 'info') this.adapter.log.info(msg);\n else if (lvl === 'warn' || lvl === 'warning') this.adapter.log.warn(msg);\n else if (lvl !== 'silent' && lvl !== 'none' && lvl !== 'off') this.adapter.log.debug(msg);\n } catch (e) {\n const msg = e && e.message ? e.message : String(e);\n if (this._isSuppressedUnsupportedWriteError(e)) {\n this._handleSuppressedUnsupportedWrite(e, key);\n return;\n }\n if (this._isAlfenTemplate() && this._looksLikePermanentModbusWriteReject(msg)) {\n this._handleAlfenRejectedControlWrite(e, key);\n return;\n }\n this.adapter.log.debug(`[${this.cfg.id}] PostWriteRepeat error for ${key}: ${msg}`);\n }\n }, delayMs);\n\n if (this._postWriteRepeatTimersByDpId) this._postWriteRepeatTimersByDpId.set(key, timer);\n }\n\n _getSetpointKeepaliveConfig() {\n const proto = this.cfg?.protocol;\n if (proto !== 'modbusTcp' && proto !== 'modbusRtu' && proto !== 'modbusAscii') return null;\n\n const hints = this.template?.driverHints?.modbus;\n if (!hints) return null;\n const cfg = hints.setpointKeepalive || hints.setpointRefresh || null;\n if (!cfg) return null;\n if (cfg.enabled === false) return null;\n\n // Support either a single target or an array.\n // Two modes are supported:\n // 1) remainingTimeDpId-based refresh: write when remaining valid time drops below threshold.\n // 2) interval-based refresh: write the last setpoint every N ms. This is needed for\n // devices such as MENNEKES AMTRON, where HEMS communication can fall back after\n // a configured timeout but no dedicated \"remaining seconds\" register exists.\n const targetsRaw = Array.isArray(cfg.targets)\n ? cfg.targets\n : (cfg.setpointDpId || cfg.dpId)\n ? [cfg]\n : [];\n\n const normalizeSources = (raw) => {\n const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];\n return arr.map(src => {\n if (!src) return null;\n if (typeof src === 'string') return { relId: src };\n if (typeof src !== 'object') return null;\n const out = Object.assign({}, src);\n if (out.relId !== undefined) out.relId = String(out.relId || '').trim();\n if (out.aliasRelId !== undefined && !out.relId) out.relId = String(out.aliasRelId || '').trim();\n if (out.dpId !== undefined) out.dpId = String(out.dpId || '').trim();\n if (out.setpointDpId !== undefined && !out.dpId) out.dpId = String(out.setpointDpId || '').trim();\n return out;\n }).filter(Boolean);\n };\n\n const targets = [];\n for (const t of targetsRaw) {\n if (!t) continue;\n const setpointDpId = (t.setpointDpId || t.dpId || '').toString();\n const remainingTimeDpId = (t.remainingTimeDpId || t.validTimeDpId || '').toString();\n const intervalMsRaw = Number(t.intervalMs ?? t.refreshIntervalMs ?? t.periodMs ?? cfg.intervalMs ?? cfg.refreshIntervalMs ?? 0);\n const intervalMs = Number.isFinite(intervalMsRaw) && intervalMsRaw > 0 ? intervalMsRaw : 0;\n if (!setpointDpId) continue;\n if (!remainingTimeDpId && !intervalMs) continue;\n targets.push({\n setpointDpId,\n remainingTimeDpId,\n refreshBelowS: Number(t.refreshBelowS ?? t.refreshBelowSec ?? cfg.refreshBelowS ?? 15),\n minWriteIntervalMs: Number(t.minWriteIntervalMs ?? cfg.minWriteIntervalMs ?? 1000),\n unsupportedBackoffMs: Number(t.unsupportedBackoffMs ?? t.writeRejectBackoffMs ?? t.disableOnErrorMs ?? cfg.unsupportedBackoffMs ?? cfg.writeRejectBackoffMs ?? cfg.disableOnErrorMs ?? hints.setpointKeepaliveUnsupportedBackoffMs ?? 300000),\n intervalMs,\n useLastCommandValue: (t.useLastCommandValue === true || cfg.useLastCommandValue === true || t.commandValue === true),\n requireEverWritten: (t.requireEverWritten !== undefined) ? (t.requireEverWritten !== false) : undefined,\n fallbackCommandSources: normalizeSources(t.fallbackCommandSources || t.commandSources || t.fallbackAliasRelIds || t.commandAliasRelIds),\n // Optional safety gate for watchdog refreshes. Example: Alfen phase-mode\n // refresh should only run while a positive current command is active; otherwise\n // a stale phase command can wake the charger's EMS path even though charging is\n // supposed to be disabled.\n activeIfCommandDpId: String(t.activeIfCommandDpId || t.activeIfDpId || '').trim(),\n activeIfCommandValueGt: Number(t.activeIfCommandValueGt ?? t.activeIfGreaterThan ?? t.activeIfGt ?? NaN),\n activeIfCommandSources: normalizeSources(t.activeIfCommandSources || t.activeIfSources || t.activeIfAliasRelIds),\n });\n }\n\n if (!targets.length) return null;\n\n return {\n checkPeriodMs: Number(cfg.checkPeriodMs ?? cfg.periodMs ?? 5000),\n targets,\n exclusiveGroups: this._normalizeExclusiveSetpointGroups(cfg.exclusiveGroups || cfg.exclusiveSetpointGroups || []),\n // If a charger answers \"illegal data address/value\" for a setpoint, pause only the\n // automatic keepalive for that target. Direct user writes still surface the real error.\n unsupportedBackoffMs: Number(cfg.unsupportedBackoffMs ?? cfg.writeRejectBackoffMs ?? cfg.disableOnErrorMs ?? hints.setpointKeepaliveUnsupportedBackoffMs ?? 300000),\n // Only start refreshing after the setpoint was written at least once by the adapter.\n requireEverWritten: (cfg.requireEverWritten !== false),\n logLevel: String(cfg.logLevel ?? cfg.keepaliveLogLevel ?? 'info').toLowerCase(),\n allowDuringPoll: (cfg.allowDuringPoll === true || cfg.allowWhilePolling === true || cfg.allowDuringRead === true),\n };\n }\n\n\n async _seedSetpointKeepaliveFromCommandAliases() {\n const cfg = this._getSetpointKeepaliveConfig();\n if (!cfg || !Array.isArray(cfg.targets) || !cfg.targets.length) return;\n\n const modHints = this.template?.driverHints?.modbus || {};\n const alfenHints = this._getAlfenHints ? this._getAlfenHints() : ((modHints && modHints.alfen && typeof modHints.alfen === 'object') ? modHints.alfen : {});\n const enabled = (modHints.seedSetpointKeepaliveFromAliases === true) ||\n (modHints.seedKeepaliveFromAliases === true) ||\n (cfg.seedFromCommandAliases === true) ||\n (this._isAlfenTemplate() && alfenHints.seedKeepaliveFromCommandAliases !== false);\n if (!enabled) return;\n\n const targets = new Set(cfg.targets.map(t => String(t && t.setpointDpId || '')).filter(Boolean));\n if (!targets.size) return;\n\n const readState = async (relId) => {\n if (!relId) return undefined;\n const st = await this.adapter.getStateAsync(relId).catch(() => null);\n if (!st || st.val === null || st.val === undefined) return undefined;\n return st.val;\n };\n const readAlias = async (aliasPath) => readState(this._aliasRelId(aliasPath));\n const readDp = async (dpId) => {\n const dp = this._getDpById(dpId);\n return dp ? readState(this.relStateId(dp)) : undefined;\n };\n const toNum = (v) => {\n if (typeof this._parseNumberWithUnits === 'function') return this._parseNumberWithUnits(v);\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string') {\n const s = v.trim().replace(',', '.');\n const direct = Number(s);\n if (Number.isFinite(direct)) return direct;\n const m = s.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (!m) return undefined;\n const n = Number(m[0]);\n return Number.isFinite(n) ? n : undefined;\n }\n if (typeof v === 'boolean') return v ? 1 : 0;\n return undefined;\n };\n const toBool = (v) => {\n if (typeof v === 'boolean') return v;\n if (typeof v === 'number' && Number.isFinite(v)) return v !== 0;\n if (typeof v === 'string') {\n const s = v.trim().toLowerCase();\n if (['true', '1', 'yes', 'on', 'an', 'ein'].includes(s)) return true;\n if (['false', '0', 'no', 'off', 'aus', 'nein'].includes(s)) return false;\n }\n return undefined;\n };\n const seedDp = async (dpId, value, sourceLabel) => {\n const dp = this._getDpById(dpId);\n if (!dp || !(dp.rw === 'rw' || dp.rw === 'wo')) return false;\n if (value === null || value === undefined) return false;\n let val = value;\n if (dp.type === 'boolean') {\n val = !!val;\n } else if (dp.type === 'string') {\n val = String(val);\n } else {\n const n = Number(val);\n if (!Number.isFinite(n)) return false;\n val = n;\n }\n\n const now = Date.now();\n // Mark it as known/active without claiming a write happened right now. The cyclic\n // keepalive will therefore send the first real refresh on its first tick.\n this._lastCommandedValueByDpId.set(String(dp.id), val);\n this._lastWriteByDpId.set(String(dp.id), now - 60000);\n this._setpointKeepaliveLastWriteByDpId.set(String(dp.id), 0);\n this._rememberAlfenMirrorCommandValues(String(dp.id), val, { markEverWritten: true });\n await this._persistSetpointValueIfNeeded(dp, val).catch(() => {});\n if (!this._seededKeepaliveLogTsByDpId) this._seededKeepaliveLogTsByDpId = new Map();\n const lastLog = Number(this._seededKeepaliveLogTsByDpId.get(String(dp.id)) || 0);\n if (!lastLog || (now - lastLog) > 60000) {\n this._seededKeepaliveLogTsByDpId.set(String(dp.id), now);\n this.adapter.log.info(`[${this.cfg.id}] SetpointKeepalive seeded ${dp.id}=${val}${sourceLabel ? ` from ${sourceLabel}` : ''}; first watchdog refresh will be sent on next keepalive tick.`);\n }\n return true;\n };\n\n // Alfen ACE: after adapter restart ioBroker keeps the command aliases as ack=true states,\n // but the runtime maps (_lastCommandedValueByDpId/_lastWriteByDpId) are empty. Without\n // seeding, requireEverWritten=true prevents the watchdog from refreshing the EMS registers.\n if (this._isAlfenTemplate()) {\n const runCurrentRaw = Number(alfenHints.runCurrentA ?? alfenHints.defaultEnableCurrentA ?? 6);\n const runCurrentA = Number.isFinite(runCurrentRaw) && runCurrentRaw > 0 ? Math.round(runCurrentRaw) : 6;\n const stopCurrentRaw = Number(alfenHints.stopCurrentA ?? 0);\n const stopCurrentA = Number.isFinite(stopCurrentRaw) && stopCurrentRaw >= 0 ? Math.round(stopCurrentRaw) : 0;\n const minRunCurrentRaw = Number(alfenHints.minRunCurrentA ?? alfenHints.positiveCurrentMinA ?? alfenHints.minimumRunCurrentA ?? 6);\n const minRunCurrentA = Number.isFinite(minRunCurrentRaw) && minRunCurrentRaw > 0 ? Math.round(minRunCurrentRaw) : 6;\n const normalizeCurrentSeed = (amp) => {\n const n = Number(amp);\n if (!Number.isFinite(n)) return undefined;\n let v = Math.round(n);\n if (v <= 0) return stopCurrentA;\n if (v < minRunCurrentA) v = minRunCurrentA;\n if (v > 80) v = 80;\n return v;\n };\n\n let currentSeed;\n let currentSource = '';\n if (targets.has('sET_CHARGING_CURRENT')) {\n const memoryCurrent = toNum(await readState(this._setpointMemoryRelId('sET_CHARGING_CURRENT')));\n const aliasCurrent = toNum(await readAlias('ctrl.currentLimitA'));\n const runAlias = toBool(await readAlias('ctrl.run'));\n const enableAlias = toBool(await readAlias('ctrl.chargeEnable'));\n const applied = toNum(await readAlias('r.appliedCurrentLimitA'));\n const released = toBool(await readAlias('r.chargingReleased'));\n const nativeSetpoint = toNum(await readDp('sET_CHARGING_CURRENT'));\n\n if (Number.isFinite(aliasCurrent) && aliasCurrent > 0.1) {\n currentSeed = Math.round(aliasCurrent);\n currentSource = 'aliases.ctrl.currentLimitA';\n } else if (runAlias === true || enableAlias === true) {\n currentSeed = runCurrentA;\n currentSource = runAlias === true ? 'aliases.ctrl.run' : 'aliases.ctrl.chargeEnable';\n } else if (Number.isFinite(memoryCurrent) && memoryCurrent > 0.1) {\n currentSeed = Math.round(memoryCurrent);\n currentSource = 'info.setpoints.sET_CHARGING_CURRENT';\n } else if (Number.isFinite(nativeSetpoint) && nativeSetpoint > 0.1) {\n currentSeed = Math.round(nativeSetpoint);\n currentSource = 'sET_CHARGING_CURRENT state';\n } else if (Number.isFinite(applied) && applied > 0.1 && released !== false) {\n currentSeed = Math.round(applied);\n currentSource = 'aliases.r.appliedCurrentLimitA';\n } else if ((Number.isFinite(aliasCurrent) && aliasCurrent <= 0.1) || runAlias === false || enableAlias === false) {\n currentSeed = stopCurrentA;\n currentSource = 'disabled command alias';\n }\n\n if (Number.isFinite(currentSeed)) {\n currentSeed = normalizeCurrentSeed(currentSeed);\n await seedDp('sET_CHARGING_CURRENT', currentSeed, currentSource);\n // Keep the user-facing command aliases coherent. This also fixes the visible\n // \"run=true but currentLimitA=0\" state after restarts/upgrades.\n await this._setStateCached(this._aliasRelId('ctrl.currentLimitA'), currentSeed, true);\n await this._setStateCached(this._aliasRelId('ctrl.run'), currentSeed > 0.1, true);\n await this._setStateCached(this._aliasRelId('ctrl.chargeEnable'), currentSeed > 0.1, true);\n }\n }\n\n if (targets.has('cHARGE_USING_PHASES')) {\n // Alfen ACE phase mode is a write command. Do not seed it from the native readback or\n // from old info.setpoints memory, because earlier builds persisted stale value 1 and\n // forced the charger back to single-phase after every restart/keepalive tick.\n const allowSeedOne = alfenHints.allowSeedOnePhaseFromAlias === true;\n let phaseSeed = toNum(await readAlias('ctrl.phaseMode'));\n let phaseSource = 'aliases.ctrl.phaseMode';\n if (phaseSeed === 1 && !allowSeedOne) {\n phaseSeed = undefined;\n }\n if (!(phaseSeed === 1 || phaseSeed === 3)) {\n const defPhase = Math.trunc(Number(alfenHints.defaultPhaseMode ?? 3));\n phaseSeed = defPhase === 1 ? 1 : 3;\n phaseSource = 'alfen defaultPhaseMode';\n }\n if (phaseSeed === 1 || phaseSeed === 3) {\n await seedDp('cHARGE_USING_PHASES', phaseSeed, phaseSource);\n await this._setStateCached(this._aliasRelId('ctrl.phaseMode'), phaseSeed, true);\n }\n }\n return;\n }\n\n // Generic opt-in behavior: seed keepalive targets from command-only aliases that write\n // to the same datapoint. This is intentionally conservative and only used by templates\n // that explicitly enable seedSetpointKeepaliveFromAliases.\n for (const t of cfg.targets) {\n const dpId = String(t && t.setpointDpId || '');\n if (!dpId) continue;\n if (this._lastCommandedValueByDpId.has(dpId) || this._lastWriteByDpId.has(dpId)) continue;\n const aliases = (this.aliasDefs || []).filter(def => def && def.commandOnlyAlias === true && String(def.writeDpId || def.dpId || '') === dpId);\n for (const def of aliases) {\n const raw = await readState(def.relId);\n if (raw === undefined) continue;\n const val = typeof def.toDevice === 'function' ? def.toDevice(raw) : raw;\n if (val === undefined || val === null) continue;\n if (await seedDp(dpId, val, def.relId)) break;\n }\n }\n }\n\n async _readRelativeStateValue(relId) {\n const rel = String(relId || '').trim();\n if (!rel) return undefined;\n const fullRel = rel.startsWith('devices.') ? rel : `${this.baseId}.${rel}`;\n const st = await this.adapter.getStateAsync(fullRel).catch(() => null);\n if (!st || st.val === null || st.val === undefined) return undefined;\n return st.val;\n }\n\n async _resolveWatchdogSourceValue(src, setDp = null) {\n if (!src || typeof src !== 'object') return undefined;\n\n let val;\n if (src.dpId) {\n const dp = this._getDpById(String(src.dpId));\n if (!dp) return undefined;\n const st = await this.adapter.getStateAsync(this.relStateId(dp)).catch(() => null);\n if (!st || st.val === null || st.val === undefined) return undefined;\n val = st.val;\n } else if (src.relId) {\n val = await this._readRelativeStateValue(src.relId);\n if (val === undefined) return undefined;\n } else if (src.value !== undefined) {\n val = src.value;\n } else {\n return undefined;\n }\n\n if (typeof val === 'boolean') {\n if (val === true && src.trueValue !== undefined) val = src.trueValue;\n else if (val === false && src.falseValue !== undefined) val = src.falseValue;\n else val = val ? 1 : 0;\n } else if (typeof val === 'string') {\n const st = val.trim();\n if (!st) return undefined;\n const lower = st.toLowerCase();\n if ((lower === 'true' || lower === 'on' || lower === 'yes' || lower === 'an') && src.trueValue !== undefined) val = src.trueValue;\n else if ((lower === 'false' || lower === 'off' || lower === 'no' || lower === 'aus') && src.falseValue !== undefined) val = src.falseValue;\n else {\n const n = Number(st);\n if (Number.isFinite(n)) val = n;\n else return undefined;\n }\n }\n\n let n = Number(val);\n if (!Number.isFinite(n)) return undefined;\n\n if (src.integer === true || src.round === true) n = Math.round(n);\n if (Number.isFinite(Number(src.minValue)) && n < Number(src.minValue)) {\n if (src.skipIfBelowMin === true || src.skipIfOutOfRange === true) return undefined;\n n = Number(src.minValue);\n }\n if (Number.isFinite(Number(src.maxValue)) && n > Number(src.maxValue)) {\n if (src.skipIfAboveMax === true || src.skipIfOutOfRange === true) return undefined;\n n = Number(src.maxValue);\n }\n if (Number.isFinite(Number(src.minValueExclusive)) && !(n > Number(src.minValueExclusive))) return undefined;\n if (Number.isFinite(Number(src.gt)) && !(n > Number(src.gt))) return undefined;\n if (Number.isFinite(Number(src.gte)) && !(n >= Number(src.gte))) return undefined;\n if (src.skipZero === true && Math.abs(n) < 1e-9) return undefined;\n\n if (Array.isArray(src.allowedValues) && src.allowedValues.length) {\n const allowed = src.allowedValues.map(x => Number(x)).filter(Number.isFinite);\n if (allowed.length && !allowed.includes(n)) return undefined;\n }\n\n const writeSrc = setDp ? ((setDp.source && setDp.source.write) || (setDp.source && setDp.source.fc ? setDp.source : null)) : null;\n if (writeSrc) {\n if (Number.isFinite(Number(writeSrc.minValue)) && n < Number(writeSrc.minValue)) n = Number(writeSrc.minValue);\n if (Number.isFinite(Number(writeSrc.maxValue)) && n > Number(writeSrc.maxValue)) n = Number(writeSrc.maxValue);\n if (writeSrc.integer === true || writeSrc.round === true) n = Math.round(n);\n if (Array.isArray(writeSrc.allowedValues) && writeSrc.allowedValues.length) {\n const allowed = writeSrc.allowedValues.map(x => Number(x)).filter(Number.isFinite);\n if (allowed.length && !allowed.includes(n)) return undefined;\n }\n }\n\n return n;\n }\n\n async _resolveWatchdogFallbackCommandValue(target, setDp) {\n const sources = Array.isArray(target && target.fallbackCommandSources) ? target.fallbackCommandSources : [];\n if (!sources.length) return undefined;\n for (const src of sources) {\n const v = await this._resolveWatchdogSourceValue(src, setDp);\n if (v !== undefined && v !== null && Number.isFinite(Number(v))) return Number(v);\n }\n return undefined;\n }\n\n async _watchdogActiveGatePasses(target) {\n const activeIfCommandDpId = String(target && target.activeIfCommandDpId || '').trim();\n if (!activeIfCommandDpId && !(Array.isArray(target && target.activeIfCommandSources) && target.activeIfCommandSources.length)) return true;\n\n let gateVal = NaN;\n if (activeIfCommandDpId && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(activeIfCommandDpId)) {\n gateVal = Number(this._lastCommandedValueByDpId.get(activeIfCommandDpId));\n }\n if (!Number.isFinite(gateVal) && Array.isArray(target.activeIfCommandSources) && target.activeIfCommandSources.length) {\n for (const src of target.activeIfCommandSources) {\n const v = await this._resolveWatchdogSourceValue(src, this._getDpById(activeIfCommandDpId));\n if (v !== undefined && v !== null && Number.isFinite(Number(v))) {\n gateVal = Number(v);\n break;\n }\n }\n }\n\n const gateGt = Number(target.activeIfCommandValueGt);\n if (!Number.isFinite(gateVal)) return false;\n if (Number.isFinite(gateGt) && !(gateVal > gateGt)) return false;\n return true;\n }\n\n async _startSetpointKeepalive() {\n const cfg = this._getSetpointKeepaliveConfig();\n if (!cfg) return;\n if (this._setpointKeepaliveTimer) return;\n\n const periodMs = Math.max(1000, Number(cfg.checkPeriodMs || 5000));\n\n const tick = async () => {\n if (this._setpointKeepaliveBusy) return;\n this._setpointKeepaliveBusy = true;\n try {\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n if (!this._connOk) return; // only when connected\n // The Modbus driver serializes operations internally. For strict write-watchdog\n // devices such as Alfen ACE, skipping keepalive while a poll is running can starve\n // the watchdog; allow templates to queue the refresh during reads.\n if (this.driver && this.driver._busy && cfg.allowDuringPoll !== true) return;\n\n const now = Date.now();\n const activeTargets = this._applyExclusiveSetpointGroupsToKeepaliveTargets(cfg.targets, cfg.exclusiveGroups || []);\n\n for (const t of activeTargets) {\n const setDp = this._getDpById(t.setpointDpId);\n const timeDp = t.remainingTimeDpId ? this._getDpById(t.remainingTimeDpId) : null;\n if (!setDp) continue;\n if (t.remainingTimeDpId && !timeDp) continue;\n if (!(setDp.rw === 'rw' || setDp.rw === 'wo')) continue;\n\n const unsupportedUntil = Number(this._setpointKeepaliveUnsupportedUntilByDpId.get(String(setDp.id)) || 0);\n if (unsupportedUntil && now < unsupportedUntil) continue;\n\n if (!(await this._watchdogActiveGatePasses(t))) continue;\n\n const hasFallbackSources = Array.isArray(t.fallbackCommandSources) && t.fallbackCommandSources.length > 0;\n const targetRequiresEverWritten = (t.requireEverWritten !== false) && (cfg.requireEverWritten !== false);\n if (targetRequiresEverWritten && !hasFallbackSources) {\n const hasEver = this._lastWriteByDpId.has(String(setDp.id));\n if (!hasEver) continue;\n }\n\n // Throttle repeated refresh writes\n const last = Number(this._setpointKeepaliveLastWriteByDpId.get(String(setDp.id)) || 0);\n const minWriteMs = Number.isFinite(t.minWriteIntervalMs) ? Math.max(250, t.minWriteIntervalMs) : 1000;\n if (last && (now - last) < minWriteMs) continue;\n\n let reason = '';\n if (timeDp) {\n // Remaining valid time (seconds)\n const timeState = await this.adapter.getStateAsync(this.relStateId(timeDp)).catch(() => null);\n const remainingS = timeState && timeState.val !== undefined ? Number(timeState.val) : NaN;\n if (!Number.isFinite(remainingS)) continue;\n\n const thresh = Number.isFinite(t.refreshBelowS) ? t.refreshBelowS : 15;\n if (remainingS > thresh) continue;\n reason = `remainingS=${remainingS}`;\n } else {\n const intervalMs = Number.isFinite(t.intervalMs) ? Math.max(1000, t.intervalMs) : 0;\n if (!intervalMs) continue;\n if (last && (now - last) < intervalMs) continue;\n reason = `intervalMs=${intervalMs}`;\n }\n\n // Use the last successfully commanded value when requested. This is important\n // for Alfen ACE: the watchdog must repeat the commanded Max Current, not a\n // transient/wrong readback that may decode as 0 A before the adaptive address\n // variant is cached.\n let setVal = NaN;\n if (t.useLastCommandValue && this._lastCommandedValueByDpId && this._lastCommandedValueByDpId.has(String(setDp.id))) {\n setVal = Number(this._lastCommandedValueByDpId.get(String(setDp.id)));\n }\n if (!Number.isFinite(setVal)) {\n const fallbackVal = await this._resolveWatchdogFallbackCommandValue(t, setDp);\n if (fallbackVal !== undefined && fallbackVal !== null && Number.isFinite(Number(fallbackVal))) {\n setVal = Number(fallbackVal);\n }\n }\n if (!Number.isFinite(setVal)) {\n const setState = await this.adapter.getStateAsync(this.relStateId(setDp)).catch(() => null);\n setVal = setState && setState.val !== undefined ? Number(setState.val) : NaN;\n }\n if (!Number.isFinite(setVal)) continue;\n\n // Send refresh write (best-effort). Respect write throttling if enabled.\n // Handle errors per target so one unsupported Alfen/EVCS setpoint does not stop\n // the watchdog refresh of other supported setpoints.\n try {\n if (this._isWriteQueueEnabled()) {\n this._enqueueWrite(null, setDp, setVal, setVal, { skipPostWriteRepeat: true, isSetpointKeepalive: true });\n } else {\n await this.driver.writeDatapoint(setDp, setVal);\n this._recordWrite(setDp.id, { skipPostWriteRepeat: true });\n await this._ackWrittenValue(setDp, setVal);\n }\n\n this._setpointKeepaliveLastWriteByDpId.set(String(setDp.id), now);\n const refreshMsg = `[${this.cfg.id}] SetpointKeepalive: refreshed ${setDp.id}=${setVal}${reason ? ` (${reason})` : ''}`;\n if (this._isAlfenTemplate && this._isAlfenTemplate()) {\n if (!this._alfenKeepaliveInfoCountByDpId) this._alfenKeepaliveInfoCountByDpId = new Map();\n const c = Number(this._alfenKeepaliveInfoCountByDpId.get(String(setDp.id)) || 0);\n if (c < 3) {\n this._alfenKeepaliveInfoCountByDpId.set(String(setDp.id), c + 1);\n this.adapter.log.info(refreshMsg);\n } else {\n this.adapter.log.debug(refreshMsg);\n }\n } else {\n this.adapter.log.debug(refreshMsg);\n }\n } catch (e) {\n if (this._isSuppressedUnsupportedWriteError(e)) {\n this._handleSuppressedUnsupportedWrite(e, setDp.id);\n continue;\n }\n const msg = (e && e.message) ? e.message : String(e);\n const lower = msg.toLowerCase();\n if (this._isAlfenTemplate() && this._looksLikePermanentModbusWriteReject(msg)) {\n this._handleAlfenRejectedControlWrite(e, setDp.id);\n continue;\n }\n if (lower.includes('illegal data address') || lower.includes('illegal data value') || lower.includes('exception 2') || lower.includes('exception 3')) {\n const targetBackoffMs = Number(t.unsupportedBackoffMs);\n const backoffMs = Number.isFinite(targetBackoffMs) && targetBackoffMs > 0\n ? targetBackoffMs\n : (Number.isFinite(cfg.unsupportedBackoffMs) && cfg.unsupportedBackoffMs > 0 ? cfg.unsupportedBackoffMs : 300000);\n this._setpointKeepaliveUnsupportedUntilByDpId.set(String(setDp.id), Date.now() + backoffMs);\n this.adapter.log.debug(`[${this.cfg.id}] SetpointKeepalive: ${setDp.id} is currently not accepted by the device; pausing automatic refresh for ${backoffMs} ms. ${msg}`);\n continue;\n }\n throw e;\n }\n }\n } catch (e) {\n // Best-effort: do not spam; poll loop will surface transport errors.\n this.adapter.log.debug(`[${this.cfg.id}] SetpointKeepalive error: ${e && e.message ? e.message : e}`);\n } finally {\n this._setpointKeepaliveBusy = false;\n }\n };\n\n // Slightly delayed first check, then periodically\n setTimeout(() => { tick().catch(() => {}); }, 2000);\n this._setpointKeepaliveTimer = setInterval(() => { tick().catch(() => {}); }, periodMs);\n const enabledMsg = `[${this.cfg.id}] SetpointKeepalive enabled: targets=[${cfg.targets.map(t => t.setpointDpId).join(', ')}], periodMs=${periodMs}`;\n const keepaliveLogLevel = String(cfg.logLevel || 'info').toLowerCase();\n if (keepaliveLogLevel === 'silent' || keepaliveLogLevel === 'none' || keepaliveLogLevel === 'off') {\n // intentionally quiet\n } else if (keepaliveLogLevel === 'debug') {\n this.adapter.log.debug(enabledMsg);\n } else if (keepaliveLogLevel === 'warn' || keepaliveLogLevel === 'warning') {\n this.adapter.log.warn(enabledMsg);\n } else {\n this.adapter.log.info(enabledMsg);\n }\n }\n\n\n _getSungrowSignedPowerControlConfigs() {\n const hints = this.template?.driverHints?.modbus || {};\n const raw = hints.sungrowSignedPowerControls || hints.sungrowSignedPowerControl || hints.sungrowPowerControl;\n const arr = Array.isArray(raw) ? raw : (raw && typeof raw === 'object' ? [raw] : []);\n return arr.filter(cfg => cfg && cfg.enabled !== false && (cfg.heartbeatAutoRefresh === true || cfg.autoRefreshHeartbeat === true) && String(cfg.heartbeatDpId || '').trim());\n }\n\n _getSungrowHeartbeatIntervalMs(configs) {\n let interval = 0;\n const values = Array.isArray(configs) ? configs : [];\n for (const cfg of values) {\n const explicit = Number(\n cfg.heartbeatRefreshIntervalMs ??\n cfg.heartbeatIntervalMs ??\n cfg.heartbeatEveryMs ??\n cfg.heartbeatCycleMs ??\n 0\n );\n if (Number.isFinite(explicit) && explicit > 0) {\n interval = interval > 0 ? Math.min(interval, explicit) : explicit;\n continue;\n }\n\n // Sungrow recommends refreshing the timeout value at roughly half of the\n // configured heartbeat timeout (e.g. 20s -> write 20 every ~10s).\n const hbSeconds = Number(cfg.heartbeatValue ?? cfg.heartbeatDefaultValue ?? cfg.heartbeatFixedValue ?? 20);\n const fromTimeout = Number.isFinite(hbSeconds) && hbSeconds > 0 ? (hbSeconds * 500) : 10000;\n interval = interval > 0 ? Math.min(interval, fromTimeout) : fromTimeout;\n }\n\n if (!Number.isFinite(interval) || interval <= 0) interval = 10000;\n\n // Do not write faster than the configured minimum interval plus a small guard.\n let minGuard = 1000;\n for (const cfg of values) {\n const min = Number(cfg.heartbeatMinIntervalMs ?? cfg.heartbeatWriteMinIntervalMs ?? 0);\n if (Number.isFinite(min) && min > 0) minGuard = Math.max(minGuard, min + 500);\n }\n\n return Math.max(1000, Math.round(Math.max(interval, minGuard)));\n }\n\n async _startSungrowExternalEmsHeartbeat() {\n if (this._sungrowHeartbeatTimer) return;\n const configs = this._getSungrowSignedPowerControlConfigs();\n if (!configs.length) return;\n if (!this.driver || typeof this.driver.refreshSungrowSignedPowerControlHeartbeats !== 'function') return;\n\n const intervalMs = this._getSungrowHeartbeatIntervalMs(configs);\n\n const tick = async () => {\n if (this._sungrowHeartbeatBusy) return;\n this._sungrowHeartbeatBusy = true;\n try {\n if (!this.started) return;\n if (!this.driver || typeof this.driver.refreshSungrowSignedPowerControlHeartbeats !== 'function') return;\n if (!this._connOk) return;\n await this.driver.refreshSungrowSignedPowerControlHeartbeats({ reason: 'external-ems-heartbeat' });\n } catch (e) {\n // Heartbeat refresh is best-effort. Transport errors will also surface via the poll loop.\n this.adapter.log.debug(`[${this.cfg.id}] Sungrow External EMS heartbeat refresh error: ${e && e.message ? e.message : e}`);\n } finally {\n this._sungrowHeartbeatBusy = false;\n }\n };\n\n // Start slightly after the first successful poll/control restore so we do not\n // bunch heartbeat writes with initial read/write commands.\n this._sungrowHeartbeatStartTimer = setTimeout(() => {\n this._sungrowHeartbeatStartTimer = null;\n tick().catch(() => {});\n }, Math.min(3000, intervalMs));\n this._sungrowHeartbeatTimer = setInterval(() => { tick().catch(() => {}); }, intervalMs);\n this.adapter.log.debug(`[${this.cfg.id}] Sungrow External EMS heartbeat auto-refresh enabled: intervalMs=${intervalMs}`);\n }\n\n _getPreWritesForDp(dpId) {\n const id = (dpId ?? '').toString();\n if (!id) return [];\n const hints = this.template?.driverHints?.modbus;\n const cfg = hints?.preWrites;\n if (!Array.isArray(cfg) || !cfg.length) return [];\n\n const wanted = id.toLowerCase();\n const out = [];\n for (const rule of cfg) {\n if (!rule) continue;\n const trig = (rule.triggerDpId ?? rule.onWriteDpId ?? '').toString().toLowerCase();\n if (!trig || trig !== wanted) continue;\n\n const cooldownMsRaw = Number(rule.cooldownMs ?? rule.throttleMs ?? rule.minIntervalMs ?? 0);\n const cooldownMs = Number.isFinite(cooldownMsRaw) && cooldownMsRaw > 0 ? cooldownMsRaw : 0;\n\n const writes = Array.isArray(rule.writes) ? rule.writes : [];\n for (const w of writes) {\n if (!w || !w.dpId) continue;\n if (w.value === undefined) continue;\n out.push({ dpId: String(w.dpId), value: w.value, triggerDpId: wanted, cooldownMs });\n }\n }\n return out;\n }\n\n async _maybeExecutePreWritesForDp(dpId) {\n if (!this.driver || typeof this.driver.writeDatapoint !== 'function') return;\n const plan = this._getPreWritesForDp(dpId);\n if (!plan.length) return;\n\n const triggerKey = (dpId ?? '').toString().toLowerCase();\n const cooldownMs = plan.reduce((m, s) => Math.max(m, Number(s.cooldownMs || 0)), 0);\n if (cooldownMs > 0) {\n const lastTs = this._preWriteLastTsByTrigger.get(triggerKey) || 0;\n const now = Date.now();\n if (lastTs && now - lastTs < cooldownMs) return;\n }\n\n for (const step of plan) {\n try {\n const dp = this._getDpById(step.dpId);\n if (!dp) continue;\n if (!(dp.rw === 'rw' || dp.rw === 'wo')) continue;\n await this.driver.writeDatapoint(dp, step.value);\n // Track pre-write activity as well (important for fail-safe logic).\n this._recordWrite(dp.id);\n await this._ackWrittenValue(dp, step.value);\n } catch (e) {\n // Pre-write failure should surface clearly (it affects the main command).\n throw e;\n }\n }\n\n if (cooldownMs > 0) this._preWriteLastTsByTrigger.set(triggerKey, Date.now());\n }\n\n async _ackWrittenValue(dp, rawValue, isCurrent = () => true) {\n if (!dp || !dp.id || !isCurrent()) return;\n\n try {\n if (this._lastCommandedValueByDpId) this._lastCommandedValueByDpId.set(String(dp.id), rawValue);\n } catch (_) {}\n\n // Update underlying datapoint state\n const dpRelId = this.relStateId(dp);\n await this._setStateCached(dpRelId, rawValue, true);\n\n // Update all alias states that reference this datapoint (best-effort).\n // Some control aliases intentionally use a different readback dpId than writeDpId\n // (Alfen ACE: ctrl.currentLimitA writes Modbus Server Max Current but reads the\n // separate Actual Applied Max Current register). For these command-only aliases,\n // also acknowledge the alias when the writeDpId matches, otherwise the UI can snap\n // back to a volatile readback/default value after a successful command.\n if (!Array.isArray(this.aliasDefs) || !this.aliasDefs.length) return;\n const writtenKey = String(dp.id);\n for (const def of this.aliasDefs) {\n try {\n if (!isCurrent()) return;\n if (!def || def.kind !== 'dp') continue;\n // A write acknowledgement is not device feedback. Additive semantic\n // readback aliases only change when the driver actually reads the source.\n if (def.deviceReadOnly === true) continue;\n // A Modbus write response confirms transmission, not the charger's\n // applied limit. Keep DEPower readback aliases tied to real polling.\n if (this.template?.driverHints?.oemModbusV1003 && def.rw !== 'rw' && def.rw !== 'wo') continue;\n const readsWrittenDp = String(def.dpId || '') === writtenKey;\n const writesWrittenDp = String(def.writeDpId || '') === writtenKey;\n if (!readsWrittenDp && !(writesWrittenDp && def.commandOnlyAlias === true)) continue;\n\n let outVal = rawValue;\n if (typeof def.fromDevice === 'function') {\n outVal = def.fromDevice(rawValue);\n if (outVal === undefined) continue;\n }\n await this._setStateCached(def.relId, outVal, true);\n } catch (_) {\n // ignore\n }\n }\n }\n}\n\nmodule.exports = {\n DeviceRuntime,\n};\n","usedDeprecatedRules":[]}]
|