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.
Files changed (762) hide show
  1. package/NEXOWATT_EOS_BUILD_INFO.json +17 -11
  2. package/README.md +37 -9
  3. package/START_HIER_9.0.21.md +53 -0
  4. package/START_HIER_9.0.22.md +48 -0
  5. package/START_HIER_9.0.23.md +47 -0
  6. package/START_HIER_9.0.24.md +70 -0
  7. package/START_HIER_9.0.25.md +60 -0
  8. package/adminWww/.vite/manifest.json +55 -55
  9. package/adminWww/NEXOWATT_EOS_FRONTEND_MANIFEST.json +13760 -13760
  10. package/adminWww/assets/{AdapterUpdateDialog-Dxl_b7Op.js → AdapterUpdateDialog-CLDpmxDx.js} +1 -1
  11. package/adminWww/assets/{Adapters-CVKKhXmI.js → Adapters-BCGeX2v7.js} +1 -1
  12. package/adminWww/assets/{ConfigManager-Bf6nTAkL.js → ConfigManager-B_sJf5_w.js} +1 -1
  13. package/adminWww/assets/{Enums-CJHVJY7t.js → Enums-D3n1pOtc.js} +1 -1
  14. package/adminWww/assets/{Fields-DWHbZKvm.js → Fields-Bdx5gPoT.js} +1 -1
  15. package/adminWww/assets/{Files-a6owMTXA.js → Files-BPK84lYU.js} +1 -1
  16. package/adminWww/assets/{Hosts-LtEMeXpV.js → Hosts--Jr6oLf2.js} +1 -1
  17. package/adminWww/assets/{Instances-DhChziA1.js → Instances-DxTOzFus.js} +1 -1
  18. package/adminWww/assets/{Intro-Cyq9gVDC.js → Intro-CYBGeZtu.js} +1 -1
  19. package/adminWww/assets/{Logs-wcramXsg.js → Logs-CVNC-4S8.js} +1 -1
  20. package/adminWww/assets/{Objects-DINVHd_e.js → Objects-Cqm9Rvym.js} +1 -1
  21. package/adminWww/assets/{Overview-DK4R41zR.js → Overview-JgjcHwlz.js} +1 -1
  22. package/adminWww/assets/{State-DcEACXzL.js → State-BV14HSwZ.js} +1 -1
  23. package/adminWww/assets/{UsedResources-C1LcM0Rb.js → UsedResources-Dz48WzEF.js} +1 -1
  24. package/adminWww/assets/{Users-DvDdSyDY.js → Users-D19YlRCD.js} +1 -1
  25. package/adminWww/assets/{bootstrap-Dbj_GbnP.js → bootstrap-a7POLSDr.js} +4 -4
  26. package/adminWww/assets/{hostInit-BNFIx0-f.js → hostInit-keGjwsZR.js} +1 -1
  27. package/adminWww/assets/{icons-material-DVbdXNgr.js → icons-material-Omb_HCfb.js} +1 -1
  28. package/adminWww/assets/{index-CoKP1NSA.js → index-DqPrQK7T.js} +2 -2
  29. package/adminWww/assets/{installSVGRenderer-CMvku1F1.js → installSVGRenderer-iWfLFoQU.js} +1 -1
  30. package/adminWww/assets/{mf-entry-bootstrap-0-ac330bce.js → mf-entry-bootstrap-0-2a856bb6.js} +2 -2
  31. package/adminWww/index.html +23 -23
  32. package/adminWww/mf-manifest.json +1 -1
  33. package/adminWww/mf-stats.json +1 -1
  34. package/adminWww/remoteEntry-eos-9.0.25.js +12 -0
  35. package/adminWww/remoteEntry.js +1 -1
  36. package/build/lib/eosHistoryBackupScope.js +73 -0
  37. package/build/lib/eosHistoryBackupScope.js.map +1 -0
  38. package/build/lib/eosKiosk.js +348 -0
  39. package/build/lib/eosKiosk.js.map +1 -0
  40. package/build/lib/eosLegacyMigration.js +24 -3
  41. package/build/lib/eosLegacyMigration.js.map +1 -1
  42. package/build/lib/eosLicenseService.js +1 -1
  43. package/build/lib/eosLicenseService.js.map +1 -1
  44. package/build/lib/eosModuleConfigStore.js +2 -2
  45. package/build/lib/eosModuleConfigStore.js.map +1 -1
  46. package/build/lib/eosModuleHost.js +289 -25
  47. package/build/lib/eosModuleHost.js.map +1 -1
  48. package/build/lib/eosModuleHttp.js +71 -8
  49. package/build/lib/eosModuleHttp.js.map +1 -1
  50. package/build/lib/eosModuleProcess.js +317 -0
  51. package/build/lib/eosModuleProcess.js.map +1 -0
  52. package/build/lib/eosModuleProcessProtocol.js +213 -0
  53. package/build/lib/eosModuleProcessProtocol.js.map +1 -0
  54. package/build/lib/eosModuleProcessWorker.js +279 -0
  55. package/build/lib/eosModuleProcessWorker.js.map +1 -0
  56. package/build/lib/eosPostgresProvisioning.js +189 -0
  57. package/build/lib/eosPostgresProvisioning.js.map +1 -0
  58. package/build/lib/eosRuntimeControl.js +224 -0
  59. package/build/lib/eosRuntimeControl.js.map +1 -0
  60. package/build/lib/eosRuntimeHealth.js +170 -0
  61. package/build/lib/eosRuntimeHealth.js.map +1 -0
  62. package/build/lib/eosUiProcess.js +728 -0
  63. package/build/lib/eosUiProcess.js.map +1 -0
  64. package/build/lib/eosUiProcessRpc.js +292 -0
  65. package/build/lib/eosUiProcessRpc.js.map +1 -0
  66. package/build/lib/eosUiProcessWorker.js +443 -0
  67. package/build/lib/eosUiProcessWorker.js.map +1 -0
  68. package/build/lib/eosUiSecretCodec.js +64 -0
  69. package/build/lib/eosUiSecretCodec.js.map +1 -0
  70. package/build/lib/eosUnifiedBoundary.js +28 -4
  71. package/build/lib/eosUnifiedBoundary.js.map +1 -1
  72. package/build/lib/eosUpdateSnapshot.js +32 -1
  73. package/build/lib/eosUpdateSnapshot.js.map +1 -1
  74. package/build/lib/web.js +175 -18
  75. package/build/lib/web.js.map +1 -1
  76. package/build/main.js +6 -2
  77. package/build/main.js.map +1 -1
  78. package/docs/reports/unified-9.0.21/CRA_NACHWEISSTAND.md +159 -0
  79. package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_BACKEND_REVIEW.md +30 -0
  80. package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_UI_REVIEW.md +44 -0
  81. package/docs/reports/unified-9.0.21/CUSTOMER_UPDATE_WORKER_REVIEW.md +147 -0
  82. package/docs/reports/unified-9.0.21/CUSTOMER_WORKER_ZWEITPRUEFUNG.md +108 -0
  83. package/docs/reports/unified-9.0.21/DEVICE_STABILITY_REVIEW.md +50 -0
  84. package/docs/reports/unified-9.0.21/EMS_STABILITAET.md +41 -0
  85. package/docs/reports/unified-9.0.21/HISTORY_TARIFF_STABILITY_REVIEW.md +48 -0
  86. package/docs/reports/unified-9.0.21/MQTT_ZWEITPRUEFUNG_EMS.md +47 -0
  87. package/docs/reports/unified-9.0.21/PERSISTENZ_STABILITAET.md +76 -0
  88. package/docs/reports/unified-9.0.21/PRUEFBERICHT.md +64 -0
  89. package/docs/reports/unified-9.0.21/SECURITY_STABILITY_REVIEW.md +118 -0
  90. package/docs/reports/unified-9.0.21/UI_SECURITY_GATE_REVIEW.md +62 -0
  91. package/docs/reports/unified-9.0.21/UPDATE_HTTP_SNAPSHOT_PRUEFUNG.md +46 -0
  92. package/docs/reports/unified-9.0.21/raw/INDEX.json +1307 -0
  93. package/docs/reports/unified-9.0.21/raw/audit-full.log +345 -0
  94. package/docs/reports/unified-9.0.21/raw/audit-full.result.json +14 -0
  95. package/docs/reports/unified-9.0.21/raw/audit-runtime.log +23 -0
  96. package/docs/reports/unified-9.0.21/raw/audit-runtime.result.json +15 -0
  97. package/docs/reports/unified-9.0.21/raw/backend-final.log +5 -0
  98. package/docs/reports/unified-9.0.21/raw/backend-final.result.json +14 -0
  99. package/docs/reports/unified-9.0.21/raw/cra/frontend-installer-sbom.json +32 -0
  100. package/docs/reports/unified-9.0.21/raw/customer-update-glue/root-glue-focused-node24.tap +34 -0
  101. package/docs/reports/unified-9.0.21/raw/customer-update-service/lint.log +0 -0
  102. package/docs/reports/unified-9.0.21/raw/customer-update-service/real920-archive-inspection.json +20 -0
  103. package/docs/reports/unified-9.0.21/raw/customer-update-service/service-node22.log +110 -0
  104. package/docs/reports/unified-9.0.21/raw/customer-update-service/service-node24.log +24 -0
  105. package/docs/reports/unified-9.0.21/raw/customer-update-service/service-verification.json +54 -0
  106. package/docs/reports/unified-9.0.21/raw/customer-update-service/typecheck.log +0 -0
  107. package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-lint.log +0 -0
  108. package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-node22.tap +86 -0
  109. package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-node24.tap +20 -0
  110. package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-strict-typecheck.log +0 -0
  111. package/docs/reports/unified-9.0.21/raw/customer-update-worker/customer-worker-typecheck.log +0 -0
  112. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/independent-worker-probes.cjs +109 -0
  113. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/node22.tap +86 -0
  114. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/node24.tap +20 -0
  115. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/probes-node22.tap +44 -0
  116. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/probes-node24.tap +13 -0
  117. package/docs/reports/unified-9.0.21/raw/customer-update-worker/independent/receipt.json +89 -0
  118. package/docs/reports/unified-9.0.21/raw/customer-update-worker/receipt.json +42 -0
  119. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-catch-node22.log +1959 -0
  120. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-test-update-node22.log +1968 -0
  121. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-drain-test-update-node24.log +337 -0
  122. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-runtime-review-node22.log +1895 -0
  123. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-before-runtime-review-node24.log +317 -0
  124. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-final-node22.log +1959 -0
  125. package/docs/reports/unified-9.0.21/raw/device-mqtt/all-devices-final-node24.log +327 -0
  126. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-final-message-test-node22.log +36 -0
  127. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-final-message-test-node24.log +28 -0
  128. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-message-session-node22.log +36 -0
  129. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-message-session-node24.log +28 -0
  130. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-command-replay-repro-node22.log +15 -0
  131. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-command-replay-repro-node24.log +13 -0
  132. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-shutdown-repro-node22.log +16 -0
  133. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-mqtt-shutdown-repro-node24.log +14 -0
  134. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-resources-node22.log +74 -0
  135. package/docs/reports/unified-9.0.21/raw/device-mqtt/baseline-resources-node24.log +46 -0
  136. package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-before-drain-test-update.json +206 -0
  137. package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-before-runtime-review.json +150 -0
  138. package/docs/reports/unified-9.0.21/raw/device-mqtt/commands-final.json +275 -0
  139. package/docs/reports/unified-9.0.21/raw/device-mqtt/commands.json +134 -0
  140. package/docs/reports/unified-9.0.21/raw/device-mqtt/env-node22.log +3 -0
  141. package/docs/reports/unified-9.0.21/raw/device-mqtt/env-node24.log +1 -0
  142. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-drain-test-update-node22.log +2 -0
  143. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-drain-test-update-node24.log +0 -0
  144. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-runtime-review-node22.log +2 -0
  145. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-before-runtime-review-node24.log +0 -0
  146. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-final-node22.log +2 -0
  147. package/docs/reports/unified-9.0.21/raw/device-mqtt/lint-final-node24.log +0 -0
  148. package/docs/reports/unified-9.0.21/raw/device-mqtt/mqtt-command-replay-repro.cjs +38 -0
  149. package/docs/reports/unified-9.0.21/raw/device-mqtt/mqtt-shutdown-repro.cjs +31 -0
  150. package/docs/reports/unified-9.0.21/raw/device-mqtt/regression-node22.log +322 -0
  151. package/docs/reports/unified-9.0.21/raw/device-mqtt/regression-node24.log +55 -0
  152. package/docs/reports/unified-9.0.21/raw/device-mqtt/run-evidence.py +23 -0
  153. package/docs/reports/unified-9.0.21/raw/device-mqtt/run-final-evidence.py +20 -0
  154. package/docs/reports/unified-9.0.21/raw/device-mqtt/runtime-lint-920.json +1 -0
  155. package/docs/reports/unified-9.0.21/raw/device-mqtt/runtime-lint-921.json +1 -0
  156. package/docs/reports/unified-9.0.21/raw/device-mqtt/source-hashes.json +16 -0
  157. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-drain-test-update-node22.log +0 -0
  158. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-drain-test-update-node24.log +0 -0
  159. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-runtime-review-node22.log +0 -0
  160. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-before-runtime-review-node24.log +0 -0
  161. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-final-node22.log +0 -0
  162. package/docs/reports/unified-9.0.21/raw/device-mqtt/types-final-node24.log +0 -0
  163. package/docs/reports/unified-9.0.21/raw/ems/baseline-files-eslint.json +1 -0
  164. package/docs/reports/unified-9.0.21/raw/ems/changed-files-eslint.json +1 -0
  165. package/docs/reports/unified-9.0.21/raw/ems/engine.patch +38 -0
  166. package/docs/reports/unified-9.0.21/raw/ems/eslint-delta.json +6 -0
  167. package/docs/reports/unified-9.0.21/raw/ems/evidence.json +171 -0
  168. package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-baseline-node24.log +124 -0
  169. package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-node22.log +56 -0
  170. package/docs/reports/unified-9.0.21/raw/ems/farm-concurrency-node24.log +15 -0
  171. package/docs/reports/unified-9.0.21/raw/ems/farm-owned-methods.patch +133 -0
  172. package/docs/reports/unified-9.0.21/raw/ems/generated-regression-node22.log +460 -0
  173. package/docs/reports/unified-9.0.21/raw/ems/generated-regression-node24.log +82 -0
  174. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-frozen-node22.log +170 -0
  175. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-frozen-node24.log +33 -0
  176. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-review-node22.log +153 -0
  177. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-review-node24.log +39 -0
  178. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-reviewed-node22.log +170 -0
  179. package/docs/reports/unified-9.0.21/raw/ems/mqtt-final-reviewed-node24.log +33 -0
  180. package/docs/reports/unified-9.0.21/raw/ems/mqtt-queue-inheritance-before.log +28 -0
  181. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-baseline-node24.log +64 -0
  182. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-initial-timing.log +32 -0
  183. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-node22.log +44 -0
  184. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-review-node24.log +13 -0
  185. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-session-review.cjs +23 -0
  186. package/docs/reports/unified-9.0.21/raw/ems/mqtt-runtime-session-review.log +119 -0
  187. package/docs/reports/unified-9.0.21/raw/ems/nvp-baseline-node22.log +170 -0
  188. package/docs/reports/unified-9.0.21/raw/ems/nvp-baseline-node24.log +121 -0
  189. package/docs/reports/unified-9.0.21/raw/ems/nvp-node22.log +68 -0
  190. package/docs/reports/unified-9.0.21/raw/ems/nvp-node24.log +17 -0
  191. package/docs/reports/unified-9.0.21/raw/ems/ui-code-delta-inventory.json +32 -0
  192. package/docs/reports/unified-9.0.21/raw/ems/ui-docs-check.log +6 -0
  193. package/docs/reports/unified-9.0.21/raw/ems/ui-farm-fingerprint-moves.json +74 -0
  194. package/docs/reports/unified-9.0.21/raw/ems/ui-lint-policy-tests.log +6 -0
  195. package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-final-node22.log +5 -0
  196. package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-final-node24.log +8 -0
  197. package/docs/reports/unified-9.0.21/raw/ems/ui-lint-security-initial.log +6 -0
  198. package/docs/reports/unified-9.0.21/raw/ems/ui-main-full-delta.patch +135 -0
  199. package/docs/reports/unified-9.0.21/raw/ems/ui-reviewed-changes.json +93 -0
  200. package/docs/reports/unified-9.0.21/raw/ems/ui-reviewed-findings-before.json +3185 -0
  201. package/docs/reports/unified-9.0.21/raw/ems/ui-security-final-node22.json +28833 -0
  202. package/docs/reports/unified-9.0.21/raw/ems/ui-security-final-node24.json +28833 -0
  203. package/docs/reports/unified-9.0.21/raw/ems/ui-security-inventory-before.json +28991 -0
  204. package/docs/reports/unified-9.0.21/raw/ems/update-ui-reviewed-findings.cjs +59 -0
  205. package/docs/reports/unified-9.0.21/raw/frontend-build.log +152 -0
  206. package/docs/reports/unified-9.0.21/raw/frontend-build.result.json +14 -0
  207. package/docs/reports/unified-9.0.21/raw/frontend-installer-sbom.json +32 -0
  208. package/docs/reports/unified-9.0.21/raw/history/baseline920-influx-sequence-node24.log +12 -0
  209. package/docs/reports/unified-9.0.21/raw/history/baseline920-outage-node24.log +64 -0
  210. package/docs/reports/unified-9.0.21/raw/history/cra-tariff-source-node22.log +38 -0
  211. package/docs/reports/unified-9.0.21/raw/history/cra-tariff-source-node24.log +36 -0
  212. package/docs/reports/unified-9.0.21/raw/history/lint-baseline-comparison.json +83 -0
  213. package/docs/reports/unified-9.0.21/raw/history/lint-scope.cjs +29 -0
  214. package/docs/reports/unified-9.0.21/raw/history/regression-node22.log +438 -0
  215. package/docs/reports/unified-9.0.21/raw/history/regression-node24.log +75 -0
  216. package/docs/reports/unified-9.0.21/raw/history/results-node22.json +37 -0
  217. package/docs/reports/unified-9.0.21/raw/history/results-node24.json +66 -0
  218. package/docs/reports/unified-9.0.21/raw/history/run-checks.py +18 -0
  219. package/docs/reports/unified-9.0.21/raw/history/source-evidence.json +83 -0
  220. package/docs/reports/unified-9.0.21/raw/installer-build.log +26 -0
  221. package/docs/reports/unified-9.0.21/raw/installer-build.result.json +14 -0
  222. package/docs/reports/unified-9.0.21/raw/keygen-source.json +6 -0
  223. package/docs/reports/unified-9.0.21/raw/lint-final.log +16 -0
  224. package/docs/reports/unified-9.0.21/raw/lint-final.result.json +14 -0
  225. package/docs/reports/unified-9.0.21/raw/modules-build.log +5 -0
  226. package/docs/reports/unified-9.0.21/raw/modules-build.result.json +14 -0
  227. package/docs/reports/unified-9.0.21/raw/node22-tests-final.log +13274 -0
  228. package/docs/reports/unified-9.0.21/raw/node22-tests-final.result.json +13 -0
  229. package/docs/reports/unified-9.0.21/raw/node22-typecheck-final.log +7 -0
  230. package/docs/reports/unified-9.0.21/raw/node22-typecheck-final.result.json +14 -0
  231. package/docs/reports/unified-9.0.21/raw/node22-version.log +1 -0
  232. package/docs/reports/unified-9.0.21/raw/node24-tests-final.log +2223 -0
  233. package/docs/reports/unified-9.0.21/raw/node24-tests-final.result.json +13 -0
  234. package/docs/reports/unified-9.0.21/raw/node24-typecheck-final.log +5 -0
  235. package/docs/reports/unified-9.0.21/raw/node24-typecheck-final.result.json +14 -0
  236. package/docs/reports/unified-9.0.21/raw/node24-version.log +1 -0
  237. package/docs/reports/unified-9.0.21/raw/persistence/920-http-draft-revision-node24.log +50 -0
  238. package/docs/reports/unified-9.0.21/raw/persistence/920-late-commit-overwrite-node24.log +30 -0
  239. package/docs/reports/unified-9.0.21/raw/persistence/920-save-lifecycle-node24.log +59 -0
  240. package/docs/reports/unified-9.0.21/raw/persistence/921-backend-types.log +0 -0
  241. package/docs/reports/unified-9.0.21/raw/persistence/921-editor-lint.log +0 -0
  242. package/docs/reports/unified-9.0.21/raw/persistence/921-eebus-editor-typecheck.log +0 -0
  243. package/docs/reports/unified-9.0.21/raw/persistence/921-final-format-review.json +24 -0
  244. package/docs/reports/unified-9.0.21/raw/persistence/921-lint.log +0 -0
  245. package/docs/reports/unified-9.0.21/raw/persistence/921-new-update-http-before.log +177 -0
  246. package/docs/reports/unified-9.0.21/raw/persistence/921-new-update-snapshot-before.log +80 -0
  247. package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node22.log +1019 -0
  248. package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node22.receipt.json +28 -0
  249. package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node24.log +174 -0
  250. package/docs/reports/unified-9.0.21/raw/persistence/921-persistence-final-node24.receipt.json +28 -0
  251. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-eslint-final.log +0 -0
  252. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node22.log +137 -0
  253. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node22.receipt.json +21 -0
  254. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node24.log +30 -0
  255. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-final-node24.receipt.json +21 -0
  256. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-strict-typecheck.log +0 -0
  257. package/docs/reports/unified-9.0.21/raw/persistence/921-update-helpers-typecheck-final.log +0 -0
  258. package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-after.log +3 -0
  259. package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-before-observation.json +25 -0
  260. package/docs/reports/unified-9.0.21/raw/persistence/http-slowbody-repro.cjs +7 -0
  261. package/docs/reports/unified-9.0.21/raw/persistence/source-files.pre-final-format.sha256 +14 -0
  262. package/docs/reports/unified-9.0.21/raw/persistence/source-files.sha256 +14 -0
  263. package/docs/reports/unified-9.0.21/raw/release-overlay/obsolete-assets-920-added.json +94 -0
  264. package/docs/reports/unified-9.0.21/raw/release-overlay/publish-catalog-regression.log +49 -0
  265. package/docs/reports/unified-9.0.21/raw/release-overlay/publish-catalog-regression.result.json +15 -0
  266. package/docs/reports/unified-9.0.21/raw/sbom-runtime.log +7 -0
  267. package/docs/reports/unified-9.0.21/raw/sbom-runtime.result.json +14 -0
  268. package/docs/reports/unified-9.0.21/raw/sbom-vendor-check.log +1 -0
  269. package/docs/reports/unified-9.0.21/raw/sbom-vendor-check.result.json +14 -0
  270. package/docs/reports/unified-9.0.21/raw/security-stability/backend-typecheck.log +0 -0
  271. package/docs/reports/unified-9.0.21/raw/security-stability/boundaries-node22.tap +495 -0
  272. package/docs/reports/unified-9.0.21/raw/security-stability/boundaries-node24.tap +88 -0
  273. package/docs/reports/unified-9.0.21/raw/security-stability/coexistence-node22.tap +179 -0
  274. package/docs/reports/unified-9.0.21/raw/security-stability/coexistence-node24.tap +36 -0
  275. package/docs/reports/unified-9.0.21/raw/security-stability/results.json +118 -0
  276. package/docs/reports/unified-9.0.21/raw/security-stability/upload-admission-before-node22.tap +63 -0
  277. package/docs/reports/unified-9.0.21/raw/security-stability/upload-admission-before-node24.tap +47 -0
  278. package/docs/reports/unified-9.0.21/raw/security-stability/upload-lint.log +0 -0
  279. package/docs/reports/unified-9.0.21/raw/security-stability/upload-node22.tap +148 -0
  280. package/docs/reports/unified-9.0.21/raw/security-stability/upload-node24.tap +30 -0
  281. package/docs/reports/unified-9.0.21/raw/ui-docs-check.log +6 -0
  282. package/docs/reports/unified-9.0.21/raw/ui-docs-check.result.json +14 -0
  283. package/docs/reports/unified-9.0.21/raw/ui-runtime-final.log +7 -0
  284. package/docs/reports/unified-9.0.21/raw/ui-runtime-final.result.json +14 -0
  285. package/docs/reports/unified-9.0.21/raw/ui-runtime-sync.log +1 -0
  286. package/docs/reports/unified-9.0.21/raw/ui-runtime-sync.result.json +14 -0
  287. package/docs/reports/unified-9.0.21/raw/ui-sbom-check.log +6 -0
  288. package/docs/reports/unified-9.0.21/raw/ui-sbom-check.result.json +14 -0
  289. package/docs/reports/unified-9.0.21/raw/ui-sbom-final.log +6 -0
  290. package/docs/reports/unified-9.0.21/raw/ui-sbom-final.result.json +14 -0
  291. package/docs/reports/unified-9.0.21/raw/ui-secret-final.log +6 -0
  292. package/docs/reports/unified-9.0.21/raw/ui-secret-final.result.json +14 -0
  293. package/docs/reports/unified-9.0.21/raw/ui-security-final.log +8 -0
  294. package/docs/reports/unified-9.0.21/raw/ui-security-final.result.json +14 -0
  295. package/docs/reports/unified-9.0.21/raw/update-ui/baseline-ui.log +280 -0
  296. package/docs/reports/unified-9.0.21/raw/update-ui/browser-preview.test.cjs +170 -0
  297. package/docs/reports/unified-9.0.21/raw/update-ui/draft-regression.log +214 -0
  298. package/docs/reports/unified-9.0.21/raw/update-ui/eos-updates-before.ts +171 -0
  299. package/docs/reports/unified-9.0.21/raw/update-ui/lint.log +0 -0
  300. package/docs/reports/unified-9.0.21/raw/update-ui/results.json +90 -0
  301. package/docs/reports/unified-9.0.21/raw/update-ui/source-evidence.json +30 -0
  302. package/docs/reports/unified-9.0.21/raw/update-ui/type-node22.log +0 -0
  303. package/docs/reports/unified-9.0.21/raw/update-ui/type-node24.log +0 -0
  304. package/docs/reports/unified-9.0.21/raw/update-ui/ui-node22.log +98 -0
  305. package/docs/reports/unified-9.0.21/raw/update-ui/ui-node24.log +22 -0
  306. package/docs/reports/unified-9.0.22/BACKUP_POSTGRES_FOLLOWUP.md +44 -0
  307. package/docs/reports/unified-9.0.22/ENERGIEFLUSS_BROWSERPRUEFUNG.md +40 -0
  308. package/docs/reports/unified-9.0.22/ENERGY_FLOW_BACKEND.md +44 -0
  309. package/docs/reports/unified-9.0.22/FLOW_TARIFF_INDEPENDENT_REVIEW.md +33 -0
  310. package/docs/reports/unified-9.0.22/OCPP_STOP_WRITER_REVIEW.md +27 -0
  311. package/docs/reports/unified-9.0.22/POSTGRESQL_SYSTEM_SETUP.md +34 -0
  312. package/docs/reports/unified-9.0.22/PRUEFBERICHT.md +85 -0
  313. package/docs/reports/unified-9.0.22/flow/PRUEFVERMERK.md +42 -0
  314. package/docs/reports/unified-9.0.22/flow/frontend-cadence-tests.log +37 -0
  315. package/docs/reports/unified-9.0.22/flow/frontend-source-hashes.json +13 -0
  316. package/docs/reports/unified-9.0.22/flow/frontend-tests.log +31 -0
  317. package/docs/reports/unified-9.0.22/postgres-history-review.md +43 -0
  318. package/docs/reports/unified-9.0.22/postgres-real-review.tap +21 -0
  319. package/docs/reports/unified-9.0.22/postgres-review-lint.log +0 -0
  320. package/docs/reports/unified-9.0.22/postgres-review-typecheck.log +0 -0
  321. package/docs/reports/unified-9.0.22/postgres-review-unit-api.tap +25 -0
  322. package/docs/reports/unified-9.0.22/raw/INDEX.json +43 -0
  323. package/docs/reports/unified-9.0.22/raw/backup-followup/eslint-backup.log +0 -0
  324. package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-after.tap +13 -0
  325. package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-before.tap +54 -0
  326. package/docs/reports/unified-9.0.22/raw/backup-followup/evcs-stop-writer-test-eslint.log +0 -0
  327. package/docs/reports/unified-9.0.22/raw/backup-followup/influx-real-node24.tap +11 -0
  328. package/docs/reports/unified-9.0.22/raw/backup-followup/scope-hashes.json +51 -0
  329. package/docs/reports/unified-9.0.22/raw/backup-followup/storage-nullable-before.tap +96 -0
  330. package/docs/reports/unified-9.0.22/raw/backup-followup/storage-nullable-flow.tap +12 -0
  331. package/docs/reports/unified-9.0.22/raw/backup-followup/tests-node24.tap +116 -0
  332. package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-backup-scope.log +0 -0
  333. package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-backup.log +0 -0
  334. package/docs/reports/unified-9.0.22/raw/backup-followup/typecheck-postgres-setup.log +0 -0
  335. package/docs/reports/unified-9.0.22/raw/current/admin-build.log +152 -0
  336. package/docs/reports/unified-9.0.22/raw/current/availability-final.log +1 -0
  337. package/docs/reports/unified-9.0.22/raw/current/backend-build.log +5 -0
  338. package/docs/reports/unified-9.0.22/raw/current/baseline-repairs.log +60 -0
  339. package/docs/reports/unified-9.0.22/raw/current/baseline-unified.log +1675 -0
  340. package/docs/reports/unified-9.0.22/raw/current/combined-fixes.log +65 -0
  341. package/docs/reports/unified-9.0.22/raw/current/control-final.log +25 -0
  342. package/docs/reports/unified-9.0.22/raw/current/energyflow-browser.json +244 -0
  343. package/docs/reports/unified-9.0.22/raw/current/energyflow-browser.stderr +0 -0
  344. package/docs/reports/unified-9.0.22/raw/current/energyflow-cadence-browser.json +63 -0
  345. package/docs/reports/unified-9.0.22/raw/current/energyflow-cadence-browser.stderr +0 -0
  346. package/docs/reports/unified-9.0.22/raw/current/lint-final.log +5 -0
  347. package/docs/reports/unified-9.0.22/raw/current/lint.log +5 -0
  348. package/docs/reports/unified-9.0.22/raw/current/markdown-build.log +1 -0
  349. package/docs/reports/unified-9.0.22/raw/current/modules-build.log +5 -0
  350. package/docs/reports/unified-9.0.22/raw/current/pre-ocpp-full.log +2337 -0
  351. package/docs/reports/unified-9.0.22/raw/current/production-audit.json +22 -0
  352. package/docs/reports/unified-9.0.22/raw/current/production-audit.stderr +1 -0
  353. package/docs/reports/unified-9.0.22/raw/current/runtime-build-final.log +8 -0
  354. package/docs/reports/unified-9.0.22/raw/current/runtime-build.log +32 -0
  355. package/docs/reports/unified-9.0.22/raw/current/runtime-sync.log +1 -0
  356. package/docs/reports/unified-9.0.22/raw/current/safety-envelope-final.log +1 -0
  357. package/docs/reports/unified-9.0.22/raw/current/sbom-lock-graph.log +1 -0
  358. package/docs/reports/unified-9.0.22/raw/current/sbom.log +6120 -0
  359. package/docs/reports/unified-9.0.22/raw/current/station-permission-final.log +1 -0
  360. package/docs/reports/unified-9.0.22/raw/current/storage-feedforward-final.log +1 -0
  361. package/docs/reports/unified-9.0.22/raw/current/typecheck-final.log +5 -0
  362. package/docs/reports/unified-9.0.22/raw/current/typecheck.log +5 -0
  363. package/docs/reports/unified-9.0.22/raw/ems-control-points/eslint.txt +0 -0
  364. package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-availability.txt +1 -0
  365. package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-safety.txt +1 -0
  366. package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-station.txt +1 -0
  367. package/docs/reports/unified-9.0.22/raw/ems-control-points/node22-tests.tap +124 -0
  368. package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-availability.txt +1 -0
  369. package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-safety.txt +1 -0
  370. package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-station.txt +1 -0
  371. package/docs/reports/unified-9.0.22/raw/ems-control-points/node24-tests.tap +26 -0
  372. package/docs/reports/unified-9.0.22/raw/ems-control-points/typecheck.txt +0 -0
  373. package/docs/reports/unified-9.0.22/raw/flow-backend/core-pv-node22.tap +30 -0
  374. package/docs/reports/unified-9.0.22/raw/flow-backend/core-pv-node24.tap +11 -0
  375. package/docs/reports/unified-9.0.22/raw/flow-backend/environment.json +7 -0
  376. package/docs/reports/unified-9.0.22/raw/flow-backend/lint.log +0 -0
  377. package/docs/reports/unified-9.0.22/raw/flow-backend/node22.tap +164 -0
  378. package/docs/reports/unified-9.0.22/raw/flow-backend/node24.tap +33 -0
  379. package/docs/reports/unified-9.0.22/raw/flow-backend/typecheck.log +0 -0
  380. package/docs/reports/unified-9.0.22/raw/history-ui/browser-runtime.json +11 -0
  381. package/docs/reports/unified-9.0.22/raw/history-ui/browser-smoke.json +49 -0
  382. package/docs/reports/unified-9.0.22/raw/history-ui/browser-smoke.stderr +0 -0
  383. package/docs/reports/unified-9.0.22/raw/history-ui/build.log +18 -0
  384. package/docs/reports/unified-9.0.22/raw/history-ui/environment.json +38 -0
  385. package/docs/reports/unified-9.0.22/raw/history-ui/lint.log +0 -0
  386. package/docs/reports/unified-9.0.22/raw/history-ui/node22.tap +144 -0
  387. package/docs/reports/unified-9.0.22/raw/history-ui/node24.tap +30 -0
  388. package/docs/reports/unified-9.0.22/raw/node22-tests-final.log +14086 -0
  389. package/docs/reports/unified-9.0.22/raw/node22-version.log +1 -0
  390. package/docs/reports/unified-9.0.22/raw/node24-tests-final.log +2356 -0
  391. package/docs/reports/unified-9.0.22/raw/node24-version.log +1 -0
  392. package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-eslint.log +0 -0
  393. package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-node22.tap +72 -0
  394. package/docs/reports/unified-9.0.22/raw/postgresql-system/setup-node24.tap +70 -0
  395. package/docs/reports/unified-9.0.22/raw/postgresql-system/status-eslint.log +0 -0
  396. package/docs/reports/unified-9.0.22/raw/postgresql-system/typecheck.log +0 -0
  397. package/docs/reports/unified-9.0.23/MODULE_PROCESS_IMPLEMENTATION.md +43 -0
  398. package/docs/reports/unified-9.0.23/OCPP_0.4.3_ERGEBNIS.json +24 -0
  399. package/docs/reports/unified-9.0.23/OCPP_0.4.3_PRUEFBERICHT.md +50 -0
  400. package/docs/reports/unified-9.0.23/OCPP_AUTOMATISCHE_ZUORDNUNG.md +49 -0
  401. package/docs/reports/unified-9.0.23/OCPP_CM_INTEGRATION.md +31 -0
  402. package/docs/reports/unified-9.0.23/PROZESSDIAGNOSE.md +35 -0
  403. package/docs/reports/unified-9.0.23/PRUEFBERICHT.md +75 -0
  404. package/docs/reports/unified-9.0.23/UI_EMS_PROZESSGRENZE.md +36 -0
  405. package/docs/reports/unified-9.0.23/UI_PROCESS_INDEPENDENT_FOLLOWUP.md +33 -0
  406. package/docs/reports/unified-9.0.23/module-process-contract-review-node22.tap +86 -0
  407. package/docs/reports/unified-9.0.23/module-process-contract-review-node24.tap +20 -0
  408. package/docs/reports/unified-9.0.23/module-process-contract-review.md +39 -0
  409. package/docs/reports/unified-9.0.23/module-process-contract-review.tap +20 -0
  410. package/docs/reports/unified-9.0.23/module-process-final.tap +27 -0
  411. package/docs/reports/unified-9.0.23/module-process-static.json +57 -0
  412. package/docs/reports/unified-9.0.23/raw/INDEX.json +43 -0
  413. package/docs/reports/unified-9.0.23/raw/build-backend-final.log +5 -0
  414. package/docs/reports/unified-9.0.23/raw/build-frontend.log +152 -0
  415. package/docs/reports/unified-9.0.23/raw/build-installer.log +26 -0
  416. package/docs/reports/unified-9.0.23/raw/build-ui-final.log +7 -0
  417. package/docs/reports/unified-9.0.23/raw/current/evcs-stop-writer-ocpp043.txt +20 -0
  418. package/docs/reports/unified-9.0.23/raw/current/ocpp-runtime-feedback-lint.txt +1 -0
  419. package/docs/reports/unified-9.0.23/raw/current/ocpp-runtime-feedback-tests.txt +28 -0
  420. package/docs/reports/unified-9.0.23/raw/current/runtime-health-browser.json +49 -0
  421. package/docs/reports/unified-9.0.23/raw/current/runtime-health-browser.stderr.txt +0 -0
  422. package/docs/reports/unified-9.0.23/raw/current/runtime-health-lint.txt +1 -0
  423. package/docs/reports/unified-9.0.23/raw/current/runtime-health-tests.txt +27 -0
  424. package/docs/reports/unified-9.0.23/raw/current/runtime-health-types.txt +1 -0
  425. package/docs/reports/unified-9.0.23/raw/eos-production-audit.json +22 -0
  426. package/docs/reports/unified-9.0.23/raw/idle-pwa-node22.log +75 -0
  427. package/docs/reports/unified-9.0.23/raw/idle-pwa-node24.log +22 -0
  428. package/docs/reports/unified-9.0.23/raw/lint-final.log +5 -0
  429. package/docs/reports/unified-9.0.23/raw/node22-tests-final.log +14612 -0
  430. package/docs/reports/unified-9.0.23/raw/node22-version.log +1 -0
  431. package/docs/reports/unified-9.0.23/raw/node24-tests-final.log +2443 -0
  432. package/docs/reports/unified-9.0.23/raw/node24-version.log +1 -0
  433. package/docs/reports/unified-9.0.23/raw/ocpp-auto-discovery.log +21 -0
  434. package/docs/reports/unified-9.0.23/raw/ocpp-discovery-browser.json +55 -0
  435. package/docs/reports/unified-9.0.23/raw/ocpp-discovery-lifecycle-regression.log +48 -0
  436. package/docs/reports/unified-9.0.23/raw/ocpp-production-audit.json +69 -0
  437. package/docs/reports/unified-9.0.23/raw/typecheck-final.log +5 -0
  438. package/docs/reports/unified-9.0.23/raw/ui-process/discovery-review.tap +21 -0
  439. package/docs/reports/unified-9.0.23/raw/ui-process/lint.log +0 -0
  440. package/docs/reports/unified-9.0.23/raw/ui-process/node22.tap +118 -0
  441. package/docs/reports/unified-9.0.23/raw/ui-process/node24.tap +112 -0
  442. package/docs/reports/unified-9.0.23/raw/ui-process/root-typecheck.log +0 -0
  443. package/docs/reports/unified-9.0.23/raw/ui-process/typecheck.log +0 -0
  444. package/docs/reports/unified-9.0.23/raw/ui-process/unified-listen-build-node24.tap +196 -0
  445. package/docs/reports/unified-9.0.23/raw/ui-process/unified-listen-node22.tap +200 -0
  446. package/docs/reports/unified-9.0.23/raw/ui-process/web-lint.log +0 -0
  447. package/docs/reports/unified-9.0.23/raw/ui-process/web-pipeline-node22.tap +92 -0
  448. package/docs/reports/unified-9.0.23/raw/ui-process/web-pipeline-node24.tap +90 -0
  449. package/docs/reports/unified-9.0.23/ui-process-contract-review.md +30 -0
  450. package/docs/reports/unified-9.0.23/ui-process-final-review-node22.tap +50 -0
  451. package/docs/reports/unified-9.0.23/ui-process-final-review-node24.tap +14 -0
  452. package/docs/reports/unified-9.0.23/ui-process-followup-hashes.json +13 -0
  453. package/docs/reports/unified-9.0.23/ui-process-operational-review-node22.tap +30 -0
  454. package/docs/reports/unified-9.0.23/ui-process-operational-review-node24.tap +11 -0
  455. package/docs/reports/unified-9.0.23/ui-process-review-node22.tap +48 -0
  456. package/docs/reports/unified-9.0.23/ui-process-review-node24.tap +46 -0
  457. package/docs/reports/unified-9.0.24/BACKUP_INTEROP_PRUEFBERICHT.md +48 -0
  458. package/docs/reports/unified-9.0.24/KIOSK_FRONTEND_BROWSERPRUEFUNG.md +49 -0
  459. package/docs/reports/unified-9.0.24/KIOSK_UNABHAENGIGER_REVIEW.md +21 -0
  460. package/docs/reports/unified-9.0.24/OCPP_HOST_MIGRATION.md +41 -0
  461. package/docs/reports/unified-9.0.24/OCPP_NAMESPACE_REGELPFAD.md +55 -0
  462. package/docs/reports/unified-9.0.24/OCPP_UNABHAENGIGER_REVIEW.md +37 -0
  463. package/docs/reports/unified-9.0.24/OCPP_VERWALTUNG.md +33 -0
  464. package/docs/reports/unified-9.0.24/PRUEFBERICHT.md +54 -0
  465. package/docs/reports/unified-9.0.24/PUBLISH_OVERLAY_9_0_21.md +23 -0
  466. package/docs/reports/unified-9.0.24/raw/INDEX.json +43 -0
  467. package/docs/reports/unified-9.0.24/raw/backup-interop/ems-independence-node24.tap +9 -0
  468. package/docs/reports/unified-9.0.24/raw/backup-interop/final-node22.tap +175 -0
  469. package/docs/reports/unified-9.0.24/raw/backup-interop/final-node24.tap +35 -0
  470. package/docs/reports/unified-9.0.24/raw/backup-interop/focused-node22.tap +132 -0
  471. package/docs/reports/unified-9.0.24/raw/backup-interop/focused-node24.tap +27 -0
  472. package/docs/reports/unified-9.0.24/raw/backup-interop/kiosk-review-node24.tap +13 -0
  473. package/docs/reports/unified-9.0.24/raw/backup-interop/kiosk-update-snapshot-node24.tap +22 -0
  474. package/docs/reports/unified-9.0.24/raw/backup-interop/lint-source.txt +0 -0
  475. package/docs/reports/unified-9.0.24/raw/backup-interop/lint-tests.txt +0 -0
  476. package/docs/reports/unified-9.0.24/raw/backup-interop/ocpp-backup-node24.tap +10 -0
  477. package/docs/reports/unified-9.0.24/raw/backup-interop/own-source-hashes.json +12 -0
  478. package/docs/reports/unified-9.0.24/raw/backup-interop/types.txt +0 -0
  479. package/docs/reports/unified-9.0.24/raw/backup-interop/update-snapshot-node24.tap +20 -0
  480. package/docs/reports/unified-9.0.24/raw/build.log +200 -0
  481. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser-node22.json +69 -0
  482. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser-node22.stderr.txt +3 -0
  483. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser.json +69 -0
  484. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-browser.stderr.txt +2 -0
  485. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-http-node22.txt +253 -0
  486. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-http-node24.txt +52 -0
  487. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-lint.txt +0 -0
  488. package/docs/reports/unified-9.0.24/raw/current/ocpp-admin-types.txt +0 -0
  489. package/docs/reports/unified-9.0.24/raw/current/ocpp-lease-registration-before.txt +28 -0
  490. package/docs/reports/unified-9.0.24/raw/current/ocpp-namespace-independent-node22.txt +302 -0
  491. package/docs/reports/unified-9.0.24/raw/current/ocpp-namespace-independent-node24.txt +55 -0
  492. package/docs/reports/unified-9.0.24/raw/current/ocpp-native-generic-before.txt +25 -0
  493. package/docs/reports/unified-9.0.24/raw/current/runtime-health-browser.json +49 -0
  494. package/docs/reports/unified-9.0.24/raw/current/runtime-health-browser.stderr.txt +0 -0
  495. package/docs/reports/unified-9.0.24/raw/current/runtime-health-types.txt +0 -0
  496. package/docs/reports/unified-9.0.24/raw/eos-production-audit.json +77 -0
  497. package/docs/reports/unified-9.0.24/raw/kiosk-auth-profiles-node22.log +16 -0
  498. package/docs/reports/unified-9.0.24/raw/kiosk-auth-profiles-node24.log +14 -0
  499. package/docs/reports/unified-9.0.24/raw/kiosk-browser-node22.json +57 -0
  500. package/docs/reports/unified-9.0.24/raw/kiosk-browser-node24.json +57 -0
  501. package/docs/reports/unified-9.0.24/raw/kiosk-idle-node22.log +215 -0
  502. package/docs/reports/unified-9.0.24/raw/kiosk-idle-node24.log +42 -0
  503. package/docs/reports/unified-9.0.24/raw/lint.log +45 -0
  504. package/docs/reports/unified-9.0.24/raw/node22-tests-final.log +15517 -0
  505. package/docs/reports/unified-9.0.24/raw/node22-version.log +1 -0
  506. package/docs/reports/unified-9.0.24/raw/node24-tests-final.log +2595 -0
  507. package/docs/reports/unified-9.0.24/raw/node24-version.log +1 -0
  508. package/docs/reports/unified-9.0.24/raw/ocpp-host-node22.tap +105 -0
  509. package/docs/reports/unified-9.0.24/raw/ocpp-host-node24.tap +24 -0
  510. package/docs/reports/unified-9.0.24/raw/ocpp-host-regression-node22.tap +818 -0
  511. package/docs/reports/unified-9.0.24/raw/ocpp-host-regression-node24.tap +140 -0
  512. package/docs/reports/unified-9.0.24/raw/ocpp-hosted-mapping-browser.log +2 -0
  513. package/docs/reports/unified-9.0.24/raw/ocpp-legacy-mapping-browser.log +2 -0
  514. package/docs/reports/unified-9.0.24/raw/ocpp-namespace-control.log +49 -0
  515. package/docs/reports/unified-9.0.24/raw/publish-overlay-node22.tap +278 -0
  516. package/docs/reports/unified-9.0.24/raw/publish-overlay-node24.tap +52 -0
  517. package/docs/reports/unified-9.0.24/raw/publish-overlay-provenance-922-923.json +32 -0
  518. package/docs/reports/unified-9.0.24/raw/publish-overlay-provenance.json +19 -0
  519. package/docs/reports/unified-9.0.24/raw/typecheck.log +5 -0
  520. package/docs/reports/unified-9.0.25/MIGRATION_INDEPENDENT_REVIEW.md +74 -0
  521. package/docs/reports/unified-9.0.25/OCPP_STARTSPERRE_9.0.24.md +60 -0
  522. package/docs/reports/unified-9.0.25/PRUEFBERICHT.md +78 -0
  523. package/docs/reports/unified-9.0.25/RUNTIME_CONTROLS_BROWSERPRUEFUNG.md +81 -0
  524. package/docs/reports/unified-9.0.25/RUNTIME_CONTROL_BACKEND.md +58 -0
  525. package/docs/reports/unified-9.0.25/RUNTIME_CONTROL_INDEPENDENT_REVIEW.md +66 -0
  526. package/docs/reports/unified-9.0.25/RUNTIME_LOGIN_RECOVERY.md +32 -0
  527. package/docs/reports/unified-9.0.25/TARIFF_UPDATE_PERSISTENCE.md +50 -0
  528. package/docs/reports/unified-9.0.25/UI_CONFIG_COMMIT_ACK.md +51 -0
  529. package/docs/reports/unified-9.0.25/raw/BUILD_CHECKS.json +49 -0
  530. package/docs/reports/unified-9.0.25/raw/INDEX.json +43 -0
  531. package/docs/reports/unified-9.0.25/raw/SBOM_GENERATION.json +42 -0
  532. package/docs/reports/unified-9.0.25/raw/build-backend.log +5 -0
  533. package/docs/reports/unified-9.0.25/raw/build-frontend.log +152 -0
  534. package/docs/reports/unified-9.0.25/raw/build-installer.log +26 -0
  535. package/docs/reports/unified-9.0.25/raw/build-modules.log +5 -0
  536. package/docs/reports/unified-9.0.25/raw/build-ui-runtime.log +7 -0
  537. package/docs/reports/unified-9.0.25/raw/eos-production-audit.json +77 -0
  538. package/docs/reports/unified-9.0.25/raw/eos-production-audit.stderr +1 -0
  539. package/docs/reports/unified-9.0.25/raw/frontend-sbom.stderr +1 -0
  540. package/docs/reports/unified-9.0.25/raw/installer-sbom.stderr +1 -0
  541. package/docs/reports/unified-9.0.25/raw/lint.log +45 -0
  542. package/docs/reports/unified-9.0.25/raw/node22-tests-final.log +15879 -0
  543. package/docs/reports/unified-9.0.25/raw/node22-version.log +1 -0
  544. package/docs/reports/unified-9.0.25/raw/node24-tests-final.log +2653 -0
  545. package/docs/reports/unified-9.0.25/raw/node24-version.log +1 -0
  546. package/docs/reports/unified-9.0.25/raw/runtime-control-backend/runtime-control-backend-node22-final.tap +236 -0
  547. package/docs/reports/unified-9.0.25/raw/runtime-control-backend/runtime-control-backend-node24-final.tap +44 -0
  548. package/docs/reports/unified-9.0.25/raw/runtime-control-backend/source-sha256.json +19 -0
  549. package/docs/reports/unified-9.0.25/raw/runtime-controls/controls-node22.json +70 -0
  550. package/docs/reports/unified-9.0.25/raw/runtime-controls/controls-node24.json +70 -0
  551. package/docs/reports/unified-9.0.25/raw/runtime-controls/health-node22.json +49 -0
  552. package/docs/reports/unified-9.0.25/raw/runtime-controls/health-node24.json +49 -0
  553. package/docs/reports/unified-9.0.25/raw/runtime-controls/login-contract-node22.log +15 -0
  554. package/docs/reports/unified-9.0.25/raw/runtime-controls/login-contract-node24.log +15 -0
  555. package/docs/reports/unified-9.0.25/raw/runtime-controls/login-node22.json +32 -0
  556. package/docs/reports/unified-9.0.25/raw/runtime-controls/login-node24.json +32 -0
  557. package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/node22.log +28 -0
  558. package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/node24.log +10 -0
  559. package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/route-regression-node24.log +28 -0
  560. package/docs/reports/unified-9.0.25/raw/runtime-login-recovery/source-sha256.json +6 -0
  561. package/docs/reports/unified-9.0.25/raw/runtime-processes/README.md +41 -0
  562. package/docs/reports/unified-9.0.25/raw/runtime-processes/runtime-control-processes-node22.tap +44 -0
  563. package/docs/reports/unified-9.0.25/raw/runtime-processes/runtime-control-processes-node24.tap +13 -0
  564. package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-and-ui-review-node22.tap +232 -0
  565. package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-and-ui-review-node24.tap +43 -0
  566. package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-review-node22.tap +68 -0
  567. package/docs/reports/unified-9.0.25/raw/runtime-review/runtime-controls-review-node24.tap +17 -0
  568. package/docs/reports/unified-9.0.25/raw/sbom-lock.log +1 -0
  569. package/docs/reports/unified-9.0.25/raw/sbom-lock.stderr +1 -0
  570. package/docs/reports/unified-9.0.25/raw/tariff-update/ack-node22.tap +44 -0
  571. package/docs/reports/unified-9.0.25/raw/tariff-update/ack-node24.tap +40 -0
  572. package/docs/reports/unified-9.0.25/raw/tariff-update/ack-review-node22.tap +44 -0
  573. package/docs/reports/unified-9.0.25/raw/tariff-update/ack-review-node24.tap +13 -0
  574. package/docs/reports/unified-9.0.25/raw/tariff-update/commit-ack-sha256.txt +4 -0
  575. package/docs/reports/unified-9.0.25/raw/tariff-update/config-ack-result.json +19 -0
  576. package/docs/reports/unified-9.0.25/raw/tariff-update/generate-921-fixture.cjs +36 -0
  577. package/docs/reports/unified-9.0.25/raw/tariff-update/node22.tap +68 -0
  578. package/docs/reports/unified-9.0.25/raw/tariff-update/node24.tap +64 -0
  579. package/docs/reports/unified-9.0.25/raw/tariff-update/reproduce-config-ack.cjs +55 -0
  580. package/docs/reports/unified-9.0.25/raw/tariff-update/reviewed-sha256.txt +4 -0
  581. package/docs/reports/unified-9.0.25/raw/typecheck.log +5 -0
  582. package/docs/unified/EMS_BEDIEN_DATENPUNKTE_9_0_22.md +51 -0
  583. package/docs/unified/HISTORY_UI_9_0_22.md +75 -0
  584. package/docs/unified/POSTGRESQL_9_0_22.md +89 -0
  585. package/io-package.json +20 -22
  586. package/modules/backup/README.md +10 -0
  587. package/modules/backup/RECOVERY-9.0.22.md +59 -0
  588. package/modules/backup/admin/index.html +2 -1
  589. package/modules/backup/admin/index.js +17 -1
  590. package/modules/backup/build/config.js +2 -0
  591. package/modules/backup/build/coverage.js +64 -0
  592. package/modules/backup/build/creators.js +22 -17
  593. package/modules/backup/build/databaseTargets.js +42 -0
  594. package/modules/backup/build/index.js +47 -4
  595. package/modules/backup/build/influxIntegrity.js +159 -0
  596. package/modules/backup/build/postgresHistory.js +91 -0
  597. package/modules/backup/build/preflight.js +3 -8
  598. package/modules/backup/build/publicTrust.js +46 -0
  599. package/modules/backup/build/restore-cli.js +72 -1
  600. package/modules/backup/build/storageRetention.js +26 -0
  601. package/modules/backup/build/worker.js +18 -1
  602. package/modules/backup/src/config.ts +2 -0
  603. package/modules/backup/src/coverage.ts +50 -0
  604. package/modules/backup/src/creators.ts +20 -17
  605. package/modules/backup/src/databaseTargets.ts +45 -0
  606. package/modules/backup/src/index.ts +37 -4
  607. package/modules/backup/src/influxIntegrity.ts +125 -0
  608. package/modules/backup/src/postgresHistory.ts +66 -0
  609. package/modules/backup/src/preflight.ts +3 -10
  610. package/modules/backup/src/publicTrust.ts +34 -0
  611. package/modules/backup/src/restore-cli.ts +55 -4
  612. package/modules/backup/src/storageRetention.ts +20 -0
  613. package/modules/backup/src/types.ts +5 -0
  614. package/modules/backup/src/worker.ts +18 -2
  615. package/modules/backup/test/completeness.test.cjs +193 -0
  616. package/modules/backup/test/hosted.test.cjs +43 -3
  617. package/modules/backup/test/influx-real.test.cjs +75 -0
  618. package/modules/backup/test/lifecycle.test.cjs +7 -5
  619. package/modules/backup/test/ocpp-coverage.test.cjs +152 -0
  620. package/modules/devices/admin/index.html +1 -1
  621. package/modules/eebus/admin/index.html +1 -1
  622. package/modules/ocpp/LICENSE +21 -0
  623. package/modules/ocpp/README.md +61 -0
  624. package/modules/ocpp/admin/config-fields.json +353 -0
  625. package/modules/ocpp/admin/index.html +52 -0
  626. package/modules/ocpp/admin/index.js +228 -0
  627. package/modules/ocpp/admin/style.css +27 -0
  628. package/modules/ocpp/build/index.js +401 -0
  629. package/modules/ocpp/build/operationGuard.js +26 -0
  630. package/modules/ocpp/build/server.js +155 -0
  631. package/modules/ocpp/eslint.config.mjs +13 -0
  632. package/modules/ocpp/index.js +3 -0
  633. package/modules/ocpp/native-defaults.json +44 -0
  634. package/modules/ocpp/ocpp/common.js +646 -0
  635. package/modules/ocpp/ocpp/compact.js +332 -0
  636. package/modules/ocpp/ocpp/configuration.js +364 -0
  637. package/modules/ocpp/ocpp/eos-contract.js +149 -0
  638. package/modules/ocpp/ocpp/freshness.d.ts +10 -0
  639. package/modules/ocpp/ocpp/freshness.js +272 -0
  640. package/modules/ocpp/ocpp/schemas/NOTICE.md +17 -0
  641. package/modules/ocpp/ocpp/schemas/ocpp2_0_1_official.json +1 -0
  642. package/modules/ocpp/ocpp/schemas/ocpp2_1_official.json +1 -0
  643. package/modules/ocpp/ocpp/server.js +3 -0
  644. package/modules/ocpp/ocpp/v16.js +213 -0
  645. package/modules/ocpp/ocpp/v201.js +4 -0
  646. package/modules/ocpp/ocpp/v21.js +4 -0
  647. package/modules/ocpp/ocpp/v2base.js +255 -0
  648. package/modules/ocpp/package.json +11 -0
  649. package/modules/ocpp/provenance.json +33 -0
  650. package/modules/ocpp/runtime.d.ts +16 -0
  651. package/modules/ocpp/runtime.js +3391 -0
  652. package/modules/ocpp/src/index.ts +463 -0
  653. package/modules/ocpp/src/operationGuard.ts +29 -0
  654. package/modules/ocpp/src/server.ts +193 -0
  655. package/modules/ocpp/test/configuration-runtime.test.js +786 -0
  656. package/modules/ocpp/test/core.test.js +772 -0
  657. package/modules/ocpp/test/eos-contract.test.js +67 -0
  658. package/modules/ocpp/test/hosted.test.cjs +165 -0
  659. package/modules/ocpp/tsconfig.json +7 -0
  660. package/modules/ocpp/validation/manifest.json +36 -0
  661. package/modules/ocpp/validation/node22-tests.log +525 -0
  662. package/modules/ocpp/validation/node24-tests.log +92 -0
  663. package/package.json +29 -11
  664. package/public/eos-migration/index.html +1 -1
  665. package/public/eos-migration/index.js +2 -2
  666. package/public/eos-runtime/index.html +36 -0
  667. package/public/eos-runtime/index.js +249 -0
  668. package/public/eos-runtime/style.css +27 -0
  669. package/release-manifests/unified/build-environment.cdx.json +767 -131
  670. package/release-manifests/unified/files.json +700 -214
  671. package/release-manifests/unified/frontend.cdx.json +6 -6
  672. package/release-manifests/unified/installer.cdx.json +6 -6
  673. package/release-manifests/unified/obsolete-admin-assets.json +292 -6
  674. package/release-manifests/unified/runtime.cdx.json +871 -143
  675. package/release-manifests/unified/validation.json +15 -15
  676. package/reports/unified/ocpp-pure-pv-9.0.22/PRUEFVERMERK.md +35 -0
  677. package/reports/unified/ocpp-pure-pv-9.0.22/raw/auto-pv-phases.log +1 -0
  678. package/reports/unified/ocpp-pure-pv-9.0.22/raw/control-tests.log +11 -0
  679. package/reports/unified/ocpp-pure-pv-9.0.22/raw/ocpp-stability.log +1 -0
  680. package/reports/unified/ocpp-pure-pv-9.0.22/raw/rc60.log +1 -0
  681. package/reports/unified/tariff-energy-flow-9.0.22/PRUEFVERMERK.md +44 -0
  682. package/reports/unified/tariff-energy-flow-9.0.22/raw/focused-tests.log +37 -0
  683. package/reports/unified/tariff-energy-flow-9.0.22/raw/grid-charge-policy.log +1 -0
  684. package/reports/unified/tariff-energy-flow-9.0.22/raw/status-truth.log +1 -0
  685. package/tools/eos-release-check.cjs +5 -0
  686. package/tools/eos-release-manifest.cjs +3 -3
  687. package/tools/eos-sbom-vendored.cjs +2 -1
  688. package/tools/system/eos-postgresql-setup.cjs +409 -0
  689. package/tsconfig.eos-history-backup-scope.json +9 -0
  690. package/tsconfig.eos-postgres-system.json +15 -0
  691. package/ui/admin/react/assets/index-wHWXfD_g.js +13 -0
  692. package/ui/admin/react/index.html +1 -1
  693. package/ui/ems/consumers/evcs.js +11 -7
  694. package/ui/ems/datapoints.js +14 -5
  695. package/ui/ems/engine.js +4 -1
  696. package/ui/ems/modules/charging-management.js +193 -63
  697. package/ui/ems/modules/core-limits.js +15 -20
  698. package/ui/ems/modules/storage-control.js +8 -6
  699. package/ui/ems/modules/tarif-vis.js +7 -2
  700. package/ui/ems/modules/tariff-status.js +19 -1
  701. package/ui/eslint.postgres-history.config.mjs +9 -0
  702. package/ui/io-package.json +5 -1
  703. package/ui/lib/ems-control-values.js +64 -0
  704. package/ui/lib/flow-measurement.js +72 -0
  705. package/ui/lib/hosted-adapter.js +12 -1
  706. package/ui/lib/influx-history-runtime.js +66 -24
  707. package/ui/lib/installer-lifecycle.js +4 -2
  708. package/ui/lib/ocpp-auto-discovery.js +397 -0
  709. package/ui/lib/ocpp-limit-feedback.js +166 -0
  710. package/ui/lib/partner-runtime.js +35 -2
  711. package/ui/lib/partner-websocket.js +4 -1
  712. package/ui/lib/postgres-history-config.js +57 -0
  713. package/ui/lib/postgres-history.js +344 -0
  714. package/ui/lib/runtime-proxy-html.js +34 -1
  715. package/ui/lib/smarthome-device-controls.js +4 -1
  716. package/ui/lib/ui-access-policy.js +39 -6
  717. package/ui/main.js +392 -222
  718. package/ui/package.json +1 -1
  719. package/ui/tsconfig.postgres-history.json +4 -0
  720. package/ui/www/app.js +106 -152
  721. package/ui/www/auth.js +36 -10
  722. package/ui/www/charging-diagnostics-appcenter.js +1 -0
  723. package/ui/www/customer-tariff.js +1 -0
  724. package/ui/www/dashboard-lp-status.js +1 -0
  725. package/ui/www/dc-station-display.js +1 -0
  726. package/ui/www/ems-apps.js +48 -8
  727. package/ui/www/energy-origin-appcenter.js +1 -0
  728. package/ui/www/energy-origin-ledger-view.js +1 -0
  729. package/ui/www/eos-kiosk-settings.js +174 -0
  730. package/ui/www/eos-session-idle.js +40 -6
  731. package/ui/www/eos-updates.js +1 -0
  732. package/ui/www/index.html +2 -1
  733. package/ui/www/license.js +1 -0
  734. package/ui/www/licenses/smarthome-markdown-components.json +157 -157
  735. package/ui/www/live-display.js +4 -2
  736. package/ui/www/login.js +25 -9
  737. package/ui/www/manifest.webmanifest +3 -3
  738. package/ui/www/netoperator-appcenter.js +1 -0
  739. package/ui/www/netoperator.js +1 -0
  740. package/ui/www/operating-strategies-appcenter.js +1 -0
  741. package/ui/www/operating-strategies-rule-builder.js +1 -0
  742. package/ui/www/power-measurements.js +27 -2
  743. package/ui/www/pwa.js +1 -0
  744. package/ui/www/runtime-base.js +1 -0
  745. package/ui/www/settings.html +13 -1
  746. package/ui/www/smarthome-activation.js +1 -0
  747. package/ui/www/smarthome-alias-config.js +1 -0
  748. package/ui/www/smarthome-custom-config.js +1 -0
  749. package/ui/www/smarthome-custom-views.js +1 -0
  750. package/ui/www/smarthome-device-categories.js +1 -0
  751. package/ui/www/smarthome-device-config.js +1 -0
  752. package/ui/www/smarthome-device-controls.js +1 -0
  753. package/ui/www/smarthome-feedback.js +1 -0
  754. package/ui/www/smarthome-layout-editor.js +1 -0
  755. package/ui/www/smarthome-presentation.js +1 -0
  756. package/ui/www/smarthome-setup.js +1 -0
  757. package/ui/www/smarthome-touch.js +1 -0
  758. package/ui/www/storagefarm-dispatch.js +1 -0
  759. package/ui/www/storagefarm-summary.js +1 -0
  760. package/ui/www/tariff-display.js +62 -2
  761. package/adminWww/remoteEntry-eos-9.0.21.js +0 -12
  762. package/ui/admin/react/assets/index-BJO3q7oe.js +0 -13
@@ -0,0 +1,3391 @@
1
+ 'use strict';
2
+ // Actual 0.4.3 station runtime; explicit base injection.
3
+ function createOcppRuntime(AdapterBase) {
4
+ const { randomUUID } = require('node:crypto');
5
+ const { OcppRpcServer } = require('./ocpp/server');
6
+ const { StationTelemetry, normalizeEosLimit, shouldSendLimit } = require('./ocpp/eos-contract');
7
+ const {
8
+ sanitizeStationIdentity,
9
+ deriveConnectionHealth,
10
+ commandTimeoutMs,
11
+ isTriggerAccepted,
12
+ isTriggerUnsupported,
13
+ isTriggerRejected,
14
+ buildTriggerPayload,
15
+ isChargingState,
16
+ statusImpliesZero,
17
+ chargingStateImpliesZero,
18
+ isRealtimeMetricId,
19
+ isCounterMetricId,
20
+ isActualPowerOrCurrentId,
21
+ dataFreshForEos,
22
+ selectCachedStatesForRepublish,
23
+ takeRotatingItems,
24
+ parseDeviceModelValue,
25
+ } = require('./ocpp/freshness');
26
+ const {
27
+ compactKeyFromLegacyAggregate,
28
+ measurementCommon,
29
+ measurementDefinition,
30
+ sanitizeFlatKey,
31
+ canonicalPhase,
32
+ aggregatePhaseValues,
33
+ deterministicChargingProfileIds,
34
+ normalizeChargingLimit,
35
+ chargingLimitChanged,
36
+ } = require('./ocpp/compact');
37
+ const {
38
+ RESERVED_CONFIGURATION_KEYS,
39
+ cloneOcppReference,
40
+ canonicalConfigurationKey16,
41
+ canonicalDeviceModelKey,
42
+ configurationStateKey16,
43
+ configurationStateKey2,
44
+ inferOcpp16Value,
45
+ configurationSensitive,
46
+ redactConfigurationReport,
47
+ configurationRefreshDiagnostic,
48
+ stateRoleForConfiguration,
49
+ parseValuesList,
50
+ configurationWritable,
51
+ buildConfigurationRefreshCall,
52
+ buildConfigurationWriteCall,
53
+ interpretConfigurationRefreshResponse,
54
+ interpretConfigurationWriteResponse,
55
+ } = require('./ocpp/configuration');
56
+
57
+ class NexoWattOcppAdapter extends AdapterBase {
58
+ constructor(options) {
59
+ super({ ...options, name: 'ocpp21' });
60
+ this.server = null;
61
+ this.runtimeIndex = new Map();
62
+ this._eosLeases = new Map();
63
+ this._eosLeaseTimer = null;
64
+ this._eosLeaseWatchdogRunning = false;
65
+ this._startedAtMs = Date.now();
66
+ this._sessionPublications = new Map();
67
+ this._chargeLimitPublications = new Map(); // Serializes status writes across reconnects, not just within one socket.
68
+
69
+ // Runtime caches to avoid excessive object creation overhead
70
+ this._dpObjCache = new Set();
71
+ this._dpCounts = new Map();
72
+ this._aliasDone = new Set();
73
+ this._configurationIndex = new Map(); // relative/full state ID -> OCPP write metadata
74
+ this._configurationValueCache = new Map(); // relative state ID -> last confirmed value
75
+ this._configurationByIdentity = new Map(); // identity -> Map(stateKey, metadata)
76
+ this._rawToStateIdentity = new Map();
77
+ this._stateToRawIdentity = new Map();
78
+ this._freshStateCache = new Map(); // identity -> Map(stateId, { val, ack, category, updatedAt })
79
+ this._phaseMetricCache = new Map();
80
+ this._identityStructureReady = new Set();
81
+ this._connectorStructureReady = new Set();
82
+ this._connectorCleanupDone = new Set();
83
+ this._advancedStructureReady = new Set();
84
+ this._legacyCleanupDone = new Set();
85
+ this._legacySubfolderCleanupDone = new Set();
86
+ this._measurementAliasCleanupDone = new Set();
87
+ this._watchdogTimer = null;
88
+ this._watchdogRunning = false;
89
+ this._shuttingDown = false;
90
+
91
+ this.on('ready', this.onReady.bind(this));
92
+ this.on('unload', this.onUnload.bind(this));
93
+ this.on('stateChange', this.onStateChange.bind(this));
94
+ }
95
+
96
+ _stripNs(id) { return id.startsWith(this.namespace + '.') ? id.slice(this.namespace.length + 1) : id; }
97
+
98
+ _sanitizeSeg(seg) {
99
+ return String(seg || '')
100
+ .trim()
101
+ .replace(/[^A-Za-z0-9_\-]/g, '_')
102
+ .replace(/_+/g, '_')
103
+ .replace(/^_+|_+$/g, '')
104
+ || 'x';
105
+ }
106
+
107
+ resolveStationIdentity(rawIdentity) {
108
+ const raw = String(rawIdentity ?? '').trim();
109
+ if (this._rawToStateIdentity.has(raw)) return this._rawToStateIdentity.get(raw);
110
+ let stateId = sanitizeStationIdentity(raw);
111
+ const existingRaw = this._stateToRawIdentity.get(stateId);
112
+ if (existingRaw && existingRaw !== raw) {
113
+ let suffix = 2;
114
+ const base = stateId;
115
+ while (this._stateToRawIdentity.has(`${base}_${suffix}`)) suffix++;
116
+ stateId = `${base}_${suffix}`;
117
+ }
118
+ this._rawToStateIdentity.set(raw, stateId);
119
+ this._stateToRawIdentity.set(stateId, raw);
120
+ return stateId;
121
+ }
122
+
123
+ _identityFromStateId(id) {
124
+ const rel = this._stripNs(String(id || ''));
125
+ return rel.split('.')[0] || '';
126
+ }
127
+
128
+ _cacheFreshState(id, val, ack, category) {
129
+ if (!category || ['payload', 'health', 'control', 'dm', 'configuration'].includes(category)) return;
130
+ const rel = this._stripNs(id);
131
+ const identity = this._identityFromStateId(rel);
132
+ if (!identity) return;
133
+ if (!this._freshStateCache.has(identity)) this._freshStateCache.set(identity, new Map());
134
+ this._freshStateCache.get(identity).set(rel, { val, ack: !!ack, category, updatedAt: Date.now() });
135
+ }
136
+
137
+ async _setStateFreshAsync(id, val, ack = true, category = 'status') {
138
+ const rel = this._stripNs(id);
139
+ await this.setStateAsync(rel, { val, ack: !!ack });
140
+ this._cacheFreshState(rel, val, ack, category);
141
+ }
142
+
143
+ _metricCategoryFromId(id) {
144
+ if (isCounterMetricId(id)) return 'counter';
145
+ if (/(?:^|\.)(?:SoC|soc(?:Percent)?)(?:_|\.|$)/.test(String(id || ''))) return 'soc';
146
+ if (isRealtimeMetricId(id)) return 'realtime';
147
+ return 'status';
148
+ }
149
+
150
+ _indexClient(identity, proto, client, rawIdentity) {
151
+ const now = Date.now();
152
+ const old = this.runtimeIndex.get(identity);
153
+ if (old && old.client !== client) {
154
+ this.log.warn(`Charging station identity ${rawIdentity || identity} connected again; the newer connection replaces the old runtime session.`);
155
+ if (old.client && typeof old.client.close === 'function') {
156
+ Promise.resolve(old.client.close({ code: 1008, reason: 'Superseded by a newer connection' })).catch(() => undefined);
157
+ }
158
+ }
159
+ // Never carry realtime timestamps or phase fragments across OCPP sessions.
160
+ this._freshStateCache.delete(identity);
161
+ for (const key of [...this._phaseMetricCache.keys()]) if (key.startsWith(`${identity}|`)) this._phaseMetricCache.delete(key);
162
+ this.runtimeIndex.set(identity, {
163
+ sessionId: randomUUID(),
164
+ proto,
165
+ client,
166
+ rawIdentity: rawIdentity || identity,
167
+ connectedAt: now,
168
+ socketConnected: true,
169
+ lastMessageAt: now,
170
+ lastAction: 'Connect',
171
+ lastHeartbeatAt: 0,
172
+ lastMeterAt: 0,
173
+ lastPowerAt: 0,
174
+ lastExportPowerAt: 0,
175
+ lastCurrentAt: 0,
176
+ lastSocAt: 0,
177
+ lastStatusAt: 0,
178
+ heartbeatIntervalSec: Math.max(10, Number(this.config.heartbeatIntervalSec) || 300),
179
+ connectors: new Set(old?.connectors || []),
180
+ statuses: new Map(),
181
+ transactionActive: false,
182
+ chargingState: '',
183
+ refreshInFlight: false,
184
+ nextRefreshAt: now,
185
+ triggerSupport: { MeterValues: 'unknown', StatusNotification: 'unknown' },
186
+ triggerRetryAt: { MeterValues: 0, StatusNotification: 0 },
187
+ lastTriggerAt: 0,
188
+ lastTriggerMessage: '',
189
+ refreshSuppressedUntil: old ? Math.max(0, Number(old.refreshSuppressedUntil) || 0) : 0,
190
+ refreshSuppressedReason: old ? String(old.refreshSuppressedReason || '') : '',
191
+ refreshRelatedDisconnects: old ? Math.max(0, Number(old.refreshRelatedDisconnects) || 0) : 0,
192
+ lastRefreshAttemptAt: 0,
193
+ lastRefreshSuccessAt: 0,
194
+ lastRefreshError: '',
195
+ lastStateRepublishAt: 0,
196
+ republishCursor: 0,
197
+ refreshConnectorCursor: 0,
198
+ safeZeroAt: 0,
199
+ safeZeroReason: '',
200
+ booted: false,
201
+ deferredTail: Promise.resolve(),
202
+ deferredDepth: 0,
203
+ deferredMaxDepth: 0,
204
+ deferredDropped: 0,
205
+ deferredErrors: 0,
206
+ lastDeferredError: '',
207
+ reconnectCount: old ? Math.max(0, Number(old.reconnectCount) || 0) + 1 : 0,
208
+ disconnectCount: old ? Math.max(0, Number(old.disconnectCount) || 0) : 0,
209
+ lastDisconnectAt: old ? old.lastDisconnectAt || 0 : 0,
210
+ lastDisconnectCode: old ? old.lastDisconnectCode || 0 : 0,
211
+ lastDisconnectReason: old ? old.lastDisconnectReason || '' : '',
212
+ outboundCallCount: old ? Math.max(0, Number(old.outboundCallCount) || 0) : 0,
213
+ outboundErrorCount: old ? Math.max(0, Number(old.outboundErrorCount) || 0) : 0,
214
+ lastOutboundMethod: '',
215
+ lastOutboundAt: 0,
216
+ outboundControlTail: Promise.resolve(),
217
+ smartChargingTail: Promise.resolve(),
218
+ smartChargingGeneration: 0,
219
+ smartChargingPending: 0,
220
+ lastSmartCharging: undefined, // Never deduplicate against a previous WebSocket session.
221
+ lastSmartChargingAt: old ? old.lastSmartChargingAt || 0 : 0,
222
+ configurationTail: Promise.resolve(),
223
+ configurationPending: 0,
224
+ configurationWriteGeneration: new Map(),
225
+ configurationRefreshInFlight: false,
226
+ configurationRequestId: old ? Math.max(0, Number(old.configurationRequestId) || 0) : 0,
227
+ configurationPendingRequestId: 0,
228
+ configurationReportDeadlineAt: 0,
229
+ configurationReportRequestId: 0,
230
+ configurationReportCount: 0,
231
+ configurationReportSequences: new Set(),
232
+ configurationInventorySeen: new Set(),
233
+ configurationRebootRequired: false,
234
+ configurationAutoRefreshDone: false,
235
+ configurationAutoRefreshAt: now + Math.max(5, Number(this.config.configurationRefreshDelaySec) || 15) * 1000,
236
+ });
237
+ const entry = this.runtimeIndex.get(identity);
238
+ // Publish the new session fence independently of any old profile publication.
239
+ const publishSession = async () => {
240
+ await this.ensureStructure(identity);
241
+ if (this.runtimeIndex.get(identity) !== entry) return;
242
+ await this._setStateFreshAsync(`${identity}.info.sessionId`, entry.sessionId, true, 'control');
243
+ };
244
+ const previousSession = this._sessionPublications.get(identity) || Promise.resolve();
245
+ entry.sessionPublication = previousSession.then(publishSession, publishSession);
246
+ this._sessionPublications.set(identity, entry.sessionPublication);
247
+ this._ensureEosLease(identity).then(lease => {
248
+ if (lease.armed && this.runtimeIndex.get(identity) === entry) {
249
+ lease.stopSessionId = '';
250
+ if (!this._eosLeaseFresh(lease)) lease.stopRequired = true;
251
+ }
252
+ }).catch(error => this.log.warn(`Could not restore EOS lease: ${error.message}`));
253
+ this._publishChargeLimitStatus(identity, entry, { valid: false, reason: 'connected-awaiting-profile' })
254
+ .catch(error => this.log.warn(`Could not invalidate charging limit on connect: ${error.message}`));
255
+ }
256
+
257
+ _unindexClient(identity, client) {
258
+ const entry = this.runtimeIndex.get(identity);
259
+ if (!entry || (client && entry.client !== client)) return false;
260
+ // Retain the runtime diagnostics while the station is offline. This lets us
261
+ // distinguish a clean reconnect from a brand-new station and preserves the
262
+ // deferred processing counters used to diagnose intermittent disconnects.
263
+ entry.client = null;
264
+ entry.socketConnected = false;
265
+ entry.booted = false;
266
+ entry.refreshInFlight = false;
267
+ entry.configurationRefreshInFlight = false;
268
+ entry.configurationPendingRequestId = 0;
269
+ entry.configurationReportDeadlineAt = 0;
270
+ entry.configurationReportSequences = new Set();
271
+ entry.configurationInventorySeen = new Set();
272
+ this._publishChargeLimitStatus(identity, entry, { valid: false, reason: 'disconnected' })
273
+ .catch(error => this.log.warn(`Could not invalidate charging limit on disconnect: ${error.message}`));
274
+ return true;
275
+ }
276
+
277
+ _deferStationTask(identity, label, task, options = {}) {
278
+ const entry = this.runtimeIndex.get(identity);
279
+ if (!entry || this._shuttingDown) return false;
280
+ const maxDepth = Math.max(25, Number(this.config.maxDeferredTasks) || 250);
281
+ const droppable = options.droppable === true;
282
+ if (droppable && entry.deferredDepth >= maxDepth) {
283
+ entry.deferredDropped++;
284
+ entry.lastDeferredError = `Dropped ${label}: deferred queue reached ${maxDepth}`;
285
+ return false;
286
+ }
287
+ entry.deferredDepth++;
288
+ entry.deferredMaxDepth = Math.max(entry.deferredMaxDepth || 0, entry.deferredDepth);
289
+ const run = async () => {
290
+ try {
291
+ if (this.runtimeIndex.get(identity) !== entry && options.allowAfterReconnect !== true) {
292
+ entry.deferredDropped++;
293
+ entry.lastDeferredError = `Dropped ${label}: OCPP session was superseded`;
294
+ return;
295
+ }
296
+ await task();
297
+ } catch (error) {
298
+ entry.deferredErrors++;
299
+ entry.lastDeferredError = `${label}: ${error && error.message || error}`;
300
+ this.log.warn(`Deferred OCPP processing failed (${identity}, ${label}): ${error && error.stack || error}`);
301
+ } finally {
302
+ entry.deferredDepth = Math.max(0, entry.deferredDepth - 1);
303
+ }
304
+ };
305
+ entry.deferredTail = Promise.resolve(entry.deferredTail).then(run, run);
306
+ return true;
307
+ }
308
+
309
+ async _noteDisconnect(identity, client, details = {}) {
310
+ const entry = this.runtimeIndex.get(identity);
311
+ if (!entry || (client && entry.client !== client)) return;
312
+ const now = Date.now();
313
+ entry.socketConnected = false;
314
+ entry.disconnectCount = Math.max(0, Number(entry.disconnectCount) || 0) + 1;
315
+ entry.lastDisconnectAt = now;
316
+ entry.lastDisconnectCode = Number(details.code) || 0;
317
+ entry.lastDisconnectReason = String(details.reason || 'socket-closed');
318
+ // Some station firmwares disconnect shortly after an actively requested
319
+ // TriggerMessage. Treat this as a correlation signal (not proof), suppress
320
+ // further active refresh for six hours and keep passive push telemetry
321
+ // running. This prevents a diagnostic refresh loop from repeatedly
322
+ // interrupting an otherwise stable charge.
323
+ if (entry.lastTriggerAt && now - entry.lastTriggerAt <= 30_000) {
324
+ entry.refreshRelatedDisconnects = Math.max(0, Number(entry.refreshRelatedDisconnects) || 0) + 1;
325
+ entry.refreshSuppressedUntil = now + 6 * 60 * 60 * 1000;
326
+ entry.refreshSuppressedReason = `disconnect-after-${entry.lastTriggerMessage || 'TriggerMessage'}`;
327
+ entry.triggerRetryAt.MeterValues = entry.refreshSuppressedUntil;
328
+ entry.triggerRetryAt.StatusNotification = entry.refreshSuppressedUntil;
329
+ }
330
+ try {
331
+ await this.ensureStructure(identity);
332
+ await this._setStateFreshAsync(`${identity}.health.lastDisconnectAt`, new Date(now).toISOString(), true, 'health');
333
+ await this._setStateFreshAsync(`${identity}.health.lastDisconnectCode`, entry.lastDisconnectCode, true, 'health');
334
+ await this._setStateFreshAsync(`${identity}.health.lastDisconnectReason`, entry.lastDisconnectReason, true, 'health');
335
+ await this._setStateFreshAsync(`${identity}.health.disconnectCount`, entry.disconnectCount, true, 'health');
336
+ await this._setStateFreshAsync(`${identity}.health.refreshRelatedDisconnects`, entry.refreshRelatedDisconnects || 0, true, 'health');
337
+ await this._setStateFreshAsync(`${identity}.health.refreshSuppressedUntil`, entry.refreshSuppressedUntil ? new Date(entry.refreshSuppressedUntil).toISOString() : '', true, 'health');
338
+ await this._setStateFreshAsync(`${identity}.health.refreshSuppressedReason`, entry.refreshSuppressedReason || '', true, 'health');
339
+ } catch (error) {
340
+ this.log.debug(`Could not persist disconnect diagnostics for ${identity}: ${error && error.message || error}`);
341
+ }
342
+ }
343
+
344
+ _noteMessage(identity, action) {
345
+ const entry = this.runtimeIndex.get(identity);
346
+ if (!entry) return;
347
+ const now = Date.now();
348
+ entry.lastMessageAt = now;
349
+ entry.lastAction = String(action || '');
350
+ }
351
+
352
+ _noteBoot(identity, intervalSec) {
353
+ const entry = this.runtimeIndex.get(identity);
354
+ if (!entry) return;
355
+ const now = Date.now();
356
+ entry.booted = true;
357
+ entry.heartbeatIntervalSec = Math.max(10, Number(intervalSec) || entry.heartbeatIntervalSec || 300);
358
+ // Boot is activity, not a Heartbeat.
359
+ entry.lastMessageAt = Math.max(entry.lastMessageAt || 0, now);
360
+ entry.nextRefreshAt = now + Math.max(30, Number(this.config.activeRefreshIntervalSec) || 60) * 1000;
361
+ entry.lastBootAt = now;
362
+ entry.configurationRebootRequired = false;
363
+ entry.configurationAutoRefreshDone = false;
364
+ entry.configurationAutoRefreshAt = now + Math.max(5, Number(this.config.configurationRefreshDelaySec) || 15) * 1000;
365
+ // RebootRequired is a latch: it stays true after an accepted write until
366
+ // the station registers again with BootNotification. Clearing it here is
367
+ // diagnostic only and never sends a Reset command.
368
+ this._deferStationTask(identity, 'configuration:clear-reboot-required', async () => {
369
+ await this._recordConfigurationStatus(identity, { rebootRequired: false });
370
+ });
371
+ }
372
+
373
+ _noteHeartbeat(identity, timestamp) {
374
+ const entry = this.runtimeIndex.get(identity);
375
+ if (!entry) return;
376
+ // Heartbeat freshness is based on local receipt time. The remote clock is
377
+ // retained only for display and must not make an old connection appear new.
378
+ const now = Date.now();
379
+ entry.lastHeartbeatAt = now;
380
+ entry.lastMessageAt = Math.max(entry.lastMessageAt || 0, now);
381
+ entry.lastHeartbeatSourceTimestamp = timestamp || '';
382
+ }
383
+
384
+ _getStationTelemetry(identity, entry) {
385
+ if (!entry.telemetry) {
386
+ const declared = this.chargePointInventory?.stations?.get(entry.rawIdentity) || [];
387
+ entry.telemetry = new StationTelemetry(entry.proto, declared, [...entry.connectors]);
388
+ }
389
+ return entry.telemetry;
390
+ }
391
+
392
+ async _publishStationTelemetry(identity, entry) {
393
+ if (this.runtimeIndex.get(identity) !== entry || !entry.client || !entry.socketConnected) return;
394
+ const telemetry = this._getStationTelemetry(identity, entry);
395
+ const now = Date.now();
396
+ const snapshot = telemetry.snapshot(now, Math.max(15, Number(this.config.telemetryMaxAgeSec) || 90) * 1000,
397
+ Math.max(30, Number(this.config.socMaxAgeSec) || 300) * 1000, this.config.zeroPowerWhenIdle !== false);
398
+ await this.ensureStructure(identity);
399
+ if (this.runtimeIndex.get(identity) !== entry || !entry.client || !entry.socketConnected) return;
400
+ const write = (key, val, category = 'health') => this._setStateFreshAsync(`${identity}.${key}`, val, true, category);
401
+ // Invalidate before changing the value; consumers must never see a partial sum as fresh.
402
+ const power = snapshot.result.powerW;
403
+ const allowed = this.config.zeroPowerWhenIdle !== false;
404
+ const usable = !!power && (power.category !== 'safeZero' || allowed);
405
+ entry.lastPowerAt = usable && power.category !== 'safeZero' ? Math.min(power.at, power.sourceAt) : 0;
406
+ entry.lastExportPowerAt = snapshot.result.powerExportW && snapshot.result.powerExportW.category !== 'safeZero' ? Math.min(snapshot.result.powerExportW.at, snapshot.result.powerExportW.sourceAt) : 0;
407
+ entry.lastCurrentAt = snapshot.result.currentA && snapshot.result.currentA.category !== 'safeZero' ? Math.min(snapshot.result.currentA.at, snapshot.result.currentA.sourceAt) : 0;
408
+ entry.lastSocAt = snapshot.result.socPercent ? Math.min(snapshot.result.socPercent.at, snapshot.result.socPercent.sourceAt) : 0;
409
+ entry.safeZeroAt = allowed && snapshot.allIdle && power?.category === 'safeZero' ? now : 0;
410
+ entry.safeZeroReason = entry.safeZeroAt ? 'all-outlets-confirmed-idle' : '';
411
+ entry.transactionActive = snapshot.active;
412
+ entry.chargingState = snapshot.chargingState;
413
+ if (!usable) await write('health.dataFresh', false);
414
+ if (!entry.lastSocAt) {
415
+ await write('health.socFresh', false);
416
+ await write('measurements.socPercent', null, 'soc');
417
+ await write('vehicle.socPercent', null, 'soc');
418
+ }
419
+ const last = entry.telemetryPublished || (entry.telemetryPublished = new Map());
420
+ // A real new sample with unchanged value still advances its source timestamp.
421
+ // An unrelated heartbeat/counter may never republish a previous measurement as new.
422
+ for (const [key, item] of Object.entries(snapshot.result)) {
423
+ if (item.category === 'safeZero' && !allowed) continue;
424
+ const prior = last.get(key);
425
+ if (prior && prior.at === item.at && prior.sourceAt === item.sourceAt && prior.val === item.val && prior.category === item.category) continue;
426
+ if (item.category === 'safeZero' && prior?.category === 'safeZero' && prior.val === item.val) continue;
427
+ await this.ensureMeasurement(identity, key);
428
+ await write(`measurements.${key}`, item.val, item.category || 'realtime');
429
+ if (key === 'socPercent') await write('vehicle.socPercent', item.val, 'soc');
430
+ last.set(key, item);
431
+ }
432
+ for (const [key, val] of Object.entries({
433
+ 'info.connectorCount': snapshot.connectorCount, 'info.evseCount': snapshot.evseCount,
434
+ 'info.topologySource': snapshot.topologySource, 'info.eosContract': 'nexowatt-ocpp21-0.4-native',
435
+ 'info.deviceType': 'evCharger', 'info.controlScope': 'station', 'health.powerSource': usable ? power.source : 'unknown-or-incomplete',
436
+ 'health.powerFresh': usable && power.category !== 'safeZero', 'health.currentFresh': !!entry.lastCurrentAt,
437
+ 'health.exportPowerFresh': !!entry.lastExportPowerAt, 'health.socFresh': !!entry.lastSocAt,
438
+ 'health.safeZeroApplied': !!entry.safeZeroAt, 'health.safeZeroReason': entry.safeZeroReason,
439
+ 'transactions.transactionActive': snapshot.active, 'transactions.chargingState': snapshot.chargingState,
440
+ })) await write(key, val, key.startsWith('health.') ? 'health' : 'status');
441
+ if (snapshot.status) await write('info.status', snapshot.status, 'status');
442
+ if (entry.lastPowerAt) await write('health.lastPowerValue', new Date(entry.lastPowerAt).toISOString());
443
+ if (entry.lastSocAt) await write('health.lastSoc', new Date(entry.lastSocAt).toISOString());
444
+ const connection = deriveConnectionHealth({ now, socketConnected: entry.socketConnected, connectedAt: entry.connectedAt, lastMessageAt: entry.lastMessageAt,
445
+ lastHeartbeatAt: entry.lastHeartbeatAt, heartbeatIntervalSec: entry.heartbeatIntervalSec, heartbeatTimeoutFactor: this.config.heartbeatTimeoutFactor, activityTimeoutSec: this.config.activityTimeoutSec });
446
+ await write('health.dataFresh', connection.online && (usable || !!entry.safeZeroAt));
447
+ }
448
+
449
+ async _publishScopedMeter(identity, evseId, connectorId, values, at, sourceAt) {
450
+ const entry = this.runtimeIndex.get(identity);
451
+ if (!entry || !entry.client || !entry.socketConnected) return;
452
+ const telemetry = this._getStationTelemetry(identity, entry);
453
+ telemetry.meter(evseId, connectorId, values, at, sourceAt);
454
+ if (evseId > 0 && connectorId > 0) entry.connectors.add(`${evseId}:${connectorId}`);
455
+ entry.lastMeterAt = at;
456
+ await this._setStateFreshAsync(`${identity}.health.lastMeterValue`, new Date(at).toISOString(), true, 'health');
457
+ await this._publishStationTelemetry(identity, entry);
458
+ }
459
+
460
+ async _publishScopedSoc(identity, evseId, connectorId, val) {
461
+ const entry = this.runtimeIndex.get(identity);
462
+ if (!entry || !entry.client || !entry.socketConnected || !Number.isFinite(val) || val < 0 || val > 100) return;
463
+ const telemetry = this._getStationTelemetry(identity, entry);
464
+ if (!Number.isSafeInteger(evseId) || evseId < 1) {
465
+ if (telemetry.scopes.size > 1) return;
466
+ evseId = 0; connectorId = 0;
467
+ }
468
+ const now = Date.now();
469
+ telemetry.meter(evseId, connectorId, { socPercent: { val, category: 'soc' } }, now, now);
470
+ await this._publishStationTelemetry(identity, entry);
471
+ }
472
+
473
+ async _noteStatus(identity, evseId, connectorId, status) {
474
+ const entry = this.runtimeIndex.get(identity);
475
+ if (!entry || !entry.client || !entry.socketConnected) return;
476
+ entry.lastStatusAt = Date.now();
477
+ if (evseId > 0 && connectorId > 0) entry.connectors.add(`${evseId}:${connectorId}`);
478
+ entry.statuses.set(`${evseId}:${connectorId}`, String(status || ''));
479
+ this._getStationTelemetry(identity, entry).status(evseId, connectorId, status);
480
+ await this._publishStationTelemetry(identity, entry);
481
+ }
482
+
483
+ async _noteMeterValue(identity, evseId, connectorId, timestamp, flags = {}) {
484
+ const entry = this.runtimeIndex.get(identity);
485
+ if (!entry) return;
486
+ // Freshness is based on local receipt time. A station clock can be wrong,
487
+ // in the future or far in the past and must not falsify EOS data quality.
488
+ const now = Date.now();
489
+ entry.lastMeterAt = Math.max(entry.lastMeterAt || 0, now);
490
+ if (flags.hasPower) entry.lastPowerAt = Math.max(entry.lastPowerAt || 0, now);
491
+ if (flags.hasExportPower) entry.lastExportPowerAt = Math.max(entry.lastExportPowerAt || 0, now);
492
+ if (flags.hasCurrent) entry.lastCurrentAt = Math.max(entry.lastCurrentAt || 0, now);
493
+ entry.connectors.add(`${Math.max(0, Number(evseId) || 0)}:${Math.max(0, Number(connectorId) || 0)}`);
494
+ // A valid, non-zero actual-flow sample contradicts a previously derived
495
+ // idle zero. Counter-only, SoC-only or zero-valued samples do not: an
496
+ // unchanged Available/Idle protocol state remains authoritative while the
497
+ // station is online.
498
+ if (flags.hasNonZeroActualFlow) {
499
+ entry.safeZeroAt = 0;
500
+ entry.safeZeroReason = '';
501
+ }
502
+ await this.ensureStructure(identity, evseId, connectorId);
503
+ await this._setStateFreshAsync(`${identity}.health.lastMeterValue`, new Date(entry.lastMeterAt).toISOString(), true, 'health');
504
+ if (flags.hasPower) await this._setStateFreshAsync(`${identity}.health.lastPowerValue`, new Date(entry.lastPowerAt).toISOString(), true, 'health');
505
+ if (flags.hasExportPower) await this._setStateFreshAsync(`${identity}.health.lastExportPowerValue`, new Date(entry.lastExportPowerAt).toISOString(), true, 'health');
506
+ if (flags.hasCurrent) await this._setStateFreshAsync(`${identity}.health.lastCurrentValue`, new Date(entry.lastCurrentAt).toISOString(), true, 'health');
507
+ }
508
+
509
+ async _noteSoc(identity, timestamp) {
510
+ const entry = this.runtimeIndex.get(identity);
511
+ if (!entry) return;
512
+ // As with meter freshness, use receipt time rather than the EV/station
513
+ // timestamp so clock skew cannot falsify health.socFresh.
514
+ const now = Date.now();
515
+ entry.lastSocAt = Math.max(entry.lastSocAt || 0, now);
516
+ await this.ensureStructure(identity);
517
+ await this._setStateFreshAsync(`${identity}.health.lastSoc`, new Date(entry.lastSocAt).toISOString(), true, 'health');
518
+ }
519
+
520
+ _recordPhaseMetric(identity, evseId, connectorId, measurand, phase, value, unit, ts) {
521
+ const phaseKey = canonicalPhase(phase);
522
+ if (!phaseKey) return;
523
+ const key = `${identity}|${evseId}|${connectorId}|${measurand}`;
524
+ if (!this._phaseMetricCache.has(key)) this._phaseMetricCache.set(key, new Map());
525
+ this._phaseMetricCache.get(key).set(phaseKey, { value: Number(value), unit: unit || '', ts: Number(ts) || Date.now() });
526
+ }
527
+
528
+ _getPhaseMetricTotal(identity, evseId, connectorId, measurand) {
529
+ const key = `${identity}|${evseId}|${connectorId}|${measurand}`;
530
+ const values = this._phaseMetricCache.get(key);
531
+ if (!values) return undefined;
532
+ const maxAgeMs = Math.max(15, Number(this.config.telemetryMaxAgeSec) || 90) * 1000;
533
+ const cutoff = Date.now() - maxAgeMs;
534
+ const samples = [];
535
+ let unit = '';
536
+ for (const [phase, sample] of values.entries()) {
537
+ if (!sample || sample.ts < cutoff || !Number.isFinite(sample.value)) {
538
+ values.delete(phase);
539
+ continue;
540
+ }
541
+ samples.push(sample.value);
542
+ unit = unit || sample.unit || '';
543
+ }
544
+ const value = aggregatePhaseValues(measurand, samples);
545
+ return Number.isFinite(value) ? { value, unit, phaseCount: samples.length } : undefined;
546
+ }
547
+
548
+ async _noteTransaction(identity, evt) {
549
+ const entry = this.runtimeIndex.get(identity);
550
+ if (!entry || !entry.client || !entry.socketConnected) return;
551
+ if (Number(evt.evseId) > 0 && Number(evt.connectorId) > 0) entry.connectors.add(`${evt.evseId}:${evt.connectorId}`);
552
+ this._getStationTelemetry(identity, entry).transaction(evt);
553
+ await this._publishStationTelemetry(identity, entry);
554
+ }
555
+
556
+ async _zeroActualFlow(identity, reason, evseId, connectorId) {
557
+ await this.ensureStructure(identity, evseId || 1, connectorId || 1);
558
+ const now = Date.now();
559
+ const entry = this.runtimeIndex.get(identity);
560
+ const ids = new Set([
561
+ `${identity}.measurements.powerW`,
562
+ `${identity}.measurements.powerExportW`,
563
+ `${identity}.measurements.currentA`,
564
+ `${identity}.measurements.currentExportA`,
565
+ ]);
566
+ const cache = this._freshStateCache.get(identity);
567
+ if (cache) {
568
+ for (const stateId of cache.keys()) if (isActualPowerOrCurrentId(stateId)) ids.add(stateId);
569
+ }
570
+ if (this.config.connectorDetails === true && evseId !== undefined && connectorId !== undefined) {
571
+ const base = this._connectorBase(identity, evseId, connectorId);
572
+ ids.add(`${base}.powerW`);
573
+ ids.add(`${base}.powerExportW`);
574
+ ids.add(`${base}.currentA`);
575
+ ids.add(`${base}.currentExportA`);
576
+ }
577
+ for (const stateId of ids) {
578
+ const key = stateId.split('.').pop();
579
+ if (stateId.includes('.measurements.')) await this.ensureMeasurement(identity, key, key.toLowerCase().includes('current') ? 'A' : 'W');
580
+ await this._setStateFreshAsync(stateId, 0, true, 'safeZero');
581
+ }
582
+ for (const key of [...this._phaseMetricCache.keys()]) if (key.startsWith(`${identity}|`)) this._phaseMetricCache.delete(key);
583
+ if (entry) {
584
+ entry.safeZeroAt = now;
585
+ entry.safeZeroReason = reason;
586
+ }
587
+ await this._setStateFreshAsync(`${identity}.health.safeZeroApplied`, true, true, 'health');
588
+ await this._setStateFreshAsync(`${identity}.health.safeZeroReason`, reason, true, 'health');
589
+ }
590
+
591
+ async _touchCachedStates(identity, safeZero, now = Date.now(), cursor = 0) {
592
+ const cache = this._freshStateCache.get(identity);
593
+ if (!cache || cache.size === 0) return 0;
594
+ const maxStates = Math.max(25, Number(this.config.maxRepublishedStates) || 250);
595
+ const selection = selectCachedStatesForRepublish(cache.entries(), {
596
+ cursor,
597
+ limit: maxStates,
598
+ now,
599
+ telemetryMaxAgeSec: this.config.telemetryMaxAgeSec,
600
+ socMaxAgeSec: this.config.socMaxAgeSec,
601
+ safeZero,
602
+ });
603
+ for (const [stateId, item] of selection.entries) {
604
+ if (cache.get(stateId) !== item) continue;
605
+ await this.setStateAsync(stateId, { val: item.val, ack: item.ack });
606
+ }
607
+ return selection.nextCursor;
608
+ }
609
+
610
+ async _callClient(identity, method, payload, options = {}) {
611
+ if (typeof this.assertCanOperate === 'function') this.assertCanOperate();
612
+ const entry = this.runtimeIndex.get(identity);
613
+ if (!entry || !entry.client) throw new Error(`No connected charging station for ${identity}`);
614
+ const timeoutMs = commandTimeoutMs(this.config.callTimeoutSec);
615
+ entry.outboundCallCount = Math.max(0, Number(entry.outboundCallCount) || 0) + 1;
616
+ entry.lastOutboundMethod = String(method || '');
617
+ entry.lastOutboundAt = Date.now();
618
+ const captureEnabled = options.capture !== false && this.config.captureRawMessages === true;
619
+ if (captureEnabled) {
620
+ this._deferStationTask(identity, `capture-out:${method}`, () => this.captureOcppPayload(identity, entry.proto, 'out', method, payload), { droppable: true });
621
+ }
622
+ let timer;
623
+ try {
624
+ const timeout = new Promise((_, reject) => {
625
+ timer = setTimeout(() => reject(new Error(`${method} timeout after ${timeoutMs} ms`)), timeoutMs);
626
+ });
627
+ const client = entry.client;
628
+ if (typeof this.assertCanOperate === 'function') this.assertCanOperate();
629
+ const response = await Promise.race([client.call(method, payload), timeout]);
630
+ if (this.runtimeIndex.get(identity) !== entry || entry.client !== client || !entry.socketConnected) throw new Error('OCPP session changed during command');
631
+ if (typeof this.assertCanOperate === 'function') this.assertCanOperate();
632
+ // A CALLRESULT is valid OCPP application activity as well. It keeps
633
+ // activityFresh/health.online alive without pretending that a Heartbeat
634
+ // was received.
635
+ if (this.runtimeIndex.get(identity) === entry) {
636
+ entry.lastMessageAt = Date.now();
637
+ entry.lastAction = `${method}Response`;
638
+ }
639
+ if (captureEnabled) {
640
+ this._deferStationTask(identity, `capture-out:${method}Response`, () => this.captureOcppPayload(identity, entry.proto, 'out', `${method}Response`, response), { droppable: true });
641
+ }
642
+ return response;
643
+ } catch (error) {
644
+ entry.outboundErrorCount = Math.max(0, Number(entry.outboundErrorCount) || 0) + 1;
645
+ if (captureEnabled) {
646
+ this._deferStationTask(identity, `capture-out:${method}Error`, () => this.captureOcppPayload(identity, entry.proto, 'out', `${method}Error`, { error: String(error && error.message || error) }), { droppable: true });
647
+ }
648
+ throw error;
649
+ } finally {
650
+ if (timer) clearTimeout(timer);
651
+ }
652
+ }
653
+
654
+ _assertCallAccepted(method, response) {
655
+ if (!response || typeof response !== 'object' || typeof response.status !== 'string') throw new Error(`${method}: missing response status`);
656
+ const status = response.status.trim();
657
+ const accepted = new Set(['accepted', 'scheduled', 'rebootrequired', 'ok']);
658
+ if (!accepted.has(status.toLowerCase())) throw new Error(`${method} returned status ${status}`);
659
+ return response;
660
+ }
661
+
662
+ _stringifyControlValue(value) {
663
+ if (value === undefined) return '';
664
+ if (typeof value === 'string') return value;
665
+ try { return JSON.stringify(value); } catch (e) { return String(value); }
666
+ }
667
+
668
+ async _recordControlResult(identity, method, response, error) {
669
+ await this.ensureStructure(identity);
670
+ const now = new Date().toISOString();
671
+ const errorText = error ? String(error && error.message || error) : '';
672
+ // Profile validity is owned by the profile/session lifecycle. An older
673
+ // command's generic diagnostics must not invalidate a newer accepted one.
674
+ await this._setStateFreshAsync(`${identity}.control.lastCommand`, String(method || ''), true, 'control');
675
+ await this._setStateFreshAsync(`${identity}.control.lastCommandAt`, now, true, 'control');
676
+ await this._setStateFreshAsync(`${identity}.control.lastResponse`, errorText ? '' : this._stringifyControlValue(response), true, 'control');
677
+ await this._setStateFreshAsync(`${identity}.control.lastError`, errorText, true, 'control');
678
+ await this._setStateFreshAsync(`${identity}.control.lastSuccess`, !errorText, true, 'control');
679
+ }
680
+
681
+ _configurationMap(identity) {
682
+ if (!this._configurationByIdentity.has(identity)) this._configurationByIdentity.set(identity, new Map());
683
+ return this._configurationByIdentity.get(identity);
684
+ }
685
+
686
+ _configurationDisplayName(meta) {
687
+ if (!meta) return 'OCPP configuration';
688
+ if (meta.kind === 'ocpp16') return String(meta.key || 'OCPP 1.6 configuration');
689
+ const component = meta.component || {};
690
+ const variable = meta.variable || {};
691
+ const componentParts = [component.name || 'Component'];
692
+ if (component.instance) componentParts.push(`[${component.instance}]`);
693
+ if (component.evse && component.evse.id !== undefined) {
694
+ componentParts.push(`EVSE ${component.evse.id}`);
695
+ if (component.evse.connectorId !== undefined) componentParts.push(`Connector ${component.evse.connectorId}`);
696
+ }
697
+ const variableParts = [variable.name || 'Variable'];
698
+ if (variable.instance) variableParts.push(`[${variable.instance}]`);
699
+ return `${componentParts.join(' ')} · ${variableParts.join(' ')} · ${meta.attributeType || 'Actual'}`;
700
+ }
701
+
702
+ _configurationNative(meta, value, hasValue = true) {
703
+ const native = {
704
+ kind: meta.kind,
705
+ protocol: meta.protocol,
706
+ canonicalKey: meta.canonicalKey,
707
+ key: meta.key,
708
+ readonly: meta.readonly,
709
+ component: cloneOcppReference(meta.component),
710
+ variable: cloneOcppReference(meta.variable),
711
+ attributeType: meta.attributeType,
712
+ mutability: meta.mutability,
713
+ persistent: meta.persistent,
714
+ constant: meta.constant,
715
+ dataType: meta.dataType,
716
+ unit: meta.unit,
717
+ minLimit: meta.minLimit,
718
+ maxLimit: meta.maxLimit,
719
+ valuesList: meta.valuesList,
720
+ supportsMonitoring: meta.supportsMonitoring,
721
+ sensitive: meta.sensitive === true || configurationSensitive(meta),
722
+ stale: meta.stale === true,
723
+ inventoryPending: meta.inventoryPending === true,
724
+ stateKey: meta.stateKey,
725
+ };
726
+ for (const key of Object.keys(native)) if (native[key] === undefined) delete native[key];
727
+ if (native.sensitive) {
728
+ native.lastConfirmedValue = null;
729
+ native.lastConfirmedAt = '';
730
+ } else if (hasValue) {
731
+ native.lastConfirmedValue = value;
732
+ native.lastConfirmedAt = new Date().toISOString();
733
+ } else if (Object.prototype.hasOwnProperty.call(meta, 'lastConfirmedValue')) {
734
+ native.lastConfirmedValue = meta.lastConfirmedValue;
735
+ if (meta.lastConfirmedAt) native.lastConfirmedAt = meta.lastConfirmedAt;
736
+ }
737
+ return native;
738
+ }
739
+
740
+ _configurationStateCommon(meta, value) {
741
+ const sensitive = meta.sensitive === true || configurationSensitive(meta);
742
+ const type = sensitive ? 'string' : meta.stateType || (typeof value === 'boolean' ? 'boolean' : typeof value === 'number' ? 'number' : 'string');
743
+ const writable = configurationWritable(meta, this.config.configurationWriteEnabled !== false);
744
+ let role = sensitive ? 'text' : stateRoleForConfiguration(type, value);
745
+ if (type === 'boolean' && !writable) role = 'indicator';
746
+ const mutability = String(meta.mutability || '').toLowerCase();
747
+ const common = {
748
+ name: this._configurationDisplayName(meta),
749
+ type,
750
+ role,
751
+ read: !sensitive && (meta.kind !== 'deviceModel' || mutability !== 'writeonly'),
752
+ write: writable,
753
+ };
754
+ if (meta.unit) common.unit = String(meta.unit);
755
+ if (type === 'number' && Number.isFinite(Number(meta.minLimit))) common.min = Number(meta.minLimit);
756
+ if (type === 'number' && Number.isFinite(Number(meta.maxLimit))) common.max = Number(meta.maxLimit);
757
+ if (String(meta.dataType || '').toLowerCase() === 'optionlist') {
758
+ const states = parseValuesList(meta.valuesList);
759
+ if (states) common.states = states;
760
+ }
761
+ return common;
762
+ }
763
+
764
+ async _upsertConfigurationState(identity, meta, value, hasValue = true) {
765
+ await this.ensureStructure(identity);
766
+ const stateKey = String(meta.stateKey || '').trim();
767
+ if (!stateKey || RESERVED_CONFIGURATION_KEYS.has(stateKey)) throw new Error(`Invalid configuration state key ${stateKey || '<empty>'}`);
768
+ const relId = `${identity}.configuration.${stateKey}`;
769
+ let existing;
770
+ try {
771
+ if (typeof this.getObjectAsync === 'function') existing = await this.getObjectAsync(relId);
772
+ else if (typeof this.getForeignObjectAsync === 'function') existing = await this.getForeignObjectAsync(`${this.namespace}.${relId}`);
773
+ } catch (error) {
774
+ this.log.debug(`Could not inspect OCPP configuration object ${relId}: ${error && error.message || error}`);
775
+ }
776
+ const previousNative = existing && existing.native && existing.native.ocppConfiguration;
777
+ const cachedConfirmed = this._configurationValueCache.has(relId)
778
+ ? this._configurationValueCache.get(relId)
779
+ : previousNative && Object.prototype.hasOwnProperty.call(previousNative, 'lastConfirmedValue')
780
+ ? previousNative.lastConfirmedValue
781
+ : undefined;
782
+ const storedMeta = {
783
+ ...meta,
784
+ stateKey,
785
+ stateId: relId,
786
+ stale: false,
787
+ inventoryPending: meta.inventoryPending === true,
788
+ };
789
+ storedMeta.sensitive = meta.sensitive === true || configurationSensitive(storedMeta);
790
+ const effectiveHasValue = hasValue && !storedMeta.sensitive;
791
+ if (!effectiveHasValue && !storedMeta.sensitive && cachedConfirmed !== undefined) {
792
+ storedMeta.lastConfirmedValue = cachedConfirmed;
793
+ storedMeta.lastConfirmedAt = previousNative && previousNative.lastConfirmedAt;
794
+ }
795
+ const common = this._configurationStateCommon(storedMeta, effectiveHasValue ? value : cachedConfirmed);
796
+ const native = { ocppConfiguration: this._configurationNative(storedMeta, value, effectiveHasValue) };
797
+ if (!existing) {
798
+ await this.setObjectNotExistsAsync(relId, { type: 'state', common, native });
799
+ } else if (typeof this.extendObjectAsync === 'function') {
800
+ await this.extendObjectAsync(relId, { common, native });
801
+ }
802
+ this._dpObjCache.add(relId);
803
+ this._configurationIndex.set(relId, storedMeta);
804
+ this._configurationIndex.set(`${this.namespace}.${relId}`, storedMeta);
805
+ this._configurationMap(identity).set(stateKey, storedMeta);
806
+ if (storedMeta.sensitive) {
807
+ this._configurationValueCache.delete(relId);
808
+ await this._setStateFreshAsync(relId, '', true, 'configuration');
809
+ } else if (effectiveHasValue) {
810
+ this._configurationValueCache.set(relId, value);
811
+ await this._setStateFreshAsync(relId, value, true, 'configuration');
812
+ }
813
+ return relId;
814
+ }
815
+
816
+ async _recordConfigurationStatus(identity, patch = {}) {
817
+ await this.ensureStructure(identity);
818
+ const known = new Set([
819
+ 'lastRefresh', 'status', 'error', 'count', 'reportInProgress', 'requestId', 'lastSequence',
820
+ 'lastChangedKey', 'lastChangedAt', 'lastChangeStatus', 'lastChangeResponse', 'rebootRequired',
821
+ 'unknownKeysJson', 'indexJson',
822
+ ]);
823
+ for (const [key, rawValue] of Object.entries(patch)) {
824
+ if (!known.has(key) || rawValue === undefined) continue;
825
+ let value = rawValue;
826
+ if (['lastChangeResponse', 'unknownKeysJson', 'indexJson'].includes(key) && typeof value !== 'string') {
827
+ value = this._stringifyControlValue(value);
828
+ }
829
+ await this._setStateFreshAsync(`${identity}.configuration.${key}`, value, true, 'configuration');
830
+ }
831
+ }
832
+
833
+ async _updateConfigurationIndex(identity) {
834
+ const map = this._configurationMap(identity);
835
+ const index = {};
836
+ for (const [stateKey, meta] of [...map.entries()].sort(([a], [b]) => a.localeCompare(b))) {
837
+ if (meta.kind === 'ocpp16') {
838
+ index[stateKey] = {
839
+ protocol: meta.protocol,
840
+ key: meta.key,
841
+ dataType: meta.dataType,
842
+ sensitive: meta.sensitive === true || configurationSensitive(meta),
843
+ stale: meta.stale === true,
844
+ inventoryPending: meta.inventoryPending === true,
845
+ writable: configurationWritable(meta, this.config.configurationWriteEnabled !== false),
846
+ };
847
+ } else {
848
+ index[stateKey] = {
849
+ protocol: meta.protocol,
850
+ component: meta.component && meta.component.name,
851
+ componentInstance: meta.component && meta.component.instance,
852
+ evseId: meta.component && meta.component.evse && meta.component.evse.id,
853
+ connectorId: meta.component && meta.component.evse && meta.component.evse.connectorId,
854
+ variable: meta.variable && meta.variable.name,
855
+ variableInstance: meta.variable && meta.variable.instance,
856
+ attributeType: meta.attributeType || 'Actual',
857
+ dataType: meta.dataType,
858
+ unit: meta.unit,
859
+ sensitive: meta.sensitive === true || configurationSensitive(meta),
860
+ stale: meta.stale === true,
861
+ inventoryPending: meta.inventoryPending === true,
862
+ writable: configurationWritable(meta, this.config.configurationWriteEnabled !== false),
863
+ };
864
+ }
865
+ for (const key of Object.keys(index[stateKey])) if (index[stateKey][key] === undefined) delete index[stateKey][key];
866
+ }
867
+ await this._recordConfigurationStatus(identity, { indexJson: index });
868
+ }
869
+
870
+ async _hydrateConfigurationIndex(identity) {
871
+ if (typeof this.getObjectViewAsync !== 'function') return 0;
872
+ const prefix = `${this.namespace}.${identity}.configuration.`;
873
+ let view;
874
+ try {
875
+ view = await this.getObjectViewAsync('system', 'state', {
876
+ startkey: prefix,
877
+ endkey: `${prefix}\u9999`,
878
+ });
879
+ } catch (error) {
880
+ this.log.debug(`Could not load existing OCPP configuration objects for ${identity}: ${error && error.message || error}`);
881
+ return 0;
882
+ }
883
+
884
+ let hydrated = 0;
885
+ const rows = Array.isArray(view && view.rows) ? view.rows : [];
886
+ for (const row of rows) {
887
+ const fullId = String(row && row.id || '');
888
+ const relId = this._stripNs(fullId);
889
+ const stateKey = relId.startsWith(`${identity}.configuration.`)
890
+ ? relId.slice(`${identity}.configuration.`.length)
891
+ : '';
892
+ if (!stateKey || stateKey.includes('.') || RESERVED_CONFIGURATION_KEYS.has(stateKey)) continue;
893
+ const object = row && (row.value || row.doc);
894
+ const nativeMeta = object && object.native && object.native.ocppConfiguration;
895
+ if (!nativeMeta || !['ocpp16', 'deviceModel'].includes(nativeMeta.kind)) continue;
896
+ const meta = {
897
+ ...nativeMeta,
898
+ component: cloneOcppReference(nativeMeta.component),
899
+ variable: cloneOcppReference(nativeMeta.variable),
900
+ stateKey: nativeMeta.stateKey || stateKey,
901
+ stateId: relId,
902
+ };
903
+ this._configurationIndex.set(relId, meta);
904
+ this._configurationIndex.set(`${this.namespace}.${relId}`, meta);
905
+ this._configurationMap(identity).set(meta.stateKey, meta);
906
+ if (meta.sensitive !== true && Object.prototype.hasOwnProperty.call(meta, 'lastConfirmedValue')
907
+ && meta.lastConfirmedValue !== null) {
908
+ this._configurationValueCache.set(relId, meta.lastConfirmedValue);
909
+ }
910
+ hydrated++;
911
+ }
912
+ return hydrated;
913
+ }
914
+
915
+ async _setConfigurationInventoryPending(identity, protocol, pending) {
916
+ const map = this._configurationMap(identity);
917
+ let changed = 0;
918
+ for (const [stateKey, currentMeta] of map.entries()) {
919
+ if (!currentMeta || currentMeta.protocol !== protocol || currentMeta.stale === true
920
+ || currentMeta.inventoryPending === pending) continue;
921
+ const relId = `${identity}.configuration.${stateKey}`;
922
+ const meta = { ...currentMeta, inventoryPending: pending === true, stateKey, stateId: relId };
923
+ this._configurationIndex.set(relId, meta);
924
+ this._configurationIndex.set(`${this.namespace}.${relId}`, meta);
925
+ map.set(stateKey, meta);
926
+ const currentValue = this._configurationValueCache.has(relId)
927
+ ? this._configurationValueCache.get(relId)
928
+ : meta.lastConfirmedValue;
929
+ try {
930
+ if (typeof this.extendObjectAsync === 'function') {
931
+ await this.extendObjectAsync(relId, {
932
+ common: this._configurationStateCommon(meta, currentValue),
933
+ native: { ocppConfiguration: this._configurationNative(meta, currentValue, false) },
934
+ });
935
+ }
936
+ } catch (error) {
937
+ this.log.debug(`Could not update OCPP configuration inventory state ${relId}: ${error && error.message || error}`);
938
+ }
939
+ changed++;
940
+ }
941
+ return changed;
942
+ }
943
+
944
+ async _finalizeConfigurationInventoryStates(identity, seenStateKeys, protocol) {
945
+ const seen = seenStateKeys instanceof Set ? seenStateKeys : new Set(seenStateKeys || []);
946
+ const map = this._configurationMap(identity);
947
+ let finalized = 0;
948
+ for (const stateKey of seen) {
949
+ const currentMeta = map.get(stateKey);
950
+ if (!currentMeta || currentMeta.protocol !== protocol) continue;
951
+ const relId = `${identity}.configuration.${stateKey}`;
952
+ const meta = {
953
+ ...currentMeta,
954
+ stale: false,
955
+ inventoryPending: false,
956
+ stateKey,
957
+ stateId: relId,
958
+ };
959
+ this._configurationIndex.set(relId, meta);
960
+ this._configurationIndex.set(`${this.namespace}.${relId}`, meta);
961
+ map.set(stateKey, meta);
962
+ const currentValue = this._configurationValueCache.has(relId)
963
+ ? this._configurationValueCache.get(relId)
964
+ : meta.lastConfirmedValue;
965
+ try {
966
+ if (typeof this.extendObjectAsync === 'function') {
967
+ await this.extendObjectAsync(relId, {
968
+ common: this._configurationStateCommon(meta, currentValue),
969
+ native: { ocppConfiguration: this._configurationNative(meta, currentValue, false) },
970
+ });
971
+ }
972
+ } catch (error) {
973
+ this.log.debug(`Could not finalize OCPP configuration state ${relId}: ${error && error.message || error}`);
974
+ }
975
+ finalized++;
976
+ }
977
+ return finalized;
978
+ }
979
+
980
+ _queueOutboundControlOperation(identity, entry, task) {
981
+ const run = async () => {
982
+ if (this.runtimeIndex.get(identity) !== entry || !entry.client) {
983
+ throw new Error('Charging station is not connected');
984
+ }
985
+ const lease = this._eosLeases.get(identity);
986
+ if (lease?.armed && (!this._eosLeaseFresh(lease) || lease.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
987
+ return task();
988
+ };
989
+ entry.outboundControlTail = Promise.resolve(entry.outboundControlTail).then(run, run);
990
+ return entry.outboundControlTail;
991
+ }
992
+
993
+ async _restoreConfigurationState(relId, meta) {
994
+ const rel = this._stripNs(relId);
995
+ if (meta && (meta.sensitive === true || configurationSensitive(meta))) {
996
+ await this._setStateFreshAsync(rel, '', true, 'configuration');
997
+ return '';
998
+ }
999
+ if (this._configurationValueCache.has(rel)) {
1000
+ const value = this._configurationValueCache.get(rel);
1001
+ await this._setStateFreshAsync(rel, value, true, 'configuration');
1002
+ return value;
1003
+ }
1004
+ if (meta && Object.prototype.hasOwnProperty.call(meta, 'lastConfirmedValue') && meta.lastConfirmedValue !== null) {
1005
+ await this._setStateFreshAsync(rel, meta.lastConfirmedValue, true, 'configuration');
1006
+ return meta.lastConfirmedValue;
1007
+ }
1008
+ // No value was ever confirmed by the station. Acknowledging the user's
1009
+ // rejected value would be misleading, so expose an explicit empty state.
1010
+ await this._setStateFreshAsync(rel, null, true, 'configuration');
1011
+ return null;
1012
+ }
1013
+
1014
+ async _retireMissingConfigurationStates(identity, seenStateKeys, protocol) {
1015
+ const seen = seenStateKeys instanceof Set ? seenStateKeys : new Set(seenStateKeys || []);
1016
+ const map = this._configurationMap(identity);
1017
+ let retired = 0;
1018
+ for (const [stateKey, currentMeta] of map.entries()) {
1019
+ if (!currentMeta || seen.has(stateKey) || currentMeta.stale === true) continue;
1020
+ const relId = `${identity}.configuration.${stateKey}`;
1021
+ const meta = {
1022
+ ...currentMeta,
1023
+ stale: true,
1024
+ inventoryPending: false,
1025
+ stateKey,
1026
+ stateId: relId,
1027
+ };
1028
+ if (!Object.prototype.hasOwnProperty.call(meta, 'lastConfirmedValue') && this._configurationValueCache.has(relId)) {
1029
+ meta.lastConfirmedValue = this._configurationValueCache.get(relId);
1030
+ }
1031
+ this._configurationIndex.set(relId, meta);
1032
+ this._configurationIndex.set(`${this.namespace}.${relId}`, meta);
1033
+ map.set(stateKey, meta);
1034
+ const currentValue = this._configurationValueCache.has(relId)
1035
+ ? this._configurationValueCache.get(relId)
1036
+ : meta.lastConfirmedValue;
1037
+ try {
1038
+ if (typeof this.extendObjectAsync === 'function') {
1039
+ await this.extendObjectAsync(relId, {
1040
+ common: this._configurationStateCommon(meta, currentValue),
1041
+ native: { ocppConfiguration: this._configurationNative(meta, currentValue, false) },
1042
+ });
1043
+ }
1044
+ } catch (error) {
1045
+ this.log.debug(`Could not retire stale OCPP configuration state ${relId}: ${error && error.message || error}`);
1046
+ }
1047
+ retired++;
1048
+ }
1049
+ return retired;
1050
+ }
1051
+
1052
+ _nextConfigurationRequestId(entry) {
1053
+ const current = Math.max(0, Math.trunc(Number(entry && entry.configurationRequestId) || 0));
1054
+ const next = current >= 0x7ffffffe ? 1 : current + 1;
1055
+ if (entry) entry.configurationRequestId = next;
1056
+ return next;
1057
+ }
1058
+
1059
+ _typedConfigurationValue(meta, valueString) {
1060
+ if (meta && meta.kind === 'ocpp16') return inferOcpp16Value(valueString).val;
1061
+ const parsed = parseDeviceModelValue(valueString, meta && meta.dataType || 'string');
1062
+ return parsed.val === undefined ? String(valueString ?? '') : parsed.val;
1063
+ }
1064
+
1065
+ async _persistConfigurationConfirmedValue(relId, meta, value) {
1066
+ const rel = this._stripNs(relId);
1067
+ const sensitive = meta.sensitive === true || configurationSensitive(meta);
1068
+ meta.sensitive = sensitive;
1069
+ if (sensitive) {
1070
+ this._configurationValueCache.delete(rel);
1071
+ delete meta.lastConfirmedValue;
1072
+ delete meta.lastConfirmedAt;
1073
+ } else {
1074
+ this._configurationValueCache.set(rel, value);
1075
+ meta.lastConfirmedValue = value;
1076
+ meta.lastConfirmedAt = new Date().toISOString();
1077
+ }
1078
+ this._configurationIndex.set(rel, meta);
1079
+ this._configurationIndex.set(`${this.namespace}.${rel}`, meta);
1080
+ try {
1081
+ if (typeof this.extendObjectAsync === 'function') {
1082
+ await this.extendObjectAsync(rel, {
1083
+ native: { ocppConfiguration: this._configurationNative(meta, value, !sensitive) },
1084
+ });
1085
+ }
1086
+ } catch (error) {
1087
+ this.log.debug(`Could not persist confirmed OCPP configuration metadata for ${rel}: ${error && error.message || error}`);
1088
+ }
1089
+ await this._setStateFreshAsync(rel, sensitive ? '' : value, true, 'configuration');
1090
+ }
1091
+
1092
+ async _resolveConfigurationMeta(relId) {
1093
+ const rel = this._stripNs(String(relId || ''));
1094
+ let meta = this._configurationIndex.get(rel) || this._configurationIndex.get(`${this.namespace}.${rel}`);
1095
+ if (meta) return meta;
1096
+ let object;
1097
+ try {
1098
+ if (typeof this.getObjectAsync === 'function') object = await this.getObjectAsync(rel);
1099
+ else if (typeof this.getForeignObjectAsync === 'function') object = await this.getForeignObjectAsync(`${this.namespace}.${rel}`);
1100
+ } catch (error) {
1101
+ this.log.debug(`Could not load OCPP configuration metadata for ${rel}: ${error && error.message || error}`);
1102
+ }
1103
+ const nativeMeta = object && object.native && object.native.ocppConfiguration;
1104
+ if (!nativeMeta || !['ocpp16', 'deviceModel'].includes(nativeMeta.kind)) return undefined;
1105
+ meta = {
1106
+ ...nativeMeta,
1107
+ component: cloneOcppReference(nativeMeta.component),
1108
+ variable: cloneOcppReference(nativeMeta.variable),
1109
+ stateKey: nativeMeta.stateKey || rel.split('.').pop(),
1110
+ stateId: rel,
1111
+ };
1112
+ this._configurationIndex.set(rel, meta);
1113
+ this._configurationIndex.set(`${this.namespace}.${rel}`, meta);
1114
+ const identity = this._identityFromStateId(rel);
1115
+ if (identity && meta.stateKey) this._configurationMap(identity).set(meta.stateKey, meta);
1116
+ if (nativeMeta.sensitive !== true && Object.prototype.hasOwnProperty.call(nativeMeta, 'lastConfirmedValue')
1117
+ && nativeMeta.lastConfirmedValue !== null) {
1118
+ this._configurationValueCache.set(rel, nativeMeta.lastConfirmedValue);
1119
+ }
1120
+ return meta;
1121
+ }
1122
+
1123
+ async ingestConfiguration16(identity, response) {
1124
+ const list = Array.isArray(response && response.configurationKey) ? response.configurationKey : [];
1125
+ const seenStateKeys = new Set();
1126
+ for (const item of list) {
1127
+ const key = String(item && item.key || '').trim();
1128
+ if (!key) continue;
1129
+ const parsed = inferOcpp16Value(item && item.value);
1130
+ const stateKey = configurationStateKey16(key);
1131
+ seenStateKeys.add(stateKey);
1132
+ await this._upsertConfigurationState(identity, {
1133
+ kind: 'ocpp16',
1134
+ protocol: 'ocpp1.6',
1135
+ canonicalKey: canonicalConfigurationKey16(key),
1136
+ key,
1137
+ readonly: !(item && item.readonly === false),
1138
+ dataType: parsed.dataType,
1139
+ stateType: parsed.type,
1140
+ stateKey,
1141
+ }, parsed.val, true);
1142
+ }
1143
+ await this._retireMissingConfigurationStates(identity, seenStateKeys, 'ocpp1.6');
1144
+ const unknown = Array.isArray(response && response.unknownKey) ? response.unknownKey.map(String) : [];
1145
+ const entry = this.runtimeIndex.get(identity);
1146
+ if (entry) {
1147
+ entry.configurationRefreshInFlight = false;
1148
+ entry.configurationPendingRequestId = 0;
1149
+ entry.configurationReportDeadlineAt = 0;
1150
+ entry.configurationInventorySeen = seenStateKeys;
1151
+ entry.configurationReportSequences = new Set();
1152
+ }
1153
+ await this._updateConfigurationIndex(identity);
1154
+ await this._recordConfigurationStatus(identity, {
1155
+ status: list.length ? 'ready' : 'empty',
1156
+ error: '',
1157
+ count: seenStateKeys.size,
1158
+ reportInProgress: false,
1159
+ lastRefresh: new Date().toISOString(),
1160
+ unknownKeysJson: unknown,
1161
+ });
1162
+ return list.length;
1163
+ }
1164
+
1165
+ async _refreshConfiguration(identity, options = {}) {
1166
+ const entry = this.runtimeIndex.get(identity);
1167
+ if (!entry || !entry.client) {
1168
+ await this._recordConfigurationStatus(identity, {
1169
+ status: 'offline', error: 'Charging station is not connected', reportInProgress: false,
1170
+ });
1171
+ throw new Error('Charging station is not connected');
1172
+ }
1173
+ if (entry.transactionActive && this.config.allowConfigurationDuringCharging !== true) {
1174
+ await this._recordConfigurationStatus(identity, {
1175
+ status: 'busy-charging',
1176
+ error: 'Configuration operations are disabled during an active charging transaction',
1177
+ reportInProgress: false,
1178
+ });
1179
+ throw new Error('Configuration operations are disabled during an active charging transaction');
1180
+ }
1181
+ if ((entry.smartChargingPending || 0) > 0 || entry.refreshInFlight || (entry.configurationPending || 0) > 0) {
1182
+ await this._recordConfigurationStatus(identity, {
1183
+ status: 'busy',
1184
+ error: 'Another station command or refresh is still in progress',
1185
+ reportInProgress: false,
1186
+ });
1187
+ throw new Error('Another station command or refresh is still in progress');
1188
+ }
1189
+ if (entry.configurationRefreshInFlight) return { status: 'AlreadyInProgress' };
1190
+ const requestId = entry.proto === 'ocpp1.6' ? 0 : this._nextConfigurationRequestId(entry);
1191
+ const call = buildConfigurationRefreshCall(entry.proto, requestId);
1192
+ entry.configurationRefreshInFlight = true;
1193
+ entry.configurationPendingRequestId = requestId;
1194
+ entry.configurationReportRequestId = requestId;
1195
+ entry.configurationInventorySeen = new Set();
1196
+ entry.configurationReportSequences = new Set();
1197
+ entry.configurationReportCount = 0;
1198
+ // The outbound CALL has its own command timeout. Start the longer
1199
+ // asynchronous NotifyReport timeout only after GetBaseReport was accepted.
1200
+ entry.configurationReportDeadlineAt = 0;
1201
+ let response;
1202
+ try {
1203
+ // Load configuration objects that survived an adapter restart before the
1204
+ // new inventory is compared. Without this hydration a removed firmware
1205
+ // variable could remain visibly writable until the station rejects it.
1206
+ await this._hydrateConfigurationIndex(identity);
1207
+ if (entry.proto === 'ocpp2.0.1' || entry.proto === 'ocpp2.1') {
1208
+ // OCPP 2.x inventories arrive asynchronously. Existing values become
1209
+ // temporarily read-only until the complete matching report is received.
1210
+ // A timeout therefore cannot leave a partially refreshed mapping writable.
1211
+ const pendingChanged = await this._setConfigurationInventoryPending(identity, entry.proto, true);
1212
+ if (pendingChanged) await this._updateConfigurationIndex(identity);
1213
+ }
1214
+ await this._recordConfigurationStatus(identity, {
1215
+ status: options.automatic ? 'auto-refreshing' : 'refreshing',
1216
+ error: '',
1217
+ reportInProgress: entry.proto !== 'ocpp1.6',
1218
+ requestId,
1219
+ });
1220
+ // Configuration reads share the same per-station outbound command slot as
1221
+ // Smart Charging and configuration writes. The potentially large
1222
+ // asynchronous NotifyReport itself remains inbound and does not block
1223
+ // later EOS charging limits after GetBaseReport has been acknowledged.
1224
+ response = await this._queueOutboundControlOperation(
1225
+ identity,
1226
+ entry,
1227
+ () => this._callClient(identity, call.method, call.payload, { capture: false }),
1228
+ );
1229
+ const interpreted = interpretConfigurationRefreshResponse(entry.proto, response);
1230
+ if (!interpreted.accepted) throw new Error(`${call.method} returned status ${interpreted.status}`);
1231
+ await this._recordControlResult(identity, call.method, configurationRefreshDiagnostic(entry.proto, response), undefined);
1232
+ if (entry.proto === 'ocpp1.6') {
1233
+ await this.ingestConfiguration16(identity, response);
1234
+ return { status: 'Accepted', response };
1235
+ }
1236
+ if (interpreted.empty) {
1237
+ await this._retireMissingConfigurationStates(identity, new Set(), entry.proto);
1238
+ await this._updateConfigurationIndex(identity);
1239
+ entry.configurationRefreshInFlight = false;
1240
+ entry.configurationPendingRequestId = 0;
1241
+ entry.configurationReportDeadlineAt = 0;
1242
+ entry.configurationInventorySeen = new Set();
1243
+ entry.configurationReportSequences = new Set();
1244
+ await this._recordConfigurationStatus(identity, {
1245
+ status: 'empty', error: '', count: 0, reportInProgress: false, lastRefresh: new Date().toISOString(), requestId,
1246
+ });
1247
+ return { status: interpreted.status, response };
1248
+ }
1249
+ entry.configurationReportDeadlineAt = Date.now()
1250
+ + Math.max(30, Number(this.config.configurationReportTimeoutSec) || 120) * 1000;
1251
+ await this._recordConfigurationStatus(identity, {
1252
+ status: 'waiting-report', error: '', reportInProgress: true, requestId,
1253
+ });
1254
+ return { status: interpreted.status, response, reportExpected: true, requestId };
1255
+ } catch (error) {
1256
+ entry.configurationRefreshInFlight = false;
1257
+ entry.configurationPendingRequestId = 0;
1258
+ entry.configurationReportDeadlineAt = 0;
1259
+ entry.configurationInventorySeen = new Set();
1260
+ entry.configurationReportSequences = new Set();
1261
+ await this._recordControlResult(identity, call.method, response, error);
1262
+ await this._recordConfigurationStatus(identity, {
1263
+ status: /notsupported|not supported/i.test(String(error && error.message || error)) ? 'not-supported' : 'error',
1264
+ error: String(error && error.message || error),
1265
+ reportInProgress: false,
1266
+ requestId,
1267
+ });
1268
+ throw error;
1269
+ }
1270
+ }
1271
+
1272
+ async _maybeAutoRefreshConfiguration(identity, entry, now = Date.now()) {
1273
+ if (this.config.autoConfigurationRefresh !== true || !entry || !entry.client || !entry.booted) return;
1274
+ if (entry.configurationAutoRefreshDone || entry.configurationRefreshInFlight || now < (entry.configurationAutoRefreshAt || 0)) return;
1275
+ if (entry.transactionActive || (entry.smartChargingPending || 0) > 0 || entry.refreshInFlight || (entry.configurationPending || 0) > 0) {
1276
+ entry.configurationAutoRefreshAt = now + 60_000;
1277
+ return;
1278
+ }
1279
+ if (entry.lastOutboundAt && now - entry.lastOutboundAt < 10_000) {
1280
+ entry.configurationAutoRefreshAt = now + 30_000;
1281
+ return;
1282
+ }
1283
+ entry.configurationAutoRefreshDone = true;
1284
+ try {
1285
+ await this._refreshConfiguration(identity, { automatic: true });
1286
+ } catch (error) {
1287
+ this.log.warn(`Automatic OCPP configuration refresh failed (${identity}): ${error && error.message || error}`);
1288
+ }
1289
+ }
1290
+
1291
+ async _writeConfigurationValue(identity, relId, requestedValue, isCurrent = () => true) {
1292
+ const entry = this.runtimeIndex.get(identity);
1293
+ if (!entry || !entry.client) throw new Error('Charging station is not connected');
1294
+ const rel = this._stripNs(relId);
1295
+ const lease = this._eosLeases.get(identity);
1296
+ if (lease?.armed && (!this._eosLeaseFresh(lease) || lease.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
1297
+ const meta = await this._resolveConfigurationMeta(rel);
1298
+ if (!meta) throw new Error('Missing OCPP configuration metadata; refresh the configuration inventory first');
1299
+ if (meta.protocol && meta.protocol !== entry.proto) {
1300
+ throw new Error(`Configuration mapping belongs to ${meta.protocol}; refresh it for the connected ${entry.proto} session first`);
1301
+ }
1302
+ if (entry.configurationRefreshInFlight) {
1303
+ throw new Error('Configuration inventory refresh is still in progress');
1304
+ }
1305
+ if (entry.transactionActive && this.config.allowConfigurationDuringCharging !== true) {
1306
+ throw new Error('Configuration operations are disabled during an active charging transaction');
1307
+ }
1308
+ if (!configurationWritable(meta, this.config.configurationWriteEnabled !== false)) throw new Error('This OCPP configuration value is read-only');
1309
+ if (!isCurrent()) return { status: 'Superseded' };
1310
+ const sensitive = meta.sensitive === true || configurationSensitive(meta);
1311
+ if (sensitive) await this._setStateFreshAsync(rel, '', true, 'configuration');
1312
+ const call = buildConfigurationWriteCall(entry.proto, meta, requestedValue);
1313
+ const changedKey = meta.kind === 'ocpp16' ? meta.key : this._configurationDisplayName(meta);
1314
+ await this._recordConfigurationStatus(identity, {
1315
+ status: 'write-pending', error: '', lastChangedKey: changedKey, lastChangedAt: new Date().toISOString(),
1316
+ });
1317
+ let response;
1318
+ try {
1319
+ if (lease?.armed && (!this._eosLeaseFresh(lease) || lease.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
1320
+ response = await this._callClient(identity, call.method, call.payload, { capture: false });
1321
+ const result = interpretConfigurationWriteResponse(entry.proto, response);
1322
+ if (!result.accepted) throw new Error(`${call.method} returned status ${result.status}`);
1323
+ if (!isCurrent()) return { status: 'Superseded', response };
1324
+ const confirmedValue = this._typedConfigurationValue(meta, call.valueString);
1325
+ await this._persistConfigurationConfirmedValue(rel, meta, confirmedValue);
1326
+ if (result.rebootRequired) entry.configurationRebootRequired = true;
1327
+ await this._recordControlResult(identity, call.method, response, undefined);
1328
+ await this._recordConfigurationStatus(identity, {
1329
+ status: result.rebootRequired ? 'reboot-required' : 'write-accepted',
1330
+ error: '',
1331
+ lastChangedKey: changedKey,
1332
+ lastChangedAt: new Date().toISOString(),
1333
+ lastChangeStatus: result.status,
1334
+ lastChangeResponse: response,
1335
+ rebootRequired: entry.configurationRebootRequired === true,
1336
+ });
1337
+ return { ...result, response, confirmedValue, method: call.method };
1338
+ } catch (error) {
1339
+ const status = response ? interpretConfigurationWriteResponse(entry.proto, response).status : 'Error';
1340
+ await this._recordControlResult(identity, call.method, response, error);
1341
+ await this._recordConfigurationStatus(identity, {
1342
+ status: 'write-error',
1343
+ error: String(error && error.message || error),
1344
+ lastChangedKey: changedKey,
1345
+ lastChangedAt: new Date().toISOString(),
1346
+ lastChangeStatus: status,
1347
+ lastChangeResponse: response || {},
1348
+ });
1349
+ await this._restoreConfigurationState(rel, meta);
1350
+ throw error;
1351
+ }
1352
+ }
1353
+
1354
+ _queueConfigurationWrite(identity, relId, requestedValue) {
1355
+ const entry = this.runtimeIndex.get(identity);
1356
+ if (!entry || !entry.client) return Promise.reject(new Error('Charging station is not connected'));
1357
+ const rel = this._stripNs(relId);
1358
+ const generation = (entry.configurationWriteGeneration.get(rel) || 0) + 1;
1359
+ entry.configurationWriteGeneration.set(rel, generation);
1360
+ entry.configurationPending = Math.max(0, Number(entry.configurationPending) || 0) + 1;
1361
+ const run = async () => {
1362
+ try {
1363
+ return await this._writeConfigurationValue(
1364
+ identity,
1365
+ rel,
1366
+ requestedValue,
1367
+ () => this.runtimeIndex.get(identity) === entry && entry.client && entry.configurationWriteGeneration.get(rel) === generation,
1368
+ );
1369
+ } finally {
1370
+ entry.configurationPending = Math.max(0, (Number(entry.configurationPending) || 1) - 1);
1371
+ }
1372
+ };
1373
+ entry.outboundControlTail = Promise.resolve(entry.outboundControlTail).then(run, run);
1374
+ entry.configurationTail = entry.outboundControlTail;
1375
+ return entry.outboundControlTail;
1376
+ }
1377
+
1378
+ _buildChargingProfileCall(protocol, limit, rateUnit, phases, identity, functionKey = 'eos-charge-limit') {
1379
+ const connectorId = this.config.smartChargingConnectorId === 0 ? 0 : Math.max(1, Math.trunc(Number(this.config.smartChargingConnectorId) || 1));
1380
+ const scope = protocol === 'ocpp1.6' ? `connector-${connectorId}` : 'charging-station';
1381
+ const { chargingProfileId, scheduleId } = deterministicChargingProfileIds(identity, functionKey, scope);
1382
+ if (protocol === 'ocpp1.6') {
1383
+ return {
1384
+ method: 'SetChargingProfile',
1385
+ payload: {
1386
+ connectorId,
1387
+ csChargingProfiles: {
1388
+ chargingProfileId,
1389
+ stackLevel: 0,
1390
+ chargingProfilePurpose: connectorId === 0 ? 'ChargePointMaxProfile' : 'TxDefaultProfile',
1391
+ chargingProfileKind: 'Absolute',
1392
+ chargingSchedule: {
1393
+ chargingRateUnit: rateUnit,
1394
+ chargingSchedulePeriod: [{ startPeriod: 0, limit, numberPhases: phases }],
1395
+ },
1396
+ },
1397
+ },
1398
+ };
1399
+ }
1400
+ return {
1401
+ method: 'SetChargingProfile',
1402
+ payload: {
1403
+ evseId: 0,
1404
+ chargingProfile: {
1405
+ id: chargingProfileId,
1406
+ stackLevel: 0,
1407
+ chargingProfilePurpose: 'ChargingStationMaxProfile',
1408
+ chargingProfileKind: 'Absolute',
1409
+ chargingSchedule: [{
1410
+ id: scheduleId,
1411
+ chargingRateUnit: rateUnit,
1412
+ chargingSchedulePeriod: [{ startPeriod: 0, limit, numberPhases: phases }],
1413
+ }],
1414
+ },
1415
+ },
1416
+ };
1417
+ }
1418
+
1419
+ _buildClearChargingProfileCall(protocol, identity, functionKey = 'eos-charge-limit') {
1420
+ const connectorId = this.config.smartChargingConnectorId === 0 ? 0 : Math.max(1, Math.trunc(Number(this.config.smartChargingConnectorId) || 1));
1421
+ const scope = protocol === 'ocpp1.6' ? `connector-${connectorId}` : 'charging-station';
1422
+ const { chargingProfileId } = deterministicChargingProfileIds(identity, functionKey, scope);
1423
+ if (protocol === 'ocpp1.6') {
1424
+ return { method: 'ClearChargingProfile', payload: { id: chargingProfileId } };
1425
+ }
1426
+ return { method: 'ClearChargingProfile', payload: { chargingProfileId } };
1427
+ }
1428
+
1429
+ _ensureEosLease(identity) {
1430
+ const existing = this._eosLeases.get(identity);
1431
+ if (existing) return existing.ready;
1432
+ const lease = { armed: false, active: false, untilMs: 0, deadline: 0, lastEventTs: 0,
1433
+ stopRequired: false, stopPending: false, stopSessionId: '', lastStopAttemptMono: -Infinity, updateTail: Promise.resolve() };
1434
+ this._eosLeases.set(identity, lease);
1435
+ lease.ready = (async () => {
1436
+ await this.ensureStructure(identity);
1437
+ const persisted = await this.getStateAsync(`${identity}.control.eosLeaseArmed`);
1438
+ lease.armed = persisted?.val === true;
1439
+ lease.stopRequired = lease.armed;
1440
+ await this._setStateFreshAsync(`${identity}.info.eosControlLeaseSupported`, true, true, 'control');
1441
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseState`, lease.armed ? 'expired-awaiting-renewal' : 'unarmed', true, 'control');
1442
+ return lease;
1443
+ })().catch(error => {
1444
+ if (this._eosLeases.get(identity) === lease) this._eosLeases.delete(identity);
1445
+ throw error;
1446
+ });
1447
+ return lease.ready;
1448
+ }
1449
+
1450
+ _eosLeaseFresh(lease) {
1451
+ return !lease?.armed || (lease.active && Date.now() < lease.untilMs && performance.now() < lease.deadline);
1452
+ }
1453
+
1454
+ async _renewEosLease(identity, state) {
1455
+ const lease = await this._ensureEosLease(identity);
1456
+ const run = async () => {
1457
+ const now = Date.now();
1458
+ const ts = state.ts;
1459
+ // Only a new live ioBroker write event may renew a lease. Never replay a
1460
+ // persisted future deadline after startup or accept an older queued event.
1461
+ if (state.ack !== false || (state.q !== undefined && state.q !== 0) || typeof ts !== 'number' || !Number.isFinite(ts) || ts < this._startedAtMs || ts <= lease.lastEventTs || ts > now + 1000 || now - ts > 5000) return false;
1462
+ lease.lastEventTs = ts;
1463
+ const until = state.val;
1464
+ const accepted = typeof until === 'number' && Number.isFinite(until) && until > now && until <= now + 30000;
1465
+ if (accepted) {
1466
+ const wasExpired = lease.armed && !this._eosLeaseFresh(lease);
1467
+ lease.armed = true;
1468
+ // Persist the latch BEFORE permitting positive power. If this write
1469
+ // fails, the lease remains inactive and no positive command is allowed.
1470
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseArmed`, true, true, 'control');
1471
+ lease.untilMs = until;
1472
+ lease.deadline = performance.now() + Math.max(0, until - Date.now());
1473
+ lease.active = true;
1474
+ if (wasExpired && !lease.stopSessionId) lease.stopRequired = true;
1475
+ } else if (lease.armed) {
1476
+ lease.active = false;
1477
+ lease.untilMs = 0;
1478
+ lease.deadline = 0;
1479
+ lease.stopRequired = true;
1480
+ lease.stopSessionId = '';
1481
+ }
1482
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseState`, !lease.armed ? 'unarmed-invalid-renewal'
1483
+ : !this._eosLeaseFresh(lease) ? 'expired' : lease.stopRequired ? 'renewed-awaiting-zero' : 'active', true, 'control');
1484
+ const current = await this.getStateAsync(`${identity}.control.eosLeaseUntilMs`);
1485
+ if (current?.ack === false && current.ts === state.ts && current.val === state.val) {
1486
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseUntilMs`, state.val, true, 'control');
1487
+ }
1488
+ return accepted;
1489
+ };
1490
+ const update = lease.updateTail.then(run, run);
1491
+ lease.updateTail = update.catch(() => {
1492
+ lease.active = false;
1493
+ if (lease.armed) { lease.stopRequired = true; lease.stopSessionId = ''; }
1494
+ });
1495
+ return update;
1496
+ }
1497
+
1498
+ async _eosLeaseWatchdogCycle() {
1499
+ if (this._shuttingDown || this._eosLeaseWatchdogRunning) return;
1500
+ this._eosLeaseWatchdogRunning = true;
1501
+ try {
1502
+ for (const [identity, entry] of this.runtimeIndex) {
1503
+ try {
1504
+ let lease;
1505
+ try { lease = await this._ensureEosLease(identity); }
1506
+ catch (error) { this.log.warn(`EOS lease state unavailable (${identity}): ${error.message}`); continue; }
1507
+ if (!lease.armed) continue;
1508
+ if (!this._eosLeaseFresh(lease) && lease.active) {
1509
+ lease.active = false;
1510
+ lease.stopRequired = true;
1511
+ lease.stopSessionId = '';
1512
+ }
1513
+ if (!lease.stopRequired || lease.stopPending) continue;
1514
+ this._publishChargeLimitStatus(identity, entry, { valid: false, reason: 'EOS_LEASE_EXPIRED', error: 'EOS_LEASE_EXPIRED' })
1515
+ .catch(() => this.log.warn(`EOS lease invalidation publication failed (${identity})`));
1516
+ if (!entry.client || !entry.socketConnected) {
1517
+ this._setStateFreshAsync(`${identity}.control.eosLeaseState`, 'expired-offline-zero-unconfirmed', true, 'control')
1518
+ .catch(() => this.log.warn(`EOS lease offline status unavailable (${identity})`));
1519
+ continue;
1520
+ }
1521
+ if (performance.now() - lease.lastStopAttemptMono < 5000) continue;
1522
+ lease.lastStopAttemptMono = performance.now();
1523
+ lease.stopPending = true;
1524
+ this._setStateFreshAsync(`${identity}.control.eosLeaseState`, 'expired-zero-pending', true, 'control')
1525
+ .catch(() => this.log.warn(`EOS lease pending publication failed (${identity})`));
1526
+ // Existing outbound serialization keeps a late positive CALLRESULT in
1527
+ // front of this zero command. Its generation can no longer confirm it.
1528
+ this._queueSmartCharging(identity, 0, 'W', 3).then(async result => {
1529
+ if (this.runtimeIndex.get(identity) !== entry || !entry.socketConnected || !['Applied', 'Unchanged'].includes(result.status)) return;
1530
+ lease.stopRequired = false;
1531
+ lease.stopSessionId = entry.sessionId;
1532
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseState`, this._eosLeaseFresh(lease) ? 'active-awaiting-new-setpoint' : 'expired-zero-confirmed', true, 'control');
1533
+ }).catch(async error => {
1534
+ this.log.warn(`EOS lease zero not confirmed (${identity}): ${error.message}`);
1535
+ await this._setStateFreshAsync(`${identity}.control.eosLeaseState`, 'expired-zero-failed', true, 'control');
1536
+ }).finally(() => { lease.stopPending = false; }).catch(error => {
1537
+ this.log.warn(`EOS lease diagnostic publication failed (${identity}): EOS_LEASE_DIAGNOSTIC_FAILED`);
1538
+ });
1539
+ } catch (error) {
1540
+ this.log.warn(`EOS lease station check failed (${identity}): EOS_LEASE_CHECK_FAILED`);
1541
+ }
1542
+ }
1543
+ } catch (error) {
1544
+ this.log.warn(`EOS lease watchdog failed: ${error.message}`);
1545
+ } finally {
1546
+ this._eosLeaseWatchdogRunning = false;
1547
+ }
1548
+ }
1549
+
1550
+ _publishChargeLimitStatus(identity, entry, patch, isCurrent = () => true, legacyResult = null) {
1551
+ const sessionId = entry?.sessionId || '';
1552
+ const client = entry?.client;
1553
+ const current = () => this.runtimeIndex.get(identity) === entry && isCurrent();
1554
+ const valid = () => current() && !!client && entry.client === client && entry.socketConnected && !this._shuttingDown
1555
+ && (!(patch.appliedW > 0) || (this._eosLeaseFresh(this._eosLeases.get(identity)) && !this._eosLeases.get(identity)?.stopRequired));
1556
+ const finiteW = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
1557
+ const code = value => String(value || '').replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 80);
1558
+ const run = async () => {
1559
+ await this.ensureStructure(identity);
1560
+ if (entry?.sessionPublication) await entry.sessionPublication;
1561
+ if (!current() || (patch.valid && !valid())) return false;
1562
+ const status = {
1563
+ schema: 1, valid: patch.valid === true,
1564
+ requestedW: finiteW(patch.requestedW), appliedW: patch.valid ? finiteW(patch.appliedW) : null,
1565
+ appliedAtMs: patch.valid && Number.isFinite(patch.appliedAtMs) ? patch.appliedAtMs : 0,
1566
+ sessionId, updatedAtMs: Date.now(), reason: code(patch.reason), error: code(patch.error),
1567
+ };
1568
+ // Legacy fields remain supported, with validity false throughout updates.
1569
+ await this._setStateFreshAsync(`${identity}.control.appliedChargeLimitValid`, false, true, 'control');
1570
+ if (!current() || (status.valid && !valid())) return false;
1571
+ if (legacyResult) {
1572
+ const fields = {
1573
+ requestedChargeLimit: legacyResult.requestedLimit,
1574
+ appliedChargeLimit: legacyResult.effectiveLimit,
1575
+ appliedChargeLimitUnit: legacyResult.rateUnit,
1576
+ appliedChargeLimitW: legacyResult.effectiveLimitW,
1577
+ chargeLimitReason: String(legacyResult.reason || ''),
1578
+ chargeLimitClamped: legacyResult.effectiveLimit !== legacyResult.requestedLimit,
1579
+ };
1580
+ for (const [key, value] of Object.entries(fields)) {
1581
+ if (!valid()) return false;
1582
+ await this._setStateFreshAsync(`${identity}.control.${key}`, value, true, 'control');
1583
+ }
1584
+ }
1585
+ if (!current() || (status.valid && !valid())) return false;
1586
+ // This single JSON value is the authoritative, internally consistent result.
1587
+ await this._setStateFreshAsync(`${identity}.control.chargeLimitStatus`, JSON.stringify(status), true, 'control');
1588
+ if (status.valid && valid()) {
1589
+ await this._setStateFreshAsync(`${identity}.control.appliedChargeLimitValid`, true, true, 'control');
1590
+ }
1591
+ if (status.valid && !valid()) {
1592
+ // A reconnect/new request can happen while an ioBroker write is awaited.
1593
+ // Serialize this invalidation before the next session/request publication.
1594
+ const invalid = { ...status, valid: false, appliedW: null, appliedAtMs: 0,
1595
+ updatedAtMs: Date.now(), reason: 'superseded', error: '' };
1596
+ await this._setStateFreshAsync(`${identity}.control.appliedChargeLimitValid`, false, true, 'control');
1597
+ await this._setStateFreshAsync(`${identity}.control.chargeLimitStatus`, JSON.stringify(invalid), true, 'control');
1598
+ return false;
1599
+ }
1600
+ return true;
1601
+ };
1602
+ const previous = this._chargeLimitPublications.get(identity) || Promise.resolve();
1603
+ const publication = previous.then(run, run);
1604
+ this._chargeLimitPublications.set(identity, publication);
1605
+ return publication;
1606
+ }
1607
+
1608
+ async _persistSmartChargingResult(identity, result, entry, isCurrent) {
1609
+ const expired = !this._eosLeaseFresh(this._eosLeases.get(identity));
1610
+ return this._publishChargeLimitStatus(identity, entry, {
1611
+ valid: !expired, requestedW: result.requestedLimit, appliedW: result.effectiveLimitW,
1612
+ appliedAtMs: entry.lastSmartChargingAt, reason: expired ? 'EOS_LEASE_EXPIRED' : result.reason || 'accepted',
1613
+ error: expired ? 'EOS_LEASE_EXPIRED' : '',
1614
+ }, isCurrent, result);
1615
+ }
1616
+
1617
+ async _applySmartCharging(identity, requestedLimit, rateUnit, phases, isCurrent = () => true) {
1618
+ const entry = this.runtimeIndex.get(identity);
1619
+ const lease = await this._ensureEosLease(identity);
1620
+ const emergencyZero = requestedLimit === 0 && lease.armed && lease.stopRequired;
1621
+ if (!emergencyZero) await lease.updateTail;
1622
+ const pendingPublication = this._publishChargeLimitStatus(identity, entry, {
1623
+ valid: false, requestedW: requestedLimit, reason: emergencyZero ? 'EOS_LEASE_EXPIRED' : 'pending',
1624
+ }, isCurrent);
1625
+ if (emergencyZero) pendingPublication.catch(() => this.log.warn(`EOS emergency zero pending status unavailable (${identity})`));
1626
+ else await pendingPublication;
1627
+ try {
1628
+ if (Number(requestedLimit) > 0 && (!this._eosLeaseFresh(lease) || lease.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
1629
+ return await this._applySmartChargingCurrent(identity, requestedLimit, rateUnit, phases, isCurrent);
1630
+ } catch (error) {
1631
+ if (this.runtimeIndex.get(identity) === entry && isCurrent()) {
1632
+ if (entry) entry.lastSmartCharging = undefined;
1633
+ const message = String(error?.message || error);
1634
+ const errorCode = message === 'EOS_LEASE_EXPIRED' ? 'EOS_LEASE_EXPIRED' : /timeout/i.test(message) ? 'timeout' : /returned/i.test(message) ? 'rejected'
1635
+ : /session|connected/i.test(message) ? 'session-changed' : 'invalid-request';
1636
+ await this._publishChargeLimitStatus(identity, entry, {
1637
+ valid: false, requestedW: requestedLimit, reason: 'failed', error: errorCode,
1638
+ }, isCurrent);
1639
+ }
1640
+ throw error;
1641
+ }
1642
+ }
1643
+
1644
+ async _applySmartChargingCurrent(identity, requestedLimit, rateUnit, phases, isCurrent = () => true) {
1645
+ const entry = this.runtimeIndex.get(identity);
1646
+ if (!entry || !entry.client) throw new Error('Charging station is not connected');
1647
+ const normalized = normalizeEosLimit(requestedLimit, rateUnit, phases, this.config);
1648
+ const topology = this._getStationTelemetry(identity, entry);
1649
+ if (topology.inventoryMismatch) throw new Error('EOS_CONNECTOR_INVENTORY_MISMATCH');
1650
+ const configuredConnector = this.config.smartChargingConnectorId === 0 ? 0 : Number(this.config.smartChargingConnectorId) || 1;
1651
+ if (entry.proto === 'ocpp1.6' && configuredConnector !== 0 && (topology.scopes.size > 1 || (topology.scopes.size === 1 && !topology.scopes.has(`c${configuredConnector}`)))) throw new Error('OCPP 1.6 station limit requires the correct connector or explicit station scope (0)');
1652
+
1653
+ // EOS may write a new setpoint while an older one is still waiting for the
1654
+ // OCPP command slot. Never send a queued value that has already been
1655
+ // superseded by a newer control cycle.
1656
+ if (!isCurrent()) return { status: 'Superseded', ...normalized };
1657
+
1658
+ if (!shouldSendLimit(entry.lastSmartCharging, normalized, this.config)) {
1659
+ normalized.reason = 'unchanged-within-deadband';
1660
+ normalized.effectiveLimit = entry.lastSmartCharging.effectiveLimit;
1661
+ normalized.effectiveLimitW = entry.lastSmartCharging.effectiveLimitW;
1662
+ if (!await this._persistSmartChargingResult(identity, normalized, entry, isCurrent)) return { status: 'Superseded', ...normalized };
1663
+ return { status: 'Unchanged', ...normalized };
1664
+ }
1665
+
1666
+ const minIntervalMs = Math.max(1000, Number(this.config.smartChargingMinIntervalMs) || 5000);
1667
+ const waitMs = Math.max(0, minIntervalMs - (Date.now() - (entry.lastSmartChargingAt || 0)));
1668
+ // Reductions are safety limits, never delayed by the increase rate limiter.
1669
+ if (waitMs > 0 && entry.lastSmartCharging && normalized.effectiveLimit > entry.lastSmartCharging.effectiveLimit) await new Promise((resolve) => setTimeout(resolve, waitMs));
1670
+ if (!isCurrent()) return { status: 'Superseded', ...normalized };
1671
+
1672
+ const call = normalized.action === 'clear'
1673
+ ? this._buildClearChargingProfileCall(entry.proto, identity)
1674
+ : this._buildChargingProfileCall(entry.proto, normalized.effectiveLimit, normalized.rateUnit, normalized.phases, identity);
1675
+ if (normalized.effectiveLimitW > 0 && (!this._eosLeaseFresh(this._eosLeases.get(identity)) || this._eosLeases.get(identity)?.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
1676
+ const response = await this._callClient(identity, call.method, call.payload);
1677
+ if (response?.status !== 'Accepted') throw new Error(`${call.method} returned ${response?.status || 'no status'}`);
1678
+ entry.lastSmartChargingAt = Date.now();
1679
+ entry.lastSmartCharging = { ...normalized };
1680
+ if (normalized.effectiveLimitW > 0) this._eosLeases.get(identity).stopSessionId = '';
1681
+ if (!isCurrent()) return { status: 'Superseded', ...normalized };
1682
+ if (!await this._persistSmartChargingResult(identity, normalized, entry, isCurrent)) return { status: 'Superseded', ...normalized };
1683
+ return { status: 'Applied', method: call.method, response, ...normalized };
1684
+ }
1685
+
1686
+ async _queueSmartCharging(identity, requestedLimit, rateUnit, phases) {
1687
+ const lease = await this._ensureEosLease(identity);
1688
+ if (!(requestedLimit === 0 && lease.armed && lease.stopRequired)) await lease.updateTail;
1689
+ if (Number(requestedLimit) > 0 && (!this._eosLeaseFresh(lease) || lease.stopRequired)) {
1690
+ await this._publishChargeLimitStatus(identity, this.runtimeIndex.get(identity), { valid: false, requestedW: requestedLimit, reason: 'EOS_LEASE_EXPIRED', error: 'EOS_LEASE_EXPIRED' });
1691
+ throw new Error('EOS_LEASE_EXPIRED');
1692
+ }
1693
+ const entry = this.runtimeIndex.get(identity);
1694
+ if (!entry || !entry.client) return Promise.reject(new Error('Charging station is not connected'));
1695
+ const generation = (entry.smartChargingGeneration || 0) + 1;
1696
+ entry.smartChargingGeneration = generation;
1697
+ const isCurrent = () => this.runtimeIndex.get(identity) === entry && !!entry.client && entry.smartChargingGeneration === generation
1698
+ && (!(Number(requestedLimit) > 0) || (this._eosLeaseFresh(lease) && !lease.stopRequired));
1699
+ this._publishChargeLimitStatus(identity, entry, { valid: false, requestedW: requestedLimit, reason: 'pending' }, isCurrent)
1700
+ .catch(error => this.log.warn(`Could not publish pending charging limit: ${error.message}`));
1701
+ entry.smartChargingPending = Math.max(0, Number(entry.smartChargingPending) || 0) + 1;
1702
+ const run = async () => {
1703
+ try {
1704
+ return await this._applySmartCharging(
1705
+ identity,
1706
+ requestedLimit,
1707
+ rateUnit,
1708
+ phases,
1709
+ isCurrent,
1710
+ );
1711
+ } finally {
1712
+ entry.smartChargingPending = Math.max(0, (Number(entry.smartChargingPending) || 1) - 1);
1713
+ }
1714
+ };
1715
+ entry.outboundControlTail = Promise.resolve(entry.outboundControlTail).then(run, run);
1716
+ entry.smartChargingTail = entry.outboundControlTail;
1717
+ return entry.outboundControlTail;
1718
+ }
1719
+
1720
+ async _requestFreshData(identity, entry) {
1721
+ if (!entry || !entry.client || entry.refreshInFlight || this.config.activeRefresh === false) return;
1722
+ if ((entry.smartChargingPending || 0) > 0) return;
1723
+ if ((entry.configurationPending || 0) > 0 || entry.configurationRefreshInFlight) return;
1724
+ if ((entry.deferredDepth || 0) > Math.max(10, Number(this.config.maxDeferredTasks) || 250) / 2) return;
1725
+ const now = Date.now();
1726
+ if (entry.refreshSuppressedUntil && now < entry.refreshSuppressedUntil) return;
1727
+ if (entry.refreshSuppressedUntil && now >= entry.refreshSuppressedUntil) {
1728
+ entry.refreshSuppressedUntil = 0;
1729
+ entry.refreshSuppressedReason = '';
1730
+ }
1731
+ if (now < (entry.nextRefreshAt || 0)) return;
1732
+ entry.refreshInFlight = true;
1733
+ entry.lastRefreshAttemptAt = now;
1734
+ if (entry.lastOutboundAt && now - entry.lastOutboundAt < 5000) {
1735
+ entry.nextRefreshAt = now + 10000;
1736
+ entry.refreshInFlight = false;
1737
+ return;
1738
+ }
1739
+ entry.nextRefreshAt = now + Math.max(30, Number(this.config.activeRefreshIntervalSec) || 60) * 1000;
1740
+ const connectorSelection = takeRotatingItems(
1741
+ entry.connectors,
1742
+ entry.refreshConnectorCursor,
1743
+ Math.max(1, Number(this.config.maxConnectorsPerRefresh) || 8),
1744
+ );
1745
+ const connectors = connectorSelection.items;
1746
+ entry.refreshConnectorCursor = connectorSelection.nextCursor;
1747
+ let accepted = 0;
1748
+ let attempted = 0;
1749
+ let skippedFresh = 0;
1750
+ let skippedBackoff = 0;
1751
+ const errors = [];
1752
+ try {
1753
+ await this._setStateFreshAsync(`${identity}.health.refreshLastAttempt`, new Date(now).toISOString(), true, 'health');
1754
+ for (const key of connectors.length ? connectors : ['1:1']) {
1755
+ const [evseId, connectorId] = key.split(':').map(Number);
1756
+ for (const requestedMessage of ['MeterValues', 'StatusNotification']) {
1757
+ if (requestedMessage === 'MeterValues' && this.config.refreshMeterValues === false) continue;
1758
+ if (requestedMessage === 'StatusNotification' && this.config.refreshStatusNotification === false) continue;
1759
+ // MeterValues refresh is driven by active-import power freshness,
1760
+ // not by unrelated counters, SoC or temperature samples.
1761
+ const freshAt = requestedMessage === 'MeterValues' ? entry.lastPowerAt : entry.lastStatusAt;
1762
+ const refreshIntervalMs = Math.max(30, Number(this.config.activeRefreshIntervalSec) || 60) * 1000;
1763
+ if (freshAt && now - freshAt < Math.max(3000, refreshIntervalMs * 0.8)) {
1764
+ skippedFresh++;
1765
+ continue;
1766
+ }
1767
+ if (entry.triggerRetryAt[requestedMessage] && now < entry.triggerRetryAt[requestedMessage]) {
1768
+ skippedBackoff++;
1769
+ continue;
1770
+ }
1771
+ attempted++;
1772
+ try {
1773
+ entry.lastTriggerAt = Date.now();
1774
+ entry.lastTriggerMessage = requestedMessage;
1775
+ const response = await this._callClient(identity, 'TriggerMessage', buildTriggerPayload(entry.proto, requestedMessage, evseId, connectorId), { capture: false });
1776
+ const status = String(response && response.status || 'Unknown');
1777
+ entry.triggerSupport[requestedMessage] = status;
1778
+ if (isTriggerAccepted(response)) {
1779
+ accepted++;
1780
+ entry.triggerRetryAt[requestedMessage] = 0;
1781
+ } else if (isTriggerUnsupported(response)) {
1782
+ entry.triggerRetryAt[requestedMessage] = now + 6 * 60 * 60 * 1000;
1783
+ } else if (isTriggerRejected(response)) {
1784
+ entry.triggerRetryAt[requestedMessage] = now + 10 * 60 * 1000;
1785
+ } else {
1786
+ entry.triggerRetryAt[requestedMessage] = now + 10 * 60 * 1000;
1787
+ errors.push(`${requestedMessage}: unexpected status ${status}`);
1788
+ }
1789
+ } catch (e) {
1790
+ entry.triggerSupport[requestedMessage] = 'error';
1791
+ entry.triggerRetryAt[requestedMessage] = now + 10 * 60 * 1000;
1792
+ errors.push(`${requestedMessage}: ${e && e.message || e}`);
1793
+ }
1794
+ }
1795
+ }
1796
+ if (accepted > 0) entry.lastRefreshSuccessAt = Date.now();
1797
+ entry.lastRefreshError = errors.join('; ');
1798
+ let refreshStatus = 'not-run';
1799
+ if (accepted > 0) refreshStatus = 'requested';
1800
+ else if (errors.length) refreshStatus = 'error/backoff';
1801
+ else if (attempted === 0 && skippedFresh > 0) refreshStatus = 'fresh-no-request';
1802
+ else if (attempted === 0 && skippedBackoff > 0) refreshStatus = 'backoff';
1803
+ else if (attempted > 0) refreshStatus = 'not-accepted/backoff';
1804
+ await this._setStateFreshAsync(`${identity}.health.refreshStatus`, refreshStatus, true, 'health');
1805
+ await this._setStateFreshAsync(`${identity}.health.refreshSupport`, JSON.stringify(entry.triggerSupport), true, 'health');
1806
+ await this._setStateFreshAsync(`${identity}.health.refreshLastError`, entry.lastRefreshError, true, 'health');
1807
+ if (entry.lastRefreshSuccessAt) await this._setStateFreshAsync(`${identity}.health.refreshLastSuccess`, new Date(entry.lastRefreshSuccessAt).toISOString(), true, 'health');
1808
+ } finally {
1809
+ entry.refreshInFlight = false;
1810
+ }
1811
+ }
1812
+
1813
+ async _watchdogCycle() {
1814
+ if (this._watchdogRunning || this._shuttingDown) return;
1815
+ this._watchdogRunning = true;
1816
+ try {
1817
+ const now = Date.now();
1818
+ for (const [identity, entry] of this.runtimeIndex.entries()) {
1819
+ await this.ensureStructure(identity);
1820
+ const connectionHealth = deriveConnectionHealth({
1821
+ now,
1822
+ socketConnected: entry.socketConnected,
1823
+ connectedAt: entry.connectedAt,
1824
+ lastMessageAt: entry.lastMessageAt,
1825
+ lastHeartbeatAt: entry.lastHeartbeatAt,
1826
+ heartbeatIntervalSec: entry.heartbeatIntervalSec,
1827
+ heartbeatTimeoutFactor: this.config.heartbeatTimeoutFactor,
1828
+ activityTimeoutSec: this.config.activityTimeoutSec,
1829
+ });
1830
+ const lastActivityAt = connectionHealth.lastActivityAt;
1831
+ const messageAgeSec = entry.lastMessageAt ? Math.max(0, (now - entry.lastMessageAt) / 1000) : -1;
1832
+ const heartbeatAgeSec = entry.lastHeartbeatAt ? Math.max(0, (now - entry.lastHeartbeatAt) / 1000) : -1;
1833
+ const meterAgeSec = entry.lastMeterAt ? Math.max(0, (now - entry.lastMeterAt) / 1000) : -1;
1834
+ const powerAgeSec = entry.lastPowerAt ? Math.max(0, (now - entry.lastPowerAt) / 1000) : -1;
1835
+ const exportPowerAgeSec = entry.lastExportPowerAt ? Math.max(0, (now - entry.lastExportPowerAt) / 1000) : -1;
1836
+ const currentAgeSec = entry.lastCurrentAt ? Math.max(0, (now - entry.lastCurrentAt) / 1000) : -1;
1837
+ const statusAgeSec = entry.lastStatusAt ? Math.max(0, (now - entry.lastStatusAt) / 1000) : -1;
1838
+ const socAgeSec = entry.lastSocAt ? Math.max(0, (now - entry.lastSocAt) / 1000) : -1;
1839
+ const socketConnected = connectionHealth.socketConnected;
1840
+ const activityFresh = connectionHealth.activityFresh;
1841
+ const online = connectionHealth.online;
1842
+ const heartbeatAlive = connectionHealth.heartbeatAlive;
1843
+ const telemetryMaxAgeSec = Math.max(15, Number(this.config.telemetryMaxAgeSec) || 90);
1844
+ const meterFresh = socketConnected && entry.lastMeterAt > 0 && meterAgeSec <= telemetryMaxAgeSec;
1845
+ const powerFresh = socketConnected && entry.lastPowerAt > 0 && powerAgeSec <= telemetryMaxAgeSec;
1846
+ const exportPowerFresh = socketConnected && entry.lastExportPowerAt > 0 && exportPowerAgeSec <= telemetryMaxAgeSec;
1847
+ const currentFresh = socketConnected && entry.lastCurrentAt > 0 && currentAgeSec <= telemetryMaxAgeSec;
1848
+ const socFresh = socketConnected && entry.lastSocAt > 0 && socAgeSec <= Math.max(30, Number(this.config.socMaxAgeSec) || 300);
1849
+ // safeZeroAt is cleared immediately by a charging event or a
1850
+ // contradictory non-zero actual-flow sample. Therefore a previously
1851
+ // confirmed idle/end state remains valid across later counter, SoC or
1852
+ // zero-only MeterValues messages.
1853
+ const safeZero = socketConnected && entry.safeZeroAt > 0;
1854
+ // EOS data freshness is tied to the canonical active-import power or a
1855
+ // protocol-derived safe zero. Heartbeat/current/reactive power alone do
1856
+ // not make an old power datapoint suitable for closed-loop control.
1857
+ const dataFresh = dataFreshForEos(online, powerFresh, safeZero);
1858
+ let staleReason = '';
1859
+ if (!socketConnected) staleReason = 'socket-disconnected';
1860
+ else if (!online) staleReason = 'no-ocpp-activity';
1861
+ else if (!dataFresh && exportPowerFresh) staleReason = 'export-power-only-no-import-power';
1862
+ else if (!dataFresh && !entry.lastPowerAt) staleReason = 'awaiting-power-or-idle-status';
1863
+ else if (!dataFresh) staleReason = 'power-values-stale';
1864
+
1865
+ // ioBroker's conventional info.connection flag represents the real
1866
+ // transport connection. Activity and heartbeat quality stay in health.*
1867
+ // so a delayed Heartbeat cannot make EOS believe the socket vanished.
1868
+ await this._setStateFreshAsync(`${identity}.info.connection`, socketConnected, true, 'status');
1869
+ await this._setStateFreshAsync(`${identity}.info.socketConnected`, socketConnected, true, 'status');
1870
+ await this._setStateFreshAsync(`${identity}.health.online`, online, true, 'health');
1871
+ await this._setStateFreshAsync(`${identity}.health.activityFresh`, activityFresh, true, 'health');
1872
+ await this._setStateFreshAsync(`${identity}.health.socketConnected`, socketConnected, true, 'health');
1873
+ await this._setStateFreshAsync(`${identity}.health.heartbeatAlive`, heartbeatAlive, true, 'health');
1874
+ await this._setStateFreshAsync(`${identity}.health.meterFresh`, meterFresh, true, 'health');
1875
+ await this._setStateFreshAsync(`${identity}.health.powerFresh`, powerFresh, true, 'health');
1876
+ await this._setStateFreshAsync(`${identity}.health.exportPowerFresh`, exportPowerFresh, true, 'health');
1877
+ await this._setStateFreshAsync(`${identity}.health.currentFresh`, currentFresh, true, 'health');
1878
+ await this._setStateFreshAsync(`${identity}.health.dataFresh`, dataFresh, true, 'health');
1879
+ await this._setStateFreshAsync(`${identity}.health.socFresh`, socFresh, true, 'health');
1880
+ await this._setStateFreshAsync(`${identity}.health.staleReason`, staleReason, true, 'health');
1881
+ await this._setStateFreshAsync(`${identity}.health.messageAgeSec`, Math.round(messageAgeSec), true, 'health');
1882
+ await this._setStateFreshAsync(`${identity}.health.activityAgeSec`, lastActivityAt ? Math.round(Math.max(0, (now - lastActivityAt) / 1000)) : -1, true, 'health');
1883
+ await this._setStateFreshAsync(`${identity}.health.activityTimeoutSec`, Math.round(connectionHealth.activityWindowMs / 1000), true, 'health');
1884
+ await this._setStateFreshAsync(`${identity}.health.heartbeatTimeoutSec`, Math.round(connectionHealth.heartbeatWindowMs / 1000), true, 'health');
1885
+ await this._setStateFreshAsync(`${identity}.health.heartbeatAgeSec`, Math.round(heartbeatAgeSec), true, 'health');
1886
+ await this._setStateFreshAsync(`${identity}.health.meterAgeSec`, Math.round(meterAgeSec), true, 'health');
1887
+ await this._setStateFreshAsync(`${identity}.health.powerAgeSec`, Math.round(powerAgeSec), true, 'health');
1888
+ await this._setStateFreshAsync(`${identity}.health.exportPowerAgeSec`, Math.round(exportPowerAgeSec), true, 'health');
1889
+ await this._setStateFreshAsync(`${identity}.health.currentAgeSec`, Math.round(currentAgeSec), true, 'health');
1890
+ await this._setStateFreshAsync(`${identity}.health.statusAgeSec`, Math.round(statusAgeSec), true, 'health');
1891
+ await this._setStateFreshAsync(`${identity}.health.socAgeSec`, Math.round(socAgeSec), true, 'health');
1892
+ await this._setStateFreshAsync(`${identity}.health.safeZeroApplied`, safeZero, true, 'health');
1893
+ await this._setStateFreshAsync(`${identity}.health.safeZeroReason`, entry.safeZeroReason || '', true, 'health');
1894
+ await this._setStateFreshAsync(`${identity}.health.lastSeenMs`, entry.lastMessageAt || 0, true, 'health');
1895
+ await this._setStateFreshAsync(`${identity}.health.lastSeen`, entry.lastMessageAt ? new Date(entry.lastMessageAt).toISOString() : '', true, 'health');
1896
+ await this._setStateFreshAsync(`${identity}.health.lastAction`, entry.lastAction || '', true, 'health');
1897
+ await this._setStateFreshAsync(`${identity}.health.lastHeartbeatMs`, entry.lastHeartbeatAt || 0, true, 'health');
1898
+ await this._setStateFreshAsync(`${identity}.health.heartbeat`, entry.lastHeartbeatAt ? new Date(entry.lastHeartbeatAt).toISOString() : '', true, 'health');
1899
+ await this._setStateFreshAsync(`${identity}.info.lastHeartbeat`, entry.lastHeartbeatAt ? new Date(entry.lastHeartbeatAt).toISOString() : '', true, 'status');
1900
+ if (entry.lastBootAt) await this._setStateFreshAsync(`${identity}.health.lastBoot`, new Date(entry.lastBootAt).toISOString(), true, 'health');
1901
+ await this._setStateFreshAsync(`${identity}.health.reconnectCount`, entry.reconnectCount || 0, true, 'health');
1902
+ await this._setStateFreshAsync(`${identity}.health.disconnectCount`, entry.disconnectCount || 0, true, 'health');
1903
+ await this._setStateFreshAsync(`${identity}.health.queueDepth`, entry.deferredDepth || 0, true, 'health');
1904
+ await this._setStateFreshAsync(`${identity}.health.queueMaxDepth`, entry.deferredMaxDepth || 0, true, 'health');
1905
+ await this._setStateFreshAsync(`${identity}.health.queueDropped`, entry.deferredDropped || 0, true, 'health');
1906
+ await this._setStateFreshAsync(`${identity}.health.queueErrors`, entry.deferredErrors || 0, true, 'health');
1907
+ await this._setStateFreshAsync(`${identity}.health.queueLastError`, entry.lastDeferredError || '', true, 'health');
1908
+ await this._setStateFreshAsync(`${identity}.health.outboundCallCount`, entry.outboundCallCount || 0, true, 'health');
1909
+ await this._setStateFreshAsync(`${identity}.health.outboundErrorCount`, entry.outboundErrorCount || 0, true, 'health');
1910
+ await this._setStateFreshAsync(`${identity}.health.lastOutboundMethod`, entry.lastOutboundMethod || '', true, 'health');
1911
+ await this._setStateFreshAsync(`${identity}.health.lastOutboundAt`, entry.lastOutboundAt ? new Date(entry.lastOutboundAt).toISOString() : '', true, 'health');
1912
+ await this._setStateFreshAsync(`${identity}.health.refreshSuppressedUntil`, entry.refreshSuppressedUntil ? new Date(entry.refreshSuppressedUntil).toISOString() : '', true, 'health');
1913
+ await this._setStateFreshAsync(`${identity}.health.refreshSuppressedReason`, entry.refreshSuppressedReason || '', true, 'health');
1914
+ await this._setStateFreshAsync(`${identity}.health.refreshRelatedDisconnects`, entry.refreshRelatedDisconnects || 0, true, 'health');
1915
+
1916
+ if (entry.configurationRefreshInFlight
1917
+ && entry.configurationReportDeadlineAt
1918
+ && now >= entry.configurationReportDeadlineAt) {
1919
+ entry.configurationRefreshInFlight = false;
1920
+ entry.configurationPendingRequestId = 0;
1921
+ entry.configurationReportDeadlineAt = 0;
1922
+ entry.configurationInventorySeen = new Set();
1923
+ entry.configurationReportSequences = new Set();
1924
+ await this._recordConfigurationStatus(identity, {
1925
+ status: 'timeout',
1926
+ error: 'Timed out waiting for the OCPP configuration report',
1927
+ reportInProgress: false,
1928
+ });
1929
+ }
1930
+
1931
+ const republishMs = Math.max(5, Number(this.config.stateRefreshIntervalSec) || 10) * 1000;
1932
+ if (online && now - (entry.lastStateRepublishAt || 0) >= republishMs) {
1933
+ entry.republishCursor = await this._touchCachedStates(identity, safeZero, now, entry.republishCursor || 0);
1934
+ entry.lastStateRepublishAt = now;
1935
+ await this._setStateFreshAsync(`${identity}.health.lastRepublish`, new Date(now).toISOString(), true, 'health');
1936
+ }
1937
+ if (online && entry.booted) {
1938
+ // Active refresh may wait for a slow or non-compliant station. Do not
1939
+ // block health processing for this or any other connected station.
1940
+ this._requestFreshData(identity, entry).catch((e) => {
1941
+ this.log.warn(`Active refresh failed for ${identity}: ${e && e.message || e}`);
1942
+ });
1943
+ this._maybeAutoRefreshConfiguration(identity, entry, now).catch((e) => {
1944
+ this.log.warn(`Configuration auto-refresh failed for ${identity}: ${e && e.message || e}`);
1945
+ });
1946
+ }
1947
+ }
1948
+ } catch (e) {
1949
+ this.log.warn(`NexoWatt OCPP freshness watchdog failed: ${e && e.stack || e}`);
1950
+ } finally {
1951
+ this._watchdogRunning = false;
1952
+ }
1953
+ }
1954
+
1955
+ _looksLikeIsoTime(s) {
1956
+ if (typeof s !== 'string') return false;
1957
+ // very lightweight ISO-8601 date-time heuristic
1958
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(s);
1959
+ }
1960
+
1961
+ async _setObjectNotExistsCached(id, obj) {
1962
+ if (this._dpObjCache.has(id)) return;
1963
+ await this.setObjectNotExistsAsync(id, obj);
1964
+ this._dpObjCache.add(id);
1965
+ }
1966
+
1967
+ _flattenJson(value, out, path, depth, maxDepth, maxArray) {
1968
+ if (depth > maxDepth) {
1969
+ out.push({ path, value: JSON.stringify(value), kind: 'json' });
1970
+ return;
1971
+ }
1972
+ if (value === null || value === undefined) {
1973
+ out.push({ path, value: null, kind: 'null' });
1974
+ return;
1975
+ }
1976
+ const t = typeof value;
1977
+ if (t === 'string' || t === 'number' || t === 'boolean') {
1978
+ out.push({ path, value, kind: t });
1979
+ return;
1980
+ }
1981
+ if (Array.isArray(value)) {
1982
+ const len = value.length;
1983
+ const n = Math.min(len, maxArray);
1984
+ for (let i = 0; i < n; i++) {
1985
+ this._flattenJson(value[i], out, path.concat(String(i)), depth + 1, maxDepth, maxArray);
1986
+ }
1987
+ if (len > maxArray) {
1988
+ out.push({ path: path.concat('_truncated'), value: `array(${len}) truncated to ${maxArray}`, kind: 'string' });
1989
+ }
1990
+ return;
1991
+ }
1992
+ if (t === 'object') {
1993
+ for (const [k, v] of Object.entries(value)) {
1994
+ this._flattenJson(v, out, path.concat(String(k)), depth + 1, maxDepth, maxArray);
1995
+ }
1996
+ return;
1997
+ }
1998
+ // fallback
1999
+ out.push({ path, value: String(value), kind: 'string' });
2000
+ }
2001
+
2002
+ async _ensureAdvancedStructure(identity) {
2003
+ if (this._advancedStructureReady.has(identity)) return;
2004
+ await this._setObjectNotExistsCached(`${identity}.advanced`, {
2005
+ type: 'channel',
2006
+ common: { name: { en: 'Advanced OCPP diagnostics', de: 'Erweiterte OCPP-Diagnose' } },
2007
+ native: {},
2008
+ });
2009
+ const states = {
2010
+ lastIncoming: ['string', 'json', ''],
2011
+ lastOutgoing: ['string', 'json', ''],
2012
+ lastIncomingAction: ['string', 'text', ''],
2013
+ lastOutgoingAction: ['string', 'text', ''],
2014
+ lastProtocol: ['string', 'text', ''],
2015
+ lastTimestamp: ['string', 'value.time', ''],
2016
+ incomingCount: ['number', 'value', 0],
2017
+ outgoingCount: ['number', 'value', 0],
2018
+ lastMessageBytes: ['number', 'value', 0],
2019
+ lastMessageTruncated: ['boolean', 'indicator', false],
2020
+ deviceModelReport: ['string', 'json', ''],
2021
+ deviceModelReportAt: ['string', 'value.time', ''],
2022
+ };
2023
+ for (const [key, [type, role, def]] of Object.entries(states)) {
2024
+ await this._setObjectNotExistsCached(`${identity}.advanced.${key}`, {
2025
+ type: 'state',
2026
+ common: { name: key, type, role, read: true, write: false, def },
2027
+ native: {},
2028
+ });
2029
+ }
2030
+ this._advancedStructureReady.add(identity);
2031
+ }
2032
+
2033
+ async captureOcppPayload(identity, protocol, direction, action, payload) {
2034
+ if (this.config.captureRawMessages !== true) return;
2035
+ await this._ensureAdvancedStructure(identity);
2036
+ const dir = String(direction || '').toLowerCase() === 'out' ? 'Outgoing' : 'Incoming';
2037
+ const countKey = dir === 'Outgoing' ? 'outgoingCount' : 'incomingCount';
2038
+ const rawKey = dir === 'Outgoing' ? 'lastOutgoing' : 'lastIncoming';
2039
+ const actionKey = dir === 'Outgoing' ? 'lastOutgoingAction' : 'lastIncomingAction';
2040
+ const counterMapKey = `${identity}|advanced|${countKey}`;
2041
+ const count = (this._dpCounts.get(counterMapKey) || 0) + 1;
2042
+ this._dpCounts.set(counterMapKey, count);
2043
+
2044
+ let raw;
2045
+ try { raw = JSON.stringify(payload ?? {}); } catch (error) { raw = JSON.stringify({ serializationError: String(error && error.message || error) }); }
2046
+ const bytes = Buffer.byteLength(raw, 'utf8');
2047
+ const maxBytes = Math.max(4096, Number(this.config.maxRawPayloadBytes) || 65536);
2048
+ let truncated = false;
2049
+ if (bytes > maxBytes) {
2050
+ raw = `${raw.slice(0, maxBytes)}…[truncated ${bytes - maxBytes} bytes]`;
2051
+ truncated = true;
2052
+ }
2053
+ const now = new Date().toISOString();
2054
+ await this._setStateFreshAsync(`${identity}.advanced.${rawKey}`, raw, true, 'payload');
2055
+ await this._setStateFreshAsync(`${identity}.advanced.${actionKey}`, String(action || ''), true, 'payload');
2056
+ await this._setStateFreshAsync(`${identity}.advanced.lastProtocol`, String(protocol || ''), true, 'payload');
2057
+ await this._setStateFreshAsync(`${identity}.advanced.lastTimestamp`, now, true, 'payload');
2058
+ await this._setStateFreshAsync(`${identity}.advanced.${countKey}`, count, true, 'payload');
2059
+ await this._setStateFreshAsync(`${identity}.advanced.lastMessageBytes`, bytes, true, 'payload');
2060
+ await this._setStateFreshAsync(`${identity}.advanced.lastMessageTruncated`, truncated, true, 'payload');
2061
+ }
2062
+
2063
+ async ingestNotifyReport(identity, protocol, params) {
2064
+ const reportData = Array.isArray(params && params.reportData) ? params.reportData : [];
2065
+ if (this.config.captureDeviceModelReport === true) {
2066
+ await this._ensureAdvancedStructure(identity);
2067
+ let raw = '';
2068
+ try {
2069
+ raw = JSON.stringify(redactConfigurationReport(params || {}));
2070
+ } catch (error) {
2071
+ raw = JSON.stringify({ serializationError: String(error && error.message || error) });
2072
+ }
2073
+ const maxBytes = Math.max(4096, Number(this.config.maxRawPayloadBytes) || 65536);
2074
+ if (Buffer.byteLength(raw, 'utf8') > maxBytes) raw = `${raw.slice(0, maxBytes)}…[truncated]`;
2075
+ await this._setStateFreshAsync(`${identity}.advanced.deviceModelReport`, raw, true, 'payload');
2076
+ await this._setStateFreshAsync(`${identity}.advanced.deviceModelReportAt`, new Date().toISOString(), true, 'payload');
2077
+ }
2078
+
2079
+ await this.ensureStructure(identity);
2080
+ const entry = this.runtimeIndex.get(identity);
2081
+ const requestId = Number.isFinite(Number(params && params.requestId)) ? Number(params.requestId) : 0;
2082
+ const seqNo = Number.isFinite(Number(params && params.seqNo)) ? Number(params.seqNo) : 0;
2083
+ const tbc = params && params.tbc === true;
2084
+ const configurationReportMatches = !!entry
2085
+ && entry.configurationRefreshInFlight
2086
+ && entry.configurationPendingRequestId > 0
2087
+ && entry.configurationPendingRequestId === requestId;
2088
+ let duplicateConfigurationSequence = false;
2089
+ if (configurationReportMatches) {
2090
+ if (entry.configurationReportRequestId !== requestId) {
2091
+ entry.configurationReportCount = 0;
2092
+ entry.configurationInventorySeen = new Set();
2093
+ entry.configurationReportSequences = new Set();
2094
+ }
2095
+ entry.configurationReportRequestId = requestId;
2096
+ if (!(entry.configurationReportSequences instanceof Set)) entry.configurationReportSequences = new Set();
2097
+ duplicateConfigurationSequence = entry.configurationReportSequences.has(seqNo);
2098
+ entry.configurationReportSequences.add(seqNo);
2099
+ if (!(entry.configurationInventorySeen instanceof Set)) entry.configurationInventorySeen = new Set();
2100
+ }
2101
+
2102
+ for (const rd of reportData) {
2103
+ const component = rd && rd.component;
2104
+ const variable = rd && rd.variable;
2105
+ if (!component || !variable) continue;
2106
+ const componentName = String(component.name || '').toLowerCase();
2107
+ const variableName = String(variable.name || '').toLowerCase();
2108
+ const characteristics = rd.variableCharacteristics || {};
2109
+ const attrs = Array.isArray(rd.variableAttribute) ? rd.variableAttribute : [];
2110
+
2111
+ for (const attribute of attrs) {
2112
+ const attributeType = String(attribute && attribute.type || 'Actual');
2113
+ const hasRawValue = !!attribute && Object.prototype.hasOwnProperty.call(attribute, 'value') && attribute.value !== undefined;
2114
+ const parsed = parseDeviceModelValue(attribute && attribute.value, characteristics.dataType || 'string');
2115
+ const hasConfirmedValue = hasRawValue && parsed.val !== undefined;
2116
+
2117
+ // A compact configuration inventory is created only for the explicit
2118
+ // ConfigurationInventory request sent by this adapter. Other Device
2119
+ // Model reports must not unexpectedly grow the object tree.
2120
+ if (configurationReportMatches && !duplicateConfigurationSequence) {
2121
+ const stateKey = configurationStateKey2(component, variable, attributeType);
2122
+ // Count distinct flat datapoints through the Set itself. Some
2123
+ // stations repeat an item in multipart or retried report chunks.
2124
+ entry.configurationInventorySeen.add(stateKey);
2125
+ await this._upsertConfigurationState(identity, {
2126
+ kind: 'deviceModel',
2127
+ protocol,
2128
+ canonicalKey: canonicalDeviceModelKey(component, variable, attributeType),
2129
+ component: cloneOcppReference(component),
2130
+ variable: cloneOcppReference(variable),
2131
+ attributeType,
2132
+ mutability: String(attribute && attribute.mutability || 'ReadOnly'),
2133
+ persistent: attribute && attribute.persistent === true,
2134
+ constant: attribute && attribute.constant === true,
2135
+ dataType: String(characteristics.dataType || 'string'),
2136
+ stateType: parsed.type,
2137
+ unit: characteristics.unit,
2138
+ minLimit: characteristics.minLimit,
2139
+ maxLimit: characteristics.maxLimit,
2140
+ valuesList: characteristics.valuesList,
2141
+ supportsMonitoring: characteristics.supportsMonitoring,
2142
+ inventoryPending: true,
2143
+ stateKey,
2144
+ }, parsed.val, hasConfirmedValue);
2145
+ }
2146
+
2147
+ // Mirror ConnectedEV.StateOfCharge into the compact EOS measurements,
2148
+ // regardless of which Device Model report carried the value.
2149
+ if (componentName === 'connectedev'
2150
+ && variableName === 'stateofcharge'
2151
+ && attributeType.toLowerCase() === 'actual'
2152
+ && typeof parsed.val === 'number'
2153
+ && Number.isFinite(parsed.val)) {
2154
+ const socId = await this.ensureMeasurement(identity, 'socPercent', '%', {
2155
+ name: { en: 'Vehicle state of charge', de: 'Fahrzeug-Ladezustand' },
2156
+ role: 'value.battery',
2157
+ });
2158
+ await this._publishScopedSoc(identity, Number(rd.component?.evse?.id), Number(rd.component?.evse?.connectorId ?? 0), parsed.val);
2159
+ // scoped SoC already published
2160
+ }
2161
+ }
2162
+ }
2163
+
2164
+ if (!configurationReportMatches) return;
2165
+
2166
+ entry.configurationReportCount = entry.configurationInventorySeen.size;
2167
+ if (!tbc) {
2168
+ await this._finalizeConfigurationInventoryStates(identity, entry.configurationInventorySeen, protocol);
2169
+ await this._retireMissingConfigurationStates(identity, entry.configurationInventorySeen, protocol);
2170
+ await this._updateConfigurationIndex(identity);
2171
+ entry.configurationRefreshInFlight = false;
2172
+ entry.configurationPendingRequestId = 0;
2173
+ entry.configurationReportDeadlineAt = 0;
2174
+ }
2175
+ await this._recordConfigurationStatus(identity, {
2176
+ status: tbc ? 'receiving-report' : 'ready',
2177
+ error: '',
2178
+ count: entry.configurationReportCount,
2179
+ reportInProgress: tbc,
2180
+ requestId,
2181
+ lastSequence: seqNo,
2182
+ lastRefresh: !tbc ? new Date().toISOString() : undefined,
2183
+ });
2184
+ }
2185
+
2186
+ async ensureAliases(identity) {
2187
+ if (this._aliasDone.has(identity)) return;
2188
+ const publicAliasBase = /^ocpp21\.\d+$/.test(this.namespace) ? `alias.0.nexowatt.ocpp.${this.instance}` : `alias.0.nexowatt.${this.namespace}`;
2189
+ const technicalAliasBase = `alias.0.${this.namespace}`;
2190
+ const ancestors = (base) => base.split('.').slice(2).map((_, i, parts) => [`alias.0.${parts.slice(0, i + 1).join('.')}`, 'NexoWatt OCPP']);
2191
+ const roots = [{ root: `${publicAliasBase}.${identity}`, parents: ancestors(publicAliasBase) }];
2192
+ if (this.config.createTechnicalAliases === true) roots.push({ root: `${technicalAliasBase}.${identity}`, parents: ancestors(technicalAliasBase) });
2193
+
2194
+ const connector1 = this._connectorBase(identity, 1, 1);
2195
+ const aliases = [
2196
+ ['connected', `${identity}.info.connection`, 'boolean', 'indicator.connected', false],
2197
+ ['socketConnected', `${identity}.info.socketConnected`, 'boolean', 'indicator.connected', false],
2198
+ ['activityFresh', `${identity}.health.activityFresh`, 'boolean', 'indicator.connected', false],
2199
+ ['heartbeatAlive', `${identity}.health.heartbeatAlive`, 'boolean', 'indicator.connected', false],
2200
+ ['dataFresh', `${identity}.health.dataFresh`, 'boolean', 'indicator', false],
2201
+ ['powerFresh', `${identity}.health.powerFresh`, 'boolean', 'indicator', false],
2202
+ ['socFresh', `${identity}.health.socFresh`, 'boolean', 'indicator', false],
2203
+ ['status', `${identity}.info.status`, 'string', 'indicator.status', false],
2204
+ ['protocol', `${identity}.info.protocol`, 'string', 'text', false],
2205
+ ['rfid', `${identity}.info.rfid`, 'string', 'text', false],
2206
+ ['powerW', `${identity}.measurements.powerW`, 'number', 'value.power', false],
2207
+ ['powerExportW', `${identity}.measurements.powerExportW`, 'number', 'value.power', false],
2208
+ ['currentTotalA', `${identity}.measurements.currentA`, 'number', 'value.current', false],
2209
+ ['energyWh', `${identity}.measurements.energyWh`, 'number', 'value.energy', false],
2210
+ ['energyKWh', `${identity}.measurements.energyKWh`, 'number', 'value.energy', false],
2211
+ ['soc', `${identity}.measurements.socPercent`, 'number', 'value.battery', false],
2212
+ ['voltageL1', `${identity}.measurements.voltageVL1`, 'number', 'value.voltage', false],
2213
+ ['voltageL2', `${identity}.measurements.voltageVL2`, 'number', 'value.voltage', false],
2214
+ ['voltageL3', `${identity}.measurements.voltageVL3`, 'number', 'value.voltage', false],
2215
+ ['currentL1', `${identity}.measurements.currentAL1`, 'number', 'value.current', false],
2216
+ ['currentL2', `${identity}.measurements.currentAL2`, 'number', 'value.current', false],
2217
+ ['currentL3', `${identity}.measurements.currentAL3`, 'number', 'value.current', false],
2218
+ ['powerL1', `${identity}.measurements.powerWL1`, 'number', 'value.power', false],
2219
+ ['powerL2', `${identity}.measurements.powerWL2`, 'number', 'value.power', false],
2220
+ ['powerL3', `${identity}.measurements.powerWL3`, 'number', 'value.power', false],
2221
+ ['frequencyHz', `${identity}.measurements.frequencyHz`, 'number', 'value.frequency', false],
2222
+ ['txActive', `${identity}.transactions.transactionActive`, 'boolean', 'indicator.working', false],
2223
+ ['chargingState', `${identity}.transactions.chargingState`, 'string', 'indicator.status', false],
2224
+ ['txId', `${identity}.transactions.lastId`, 'string', 'text', false],
2225
+ ['txEnergyKWh', `${identity}.transactions.lastTransactionConsumption_kWh`, 'number', 'value.energy', false],
2226
+ ['chargeLimit', `${identity}.control.chargeLimit`, 'number', 'value.power', true],
2227
+ ['numberPhases', `${identity}.control.numberOfPhases`, 'number', 'value', true],
2228
+ ['availability', `${identity}.control.availability`, 'boolean', 'switch.power', true],
2229
+ ];
2230
+ if (this.config.connectorDetails === true) {
2231
+ aliases.push(
2232
+ ['connector1Status', `${connector1}.status`, 'string', 'indicator.status', false],
2233
+ ['connector1EnergyKWh', `${connector1}.energyKWh`, 'number', 'value.energy', false],
2234
+ );
2235
+ }
2236
+
2237
+ try {
2238
+ for (const definition of roots) {
2239
+ for (const [parent, name] of definition.parents) {
2240
+ await this.setForeignObjectNotExistsAsync(parent, { type: 'channel', common: { name }, native: {} });
2241
+ }
2242
+ await this.setForeignObjectNotExistsAsync(definition.root, {
2243
+ type: 'channel',
2244
+ common: { name: this._stateToRawIdentity.get(identity) || identity },
2245
+ native: {},
2246
+ });
2247
+ for (const [name, target, type, role, write] of aliases) {
2248
+ const aliasId = `${definition.root}.${name}`;
2249
+ const object = {
2250
+ type: 'state',
2251
+ common: { name, type, role, read: true, write: !!write, alias: { id: `${this.namespace}.${target}` } },
2252
+ native: {},
2253
+ };
2254
+ await this.setForeignObjectNotExistsAsync(aliasId, object);
2255
+ // Existing aliases from 0.3.x pointed to the old deep tree. Update
2256
+ // them in place so EOS mappings continue to work after migration.
2257
+ if (typeof this.extendForeignObjectAsync === 'function') await this.extendForeignObjectAsync(aliasId, object);
2258
+ }
2259
+ // Existing connector aliases are preserved.
2260
+ }
2261
+ this._aliasDone.add(identity);
2262
+ } catch (error) {
2263
+ this.log.debug(`Alias creation will be retried (${identity}): ${error}`);
2264
+ }
2265
+ }
2266
+
2267
+ _connectorBase(identity, evseId = 1, connectorId = 1) {
2268
+ const evse = Math.max(0, Math.trunc(Number(evseId) || 0));
2269
+ const connector = Math.max(0, Math.trunc(Number(connectorId) || 0));
2270
+ return `${identity}.connectors.${evse}_${connector}`;
2271
+ }
2272
+
2273
+ async ensureMeasurement(identity, key, unit, options = {}) {
2274
+ const cleanKey = sanitizeFlatKey(key);
2275
+ await this._setObjectNotExistsCached(`${identity}.measurements`, {
2276
+ type: 'channel',
2277
+ common: { name: { en: 'Measurements', de: 'Messwerte' } },
2278
+ native: {},
2279
+ });
2280
+ const id = `${identity}.measurements.${cleanKey}`;
2281
+ await this._setObjectNotExistsCached(id, {
2282
+ type: 'state',
2283
+ common: measurementCommon(cleanKey, unit, options),
2284
+ native: {},
2285
+ });
2286
+ return id;
2287
+ }
2288
+
2289
+ async ensureTextMeasurement(identity, key, name, role = 'text') {
2290
+ const cleanKey = sanitizeFlatKey(key);
2291
+ await this._setObjectNotExistsCached(`${identity}.measurements`, {
2292
+ type: 'channel',
2293
+ common: { name: { en: 'Measurements', de: 'Messwerte' } },
2294
+ native: {},
2295
+ });
2296
+ const id = `${identity}.measurements.${cleanKey}`;
2297
+ await this._setObjectNotExistsCached(id, {
2298
+ type: 'state',
2299
+ common: { name: name || cleanKey, type: 'string', role, read: true, write: false, def: '' },
2300
+ native: {},
2301
+ });
2302
+ return id;
2303
+ }
2304
+
2305
+ async ensureConnectorStructure(identity, evseId = 1, connectorId = 1) {
2306
+ if (this.config.connectorDetails !== true) return undefined;
2307
+ const evse = Math.max(0, Math.trunc(Number(evseId) || 0));
2308
+ const connector = Math.max(0, Math.trunc(Number(connectorId) || 0));
2309
+ const connectorKey = `${identity}|${evse}|${connector}`;
2310
+ const base = this._connectorBase(identity, evse, connector);
2311
+ if (this._connectorStructureReady.has(connectorKey)) return base;
2312
+
2313
+ await this._setObjectNotExistsCached(`${identity}.connectors`, {
2314
+ type: 'channel',
2315
+ common: { name: { en: 'Connectors', de: 'Ladeanschlüsse' } },
2316
+ native: {},
2317
+ });
2318
+ await this._setObjectNotExistsCached(base, {
2319
+ type: 'channel',
2320
+ common: { name: { en: `EVSE ${evse}, connector ${connector}`, de: `EVSE ${evse}, Anschluss ${connector}` } },
2321
+ native: { evseId: evse, connectorId: connector },
2322
+ });
2323
+
2324
+ const states = {
2325
+ status: { name: { en: 'Connector status', de: 'Anschlussstatus' }, type: 'string', role: 'indicator.status', def: '' },
2326
+ errorCode: { name: { en: 'Error code', de: 'Fehlercode' }, type: 'string', role: 'text', def: '' },
2327
+ info: { name: { en: 'Status information', de: 'Statusinformation' }, type: 'string', role: 'text', def: '' },
2328
+ vendorErrorCode: { name: { en: 'Vendor error code', de: 'Hersteller-Fehlercode' }, type: 'string', role: 'text', def: '' },
2329
+ vendorId: { name: { en: 'Vendor identifier', de: 'Herstellerkennung' }, type: 'string', role: 'text', def: '' },
2330
+ lastUpdate: { name: { en: 'Last connector update', de: 'Letzte Anschlussaktualisierung' }, type: 'string', role: 'value.time', def: '' },
2331
+ energyWh: { name: { en: 'Charged energy total', de: 'Geladene Energie gesamt' }, type: 'number', role: 'value.energy', unit: 'Wh', def: 0 },
2332
+ energyKWh: { name: { en: 'Charged energy total', de: 'Geladene Energie gesamt' }, type: 'number', role: 'value.energy', unit: 'kWh', def: 0 },
2333
+ };
2334
+ for (const [key, common] of Object.entries(states)) {
2335
+ await this._setObjectNotExistsCached(`${base}.${key}`, {
2336
+ type: 'state',
2337
+ common: { ...common, read: true, write: false },
2338
+ native: {},
2339
+ });
2340
+ }
2341
+ this._connectorStructureReady.add(connectorKey);
2342
+ return base;
2343
+ }
2344
+
2345
+ async _cleanupDisabledConnectorDetails(identity) {
2346
+ if (this.config.connectorDetails === true || this._connectorCleanupDone.has(identity)) return;
2347
+ if (typeof this.delObjectAsync === 'function') {
2348
+ try {
2349
+ const branchId = `${identity}.connectors`;
2350
+ const exists = typeof this.getObjectAsync === 'function' ? await this.getObjectAsync(branchId) : true;
2351
+ if (exists) {
2352
+ await this.delObjectAsync(branchId, { recursive: true });
2353
+ this.log.info(`Optional connector detail branch removed for ${identity}; station-level measurements remain available.`);
2354
+ }
2355
+ } catch (error) {
2356
+ this.log.debug(`Connector detail cleanup skipped (${identity}): ${error && error.message || error}`);
2357
+ }
2358
+ }
2359
+ for (const key of [...this._connectorStructureReady]) if (key.startsWith(`${identity}|`)) this._connectorStructureReady.delete(key);
2360
+ this._connectorCleanupDone.add(identity);
2361
+ }
2362
+
2363
+ async _cleanupLegacySubfolders(identity) {
2364
+ if (this.config.cleanupLegacyObjects === false || this._legacySubfolderCleanupDone.has(identity)) return;
2365
+ if (typeof this.delObjectAsync !== 'function') {
2366
+ this._legacySubfolderCleanupDone.add(identity);
2367
+ return;
2368
+ }
2369
+
2370
+ const candidates = [
2371
+ { id: `${identity}.control.hardReset`, keepState: true },
2372
+ { id: `${identity}.control.softReset`, keepState: true },
2373
+ { id: `${identity}.control.rpc`, keepState: false },
2374
+ { id: `${identity}.control.requestStartTransaction`, keepState: false },
2375
+ { id: `${identity}.control.requestStopTransaction`, keepState: false },
2376
+ { id: `${identity}.transactions.last`, keepState: false },
2377
+ ];
2378
+
2379
+ for (const candidate of candidates) {
2380
+ try {
2381
+ let object;
2382
+ if (typeof this.getObjectAsync === 'function') object = await this.getObjectAsync(candidate.id);
2383
+ else if (typeof this.getForeignObjectAsync === 'function') object = await this.getForeignObjectAsync(`${this.namespace}.${candidate.id}`);
2384
+ if (!object) continue;
2385
+ if (candidate.keepState && object.type === 'state') continue;
2386
+ await this.delObjectAsync(candidate.id, { recursive: true });
2387
+ this.log.info(`Removed obsolete OCPP subfolder ${candidate.id}.`);
2388
+ } catch (error) {
2389
+ this.log.debug(`Legacy OCPP subfolder cleanup skipped (${candidate.id}): ${error && error.message || error}`);
2390
+ }
2391
+ }
2392
+ this._legacySubfolderCleanupDone.add(identity);
2393
+ }
2394
+
2395
+ async _cleanupKnownMeasurementAliases(identity) {
2396
+ if (this.config.cleanupLegacyObjects === false || this._measurementAliasCleanupDone.has(identity)) return;
2397
+ if (typeof this.delObjectAsync !== 'function') {
2398
+ this._measurementAliasCleanupDone.add(identity);
2399
+ return;
2400
+ }
2401
+
2402
+ // Early compact-tree candidates could expose manufacturer spellings as
2403
+ // separate states. They are now normalised into measurements.powerW. Remove
2404
+ // only the known duplicates/typo so the compact folder does not keep an
2405
+ // obsolete "ActivePowerInport" datapoint after an update.
2406
+ const obsoleteKeys = [
2407
+ 'ActivePowerInport',
2408
+ 'activePowerInport',
2409
+ 'activepowerinport',
2410
+ 'extra_ActivePowerInport',
2411
+ 'extra_activePowerInport',
2412
+ 'extra_activepowerinport',
2413
+ 'Power_Active_Inport',
2414
+ 'extra_Power_Active_Inport',
2415
+ ];
2416
+ for (const key of obsoleteKeys) {
2417
+ const stateId = `${identity}.measurements.${key}`;
2418
+ try {
2419
+ let object;
2420
+ if (typeof this.getObjectAsync === 'function') object = await this.getObjectAsync(stateId);
2421
+ else if (typeof this.getForeignObjectAsync === 'function') object = await this.getForeignObjectAsync(`${this.namespace}.${stateId}`);
2422
+ if (!object) continue;
2423
+ await this.delObjectAsync(stateId, { recursive: true });
2424
+ this._dpObjCache.delete(stateId);
2425
+ this.log.info(`Removed obsolete OCPP measurement alias ${stateId}; use ${identity}.measurements.powerW.`);
2426
+ } catch (error) {
2427
+ this.log.debug(`Obsolete OCPP measurement cleanup skipped (${stateId}): ${error && error.message || error}`);
2428
+ }
2429
+ }
2430
+ this._measurementAliasCleanupDone.add(identity);
2431
+ }
2432
+
2433
+ async _cleanupLegacyObjects(identity) {
2434
+ if (this.config.cleanupLegacyObjects === false || this._legacyCleanupDone.has(identity)) return;
2435
+ const legacyBranches = [
2436
+ `${identity}.main`,
2437
+ `${identity}.meterValues`,
2438
+ `${identity}.evse`,
2439
+ `${identity}.evChargingNeeds`,
2440
+ `${identity}.ocpp`,
2441
+ `${identity}.dm`,
2442
+ ];
2443
+ let removed = 0;
2444
+ for (const branch of legacyBranches) {
2445
+ try {
2446
+ if (typeof this.delObjectAsync === 'function') {
2447
+ await this.delObjectAsync(branch, { recursive: true });
2448
+ removed++;
2449
+ }
2450
+ } catch (error) {
2451
+ // The branch usually does not exist on a new installation.
2452
+ this.log.debug(`Legacy OCPP branch cleanup skipped (${branch}): ${error && error.message || error}`);
2453
+ }
2454
+ }
2455
+ if (this.config.createTechnicalAliases !== true && typeof this.delForeignObjectAsync === 'function') {
2456
+ try {
2457
+ await this.delForeignObjectAsync(`alias.0.${this.namespace}.${identity}`, { recursive: true });
2458
+ } catch (error) {
2459
+ this.log.debug(`Technical alias cleanup skipped (${identity}): ${error && error.message || error}`);
2460
+ }
2461
+ }
2462
+ this._legacyCleanupDone.add(identity);
2463
+ if (removed > 0) this.log.info(`Compact OCPP datapoint structure activated for ${identity}; obsolete technical branches were removed.`);
2464
+ }
2465
+
2466
+ async ensureStructure(identity, evseId = 1, connectorId = 1) {
2467
+ const rawIdentity = this._stateToRawIdentity.get(identity) || identity;
2468
+ const state = async (id, common, native = {}) => this._setObjectNotExistsCached(id, { type: 'state', common, native });
2469
+ const channel = async (id, name, type = 'channel') => this._setObjectNotExistsCached(id, { type, common: { name }, native: {} });
2470
+
2471
+ if (!this._identityStructureReady.has(identity)) {
2472
+ await channel(identity, rawIdentity, 'device');
2473
+ await this.extendObjectAsync(identity, { native: { eosContract: 'nexowatt-ocpp21-0.4-native', deviceType: 'evCharger', controlScope: 'station' } });
2474
+ await channel(`${identity}.info`, { en: 'Information', de: 'Informationen' });
2475
+ await channel(`${identity}.health`, { en: 'Connection and data health', de: 'Verbindungs- und Datenstatus' });
2476
+ await channel(`${identity}.measurements`, { en: 'Measurements', de: 'Messwerte' });
2477
+ await channel(`${identity}.configuration`, { en: 'OCPP device configuration', de: 'OCPP-Gerätekonfiguration' });
2478
+ if (this.config.connectorDetails === true) await channel(`${identity}.connectors`, { en: 'Connectors', de: 'Ladeanschlüsse' });
2479
+ await channel(`${identity}.vehicle`, { en: 'Vehicle charging needs', de: 'Fahrzeug und Ladebedarf' });
2480
+ await channel(`${identity}.transactions`, { en: 'Transactions', de: 'Ladevorgänge' });
2481
+ await channel(`${identity}.control`, { en: 'Control', de: 'Steuerung' });
2482
+ // Legacy deletion is intentionally not automatic.
2483
+ // Preserve existing user mappings until explicit migration.
2484
+
2485
+ const info = {
2486
+ identity: ['string', 'text', ''],
2487
+ stateIdentity: ['string', 'text', ''],
2488
+ eosContract: ['string', 'text', 'nexowatt-ocpp21-0.4-native'],
2489
+ deviceType: ['string', 'text', 'evCharger'],
2490
+ controlScope: ['string', 'text', 'station'],
2491
+ sessionId: ['string', 'text', ''],
2492
+ eosControlLeaseSupported: ['boolean', 'indicator', true],
2493
+ connectorCount: ['number', 'value', 0],
2494
+ evseCount: ['number', 'value', 0],
2495
+ topologySource: ['string', 'text', 'unknown'],
2496
+ connection: ['boolean', 'indicator.connected', false],
2497
+ socketConnected: ['boolean', 'indicator.connected', false],
2498
+ status: ['string', 'indicator.status', ''],
2499
+ errorCode: ['string', 'text', ''],
2500
+ statusInfo: ['string', 'text', ''],
2501
+ vendorErrorCode: ['string', 'text', ''],
2502
+ vendorId: ['string', 'text', ''],
2503
+ protocol: ['string', 'text', ''],
2504
+ vendor: ['string', 'text', ''],
2505
+ model: ['string', 'text', ''],
2506
+ firmware: ['string', 'text', ''],
2507
+ serialNumber: ['string', 'text', ''],
2508
+ vin: ['string', 'text', ''],
2509
+ rfid: ['string', 'text', ''],
2510
+ rfidType: ['string', 'text', ''],
2511
+ chargePointSerialNumber: ['string', 'text', ''],
2512
+ chargeBoxSerialNumber: ['string', 'text', ''],
2513
+ iccid: ['string', 'text', ''],
2514
+ imsi: ['string', 'text', ''],
2515
+ meterType: ['string', 'text', ''],
2516
+ meterSerialNumber: ['string', 'text', ''],
2517
+ heartbeatInterval: ['number', 'value.interval', 0, 's'],
2518
+ lastHeartbeat: ['string', 'value.time', ''],
2519
+ firmwareStatus: ['string', 'text', ''],
2520
+ diagnosticsStatus: ['string', 'text', ''],
2521
+ logStatus: ['string', 'text', ''],
2522
+ };
2523
+ for (const [key, [type, role, def, unit]] of Object.entries(info)) {
2524
+ await state(`${identity}.info.${key}`, { name: key, type, role, read: true, write: false, def, unit });
2525
+ }
2526
+
2527
+ const health = {
2528
+ online: ['boolean', 'indicator.connected', false],
2529
+ activityFresh: ['boolean', 'indicator.connected', false],
2530
+ socketConnected: ['boolean', 'indicator.connected', false],
2531
+ heartbeatAlive: ['boolean', 'indicator.connected', false],
2532
+ meterFresh: ['boolean', 'indicator', false],
2533
+ powerFresh: ['boolean', 'indicator', false],
2534
+ exportPowerFresh: ['boolean', 'indicator', false],
2535
+ currentFresh: ['boolean', 'indicator', false],
2536
+ dataFresh: ['boolean', 'indicator', false],
2537
+ socFresh: ['boolean', 'indicator', false],
2538
+ staleReason: ['string', 'text', ''],
2539
+ powerSource: ['string', 'text', 'unknown-or-incomplete'],
2540
+ heartbeat: ['string', 'value.time', ''],
2541
+ lastHeartbeatMs: ['number', 'value.time', 0],
2542
+ lastSeen: ['string', 'value.time', ''],
2543
+ lastSeenMs: ['number', 'value.time', 0],
2544
+ lastAction: ['string', 'text', ''],
2545
+ lastBoot: ['string', 'value.time', ''],
2546
+ lastMeterValue: ['string', 'value.time', ''],
2547
+ lastPowerValue: ['string', 'value.time', ''],
2548
+ lastExportPowerValue: ['string', 'value.time', ''],
2549
+ lastCurrentValue: ['string', 'value.time', ''],
2550
+ lastSoc: ['string', 'value.time', ''],
2551
+ messageAgeSec: ['number', 'value.interval', -1, 's'],
2552
+ activityAgeSec: ['number', 'value.interval', -1, 's'],
2553
+ activityTimeoutSec: ['number', 'value.interval', 90, 's'],
2554
+ heartbeatTimeoutSec: ['number', 'value.interval', 0, 's'],
2555
+ heartbeatAgeSec: ['number', 'value.interval', -1, 's'],
2556
+ meterAgeSec: ['number', 'value.interval', -1, 's'],
2557
+ powerAgeSec: ['number', 'value.interval', -1, 's'],
2558
+ exportPowerAgeSec: ['number', 'value.interval', -1, 's'],
2559
+ currentAgeSec: ['number', 'value.interval', -1, 's'],
2560
+ statusAgeSec: ['number', 'value.interval', -1, 's'],
2561
+ socAgeSec: ['number', 'value.interval', -1, 's'],
2562
+ refreshStatus: ['string', 'text', 'not-run'],
2563
+ refreshSupport: ['string', 'json', '{}'],
2564
+ refreshLastAttempt: ['string', 'value.time', ''],
2565
+ refreshLastSuccess: ['string', 'value.time', ''],
2566
+ refreshLastError: ['string', 'text', ''],
2567
+ refreshSuppressedUntil: ['string', 'value.time', ''],
2568
+ refreshSuppressedReason: ['string', 'text', ''],
2569
+ refreshRelatedDisconnects: ['number', 'value', 0],
2570
+ lastRepublish: ['string', 'value.time', ''],
2571
+ safeZeroApplied: ['boolean', 'indicator', false],
2572
+ safeZeroReason: ['string', 'text', ''],
2573
+ lastDisconnectAt: ['string', 'value.time', ''],
2574
+ lastDisconnectCode: ['number', 'value', 0],
2575
+ lastDisconnectReason: ['string', 'text', ''],
2576
+ reconnectCount: ['number', 'value', 0],
2577
+ disconnectCount: ['number', 'value', 0],
2578
+ queueDepth: ['number', 'value', 0],
2579
+ queueMaxDepth: ['number', 'value', 0],
2580
+ queueDropped: ['number', 'value', 0],
2581
+ queueErrors: ['number', 'value', 0],
2582
+ queueLastError: ['string', 'text', ''],
2583
+ outboundCallCount: ['number', 'value', 0],
2584
+ outboundErrorCount: ['number', 'value', 0],
2585
+ lastOutboundMethod: ['string', 'text', ''],
2586
+ lastOutboundAt: ['string', 'value.time', ''],
2587
+ lastTransactionStopReason: ['string', 'text', ''],
2588
+ };
2589
+ for (const [key, [type, role, def, unit]] of Object.entries(health)) {
2590
+ await state(`${identity}.health.${key}`, { name: key, type, role, read: true, write: false, def, unit });
2591
+ }
2592
+
2593
+ const configurationStates = {
2594
+ refresh: {
2595
+ name: { en: 'Read configuration from charging station', de: 'Konfiguration von der Ladestation lesen' },
2596
+ type: 'boolean', role: 'button', read: true, write: true, def: false,
2597
+ },
2598
+ lastRefresh: {
2599
+ name: { en: 'Last completed configuration refresh', de: 'Letzte abgeschlossene Konfigurationsabfrage' },
2600
+ type: 'string', role: 'value.time', read: true, write: false, def: '',
2601
+ },
2602
+ status: {
2603
+ name: { en: 'Configuration operation status', de: 'Status der Konfigurationsverarbeitung' },
2604
+ type: 'string', role: 'text', read: true, write: false, def: 'idle',
2605
+ },
2606
+ error: {
2607
+ name: { en: 'Last configuration error', de: 'Letzter Konfigurationsfehler' },
2608
+ type: 'string', role: 'text', read: true, write: false, def: '',
2609
+ },
2610
+ count: {
2611
+ name: { en: 'Configuration values in latest complete inventory', de: 'Konfigurationswerte im letzten vollständigen Inventar' },
2612
+ type: 'number', role: 'value', read: true, write: false, def: 0, min: 0,
2613
+ },
2614
+ reportInProgress: {
2615
+ name: { en: 'Configuration report in progress', de: 'Konfigurationsbericht läuft' },
2616
+ type: 'boolean', role: 'indicator.working', read: true, write: false, def: false,
2617
+ },
2618
+ requestId: {
2619
+ name: { en: 'OCPP configuration request ID', de: 'OCPP-Anfrage-ID der Konfiguration' },
2620
+ type: 'number', role: 'value', read: true, write: false, def: 0,
2621
+ },
2622
+ lastSequence: {
2623
+ name: { en: 'Last configuration report sequence', de: 'Letzte Sequenz des Konfigurationsberichts' },
2624
+ type: 'number', role: 'value', read: true, write: false, def: 0,
2625
+ },
2626
+ lastChangedKey: {
2627
+ name: { en: 'Last changed configuration value', de: 'Zuletzt geänderter Konfigurationswert' },
2628
+ type: 'string', role: 'text', read: true, write: false, def: '',
2629
+ },
2630
+ lastChangedAt: {
2631
+ name: { en: 'Last configuration change timestamp', de: 'Zeitpunkt der letzten Konfigurationsänderung' },
2632
+ type: 'string', role: 'value.time', read: true, write: false, def: '',
2633
+ },
2634
+ lastChangeStatus: {
2635
+ name: { en: 'Last configuration change status', de: 'Status der letzten Konfigurationsänderung' },
2636
+ type: 'string', role: 'text', read: true, write: false, def: '',
2637
+ },
2638
+ lastChangeResponse: {
2639
+ name: { en: 'Last configuration change response', de: 'Antwort der letzten Konfigurationsänderung' },
2640
+ type: 'string', role: 'json', read: true, write: false, def: '',
2641
+ },
2642
+ rebootRequired: {
2643
+ name: { en: 'Charging station reports reboot required', de: 'Ladestation meldet erforderlichen Neustart' },
2644
+ type: 'boolean', role: 'indicator', read: true, write: false, def: false,
2645
+ },
2646
+ unknownKeysJson: {
2647
+ name: { en: 'Unknown OCPP 1.6 configuration keys', de: 'Unbekannte OCPP-1.6-Konfigurationsschlüssel' },
2648
+ type: 'string', role: 'json', read: true, write: false, def: '[]',
2649
+ },
2650
+ indexJson: {
2651
+ name: { en: 'Configuration datapoint index', de: 'Index der Konfigurationsdatenpunkte' },
2652
+ type: 'string', role: 'json', read: true, write: false, def: '{}',
2653
+ },
2654
+ };
2655
+ for (const [key, common] of Object.entries(configurationStates)) {
2656
+ await state(`${identity}.configuration.${key}`, common);
2657
+ }
2658
+
2659
+ const vehicle = {
2660
+ evseId: ['number', 'value', 0],
2661
+ lastUpdate: ['string', 'value.time', ''],
2662
+ energyTransferMode: ['string', 'text', ''],
2663
+ departureTime: ['string', 'value.time', ''],
2664
+ socPercent: ['number', 'value.battery', 0, '%'],
2665
+ targetSocPercent: ['number', 'value.battery', 0, '%'],
2666
+ fullSocPercent: ['number', 'value.battery', 0, '%'],
2667
+ bulkSocPercent: ['number', 'value.battery', 0, '%'],
2668
+ energyRequestWh: ['number', 'value.energy', 0, 'Wh'],
2669
+ batteryCapacityWh: ['number', 'value.energy', 0, 'Wh'],
2670
+ maxPowerW: ['number', 'value.power', 0, 'W'],
2671
+ maxCurrentA: ['number', 'value.current', 0, 'A'],
2672
+ maxVoltageV: ['number', 'value.voltage', 0, 'V'],
2673
+ maxScheduleTuples: ['number', 'value', 0],
2674
+ };
2675
+ for (const [key, [type, role, def, unit]] of Object.entries(vehicle)) {
2676
+ await state(`${identity}.vehicle.${key}`, { name: key, type, role, read: true, write: false, def, unit });
2677
+ }
2678
+
2679
+ const measurementSeeds = [
2680
+ ['Power.Active.Import', ''], ['Power.Active.Export', ''], ['Power.Offered', ''],
2681
+ ['Current.Import', ''], ['Current.Export', ''],
2682
+ ['Energy.Active.Import.Register', ''], ['Energy.Active.Export.Register', ''],
2683
+ ['SoC', ''], ['Voltage', ''], ['Frequency', ''], ['Temperature', ''],
2684
+ ['Power.Active.Import', 'L1'], ['Power.Active.Import', 'L2'], ['Power.Active.Import', 'L3'],
2685
+ ['Current.Import', 'L1'], ['Current.Import', 'L2'], ['Current.Import', 'L3'],
2686
+ ['Voltage', 'L1'], ['Voltage', 'L2'], ['Voltage', 'L3'],
2687
+ ];
2688
+ for (const [measurand, phase] of measurementSeeds) {
2689
+ const definition = measurementDefinition(measurand, phase);
2690
+ await this.ensureMeasurement(identity, definition.key, definition.unit, definition);
2691
+ if (definition.kwhKey) {
2692
+ await this.ensureMeasurement(identity, definition.kwhKey, 'kWh', {
2693
+ ...definition,
2694
+ key: definition.kwhKey,
2695
+ kwhKey: undefined,
2696
+ unit: 'kWh',
2697
+ });
2698
+ }
2699
+ }
2700
+ await this.ensureTextMeasurement(identity, 'lastUpdate', { en: 'Last measurement update', de: 'Letzte Messwertaktualisierung' }, 'value.time');
2701
+
2702
+ const controls = {
2703
+ eosLeaseUntilMs: { name: 'EOS control lease deadline (Unix ms, max 30 s)', type: 'number', role: 'value.time', write: true, def: 0 },
2704
+ eosLeaseArmed: { name: 'EOS lease watchdog persistently armed', type: 'boolean', role: 'indicator', write: false, def: false },
2705
+ eosLeaseState: { name: 'EOS lease watchdog state', type: 'string', role: 'text', write: false, def: 'unarmed' },
2706
+ availability: { name: { en: 'Charging station available', de: 'Ladestation verfügbar' }, type: 'boolean', role: 'switch.power', write: true, def: true },
2707
+ hardReset: { name: { en: 'Hard reset', de: 'Harter Neustart' }, type: 'boolean', role: 'button', write: true, def: false },
2708
+ softReset: { name: { en: 'Soft reset', de: 'Sanfter Neustart' }, type: 'boolean', role: 'button', write: true, def: false },
2709
+ chargeLimit: { name: { en: 'Requested charging limit', de: 'Angeforderte Ladegrenze' }, type: 'number', role: 'value.power', write: true, def: 0, unit: 'W', min: 0 },
2710
+ chargeLimitType: { name: { en: 'Charging limit unit', de: 'Einheit der Ladegrenze' }, type: 'string', role: 'text', write: true, def: 'W', states: { W: 'W', A: 'A' } },
2711
+ numberOfPhases: { name: { en: 'Number of phases', de: 'Anzahl Phasen' }, type: 'number', role: 'value', write: true, def: 3, min: 1, max: 3 },
2712
+ requestedChargeLimit: { name: { en: 'Last requested charging limit', de: 'Zuletzt angeforderte Ladegrenze' }, type: 'number', role: 'value', write: false, def: 0 },
2713
+ appliedChargeLimitUnit: { name: 'Applied limit unit', type: 'string', role: 'text', write: false, def: '' },
2714
+ appliedChargeLimitW: { name: 'Confirmed limit expressed as W ceiling', type: 'number', role: 'value.power', unit: 'W', write: false, def: 0 },
2715
+ chargeLimitStatus: { name: 'Atomic charging limit status for current session', type: 'string', role: 'json', write: false, def: '{}' },
2716
+ appliedChargeLimitValid: { name: 'Charging limit confirmed in current session', type: 'boolean', role: 'indicator', write: false, def: false },
2717
+ appliedChargeLimit: { name: { en: 'Applied charging limit', de: 'Angewendete Ladegrenze' }, type: 'number', role: 'value', write: false, def: 0 },
2718
+ chargeLimitReason: { name: { en: 'Charging limit decision', de: 'Entscheidung zur Ladegrenze' }, type: 'string', role: 'text', write: false, def: '' },
2719
+ chargeLimitClamped: { name: { en: 'Charging limit was clamped', de: 'Ladegrenze wurde angehoben' }, type: 'boolean', role: 'indicator', write: false, def: false },
2720
+ lastCommand: { name: { en: 'Last OCPP command', de: 'Letzter OCPP-Befehl' }, type: 'string', role: 'text', write: false, def: '' },
2721
+ lastCommandAt: { name: { en: 'Last command timestamp', de: 'Zeit des letzten Befehls' }, type: 'string', role: 'value.time', write: false, def: '' },
2722
+ lastResponse: { name: { en: 'Last command response', de: 'Letzte Befehlsantwort' }, type: 'string', role: 'json', write: false, def: '' },
2723
+ lastError: { name: { en: 'Last command error', de: 'Letzter Befehlsfehler' }, type: 'string', role: 'text', write: false, def: '' },
2724
+ lastSuccess: { name: { en: 'Last command successful', de: 'Letzter Befehl erfolgreich' }, type: 'boolean', role: 'indicator', write: false, def: false },
2725
+ rpcMethod: { name: 'OCPP method/action', type: 'string', role: 'text', write: true, def: '' },
2726
+ rpcPayload: { name: 'OCPP payload (JSON)', type: 'string', role: 'json', write: true, def: '' },
2727
+ rpcExecute: { name: 'Execute generic OCPP call', type: 'boolean', role: 'button', write: true, def: false },
2728
+ rpcLastResponse: { name: 'Generic OCPP response', type: 'string', role: 'json', write: false, def: '' },
2729
+ rpcLastError: { name: 'Generic OCPP error', type: 'string', role: 'text', write: false, def: '' },
2730
+ startIdToken: { name: 'Start idToken / idTag', type: 'string', role: 'text', write: true, def: '' },
2731
+ startIdTokenType: { name: 'Start idToken type (2.x)', type: 'string', role: 'text', write: true, def: 'Central' },
2732
+ startEvseId: { name: 'Start EVSE / connector ID', type: 'number', role: 'value', write: true, def: 1, min: 0 },
2733
+ startRemoteStartId: { name: 'Start remoteStartId (2.x)', type: 'number', role: 'value', write: true, def: 1, min: 1 },
2734
+ startChargingProfile: { name: 'Optional start chargingProfile JSON', type: 'string', role: 'json', write: true, def: '' },
2735
+ startTrigger: { name: 'Start transaction', type: 'boolean', role: 'button', write: true, def: false },
2736
+ startLastResponse: { name: 'Start response', type: 'string', role: 'json', write: false, def: '' },
2737
+ startLastError: { name: 'Start error', type: 'string', role: 'text', write: false, def: '' },
2738
+ stopTransactionId: { name: 'Stop transactionId (empty = last)', type: 'string', role: 'text', write: true, def: '' },
2739
+ stopTrigger: { name: 'Stop transaction', type: 'boolean', role: 'button', write: true, def: false },
2740
+ stopLastResponse: { name: 'Stop response', type: 'string', role: 'json', write: false, def: '' },
2741
+ stopLastError: { name: 'Stop error', type: 'string', role: 'text', write: false, def: '' },
2742
+ };
2743
+ for (const [key, common] of Object.entries(controls)) {
2744
+ await state(`${identity}.control.${key}`, { ...common, read: true, write: !!common.write });
2745
+ }
2746
+
2747
+ const txStates = {
2748
+ idTag: ['string', 'text', ''],
2749
+ idTagType: ['string', 'text', ''],
2750
+ transactionActive: ['boolean', 'indicator.working', false],
2751
+ chargingState: ['string', 'indicator.status', ''],
2752
+ triggerReason: ['string', 'text', ''],
2753
+ seqNo: ['number', 'value', 0],
2754
+ transactionStartMeter: ['number', 'value.energy', 0, 'Wh'],
2755
+ transactionStartMeter_kWh: ['number', 'value.energy', 0, 'kWh'],
2756
+ transactionEndMeter: ['number', 'value.energy', 0, 'Wh'],
2757
+ transactionEndMeter_kWh: ['number', 'value.energy', 0, 'kWh'],
2758
+ lastTransactionConsumption: ['number', 'value.energy', 0, 'Wh'],
2759
+ lastTransactionConsumption_kWh: ['number', 'value.energy', 0, 'kWh'],
2760
+ numberPhases: ['number', 'value', 0],
2761
+ lastType: ['string', 'text', ''],
2762
+ lastId: ['string', 'text', ''],
2763
+ lastEvseId: ['number', 'value', 0],
2764
+ lastConnectorId: ['number', 'value', 0],
2765
+ lastIdTag: ['string', 'text', ''],
2766
+ lastMeterStartWh: ['number', 'value.energy', 0, 'Wh'],
2767
+ lastMeterStartKWh: ['number', 'value.energy', 0, 'kWh'],
2768
+ lastMeterStopWh: ['number', 'value.energy', 0, 'Wh'],
2769
+ lastMeterStopKWh: ['number', 'value.energy', 0, 'kWh'],
2770
+ lastReason: ['string', 'text', ''],
2771
+ lastTimestamp: ['string', 'value.time', ''],
2772
+ };
2773
+ for (const [key, [type, role, def, unit]] of Object.entries(txStates)) {
2774
+ await state(`${identity}.transactions.${key}`, { name: key, type, role, read: true, write: false, def, unit });
2775
+ }
2776
+
2777
+ this._identityStructureReady.add(identity);
2778
+ // Preserve existing user mappings until explicit migration.
2779
+ }
2780
+
2781
+ if (this.config.connectorDetails === true) await this.ensureConnectorStructure(identity, evseId, connectorId);
2782
+ // Existing connector objects are never deleted automatically.
2783
+ if ((this.config.createPublicAliases === true || this.config.createTechnicalAliases === true) && !this._aliasDone.has(identity)) await this.ensureAliases(identity);
2784
+ }
2785
+
2786
+ async ensureMetric(identity, evseId, connectorId, key, unit, meta = {}) {
2787
+ if (this.config.connectorDetails !== true) return undefined;
2788
+ await this.ensureStructure(identity, evseId, connectorId);
2789
+ const base = this._connectorBase(identity, evseId, connectorId);
2790
+ const definition = meta && meta.definition;
2791
+ const compactKey = definition && !definition.extra
2792
+ ? sanitizeFlatKey(definition.key)
2793
+ : `extra_${sanitizeFlatKey(key)}`;
2794
+ const id = `${base}.${compactKey}`;
2795
+ const options = definition || {};
2796
+ await this._setObjectNotExistsCached(id, {
2797
+ type: 'state',
2798
+ common: measurementCommon(compactKey, unit, options),
2799
+ native: {
2800
+ measurand: meta && meta.measurand,
2801
+ phase: meta && meta.phase,
2802
+ },
2803
+ });
2804
+ return id;
2805
+ }
2806
+
2807
+ async ensureAgg(identity, key, unit) {
2808
+ const compactKey = compactKeyFromLegacyAggregate(key);
2809
+ return this.ensureMeasurement(identity, compactKey, unit);
2810
+ }
2811
+
2812
+ async _setDisconnectedHealth(identity, reason, entry = this.runtimeIndex.get(identity)) {
2813
+ await this._publishChargeLimitStatus(identity, entry, { valid: false, reason: reason || 'disconnected' });
2814
+ await this.ensureStructure(identity);
2815
+ if (this.runtimeIndex.get(identity) !== entry) return;
2816
+ const writes = {
2817
+ [`${identity}.info.connection`]: false,
2818
+ [`${identity}.info.socketConnected`]: false,
2819
+ [`${identity}.health.online`]: false,
2820
+ [`${identity}.health.activityFresh`]: false,
2821
+ [`${identity}.health.socketConnected`]: false,
2822
+ [`${identity}.health.heartbeatAlive`]: false,
2823
+ [`${identity}.health.meterFresh`]: false,
2824
+ [`${identity}.health.powerFresh`]: false,
2825
+ [`${identity}.health.exportPowerFresh`]: false,
2826
+ [`${identity}.health.currentFresh`]: false,
2827
+ [`${identity}.health.socFresh`]: false,
2828
+ [`${identity}.health.dataFresh`]: false,
2829
+ [`${identity}.measurements.socPercent`]: null,
2830
+ [`${identity}.vehicle.socPercent`]: null,
2831
+ [`${identity}.health.safeZeroApplied`]: false,
2832
+ [`${identity}.health.safeZeroReason`]: '',
2833
+ [`${identity}.health.messageAgeSec`]: -1,
2834
+ [`${identity}.health.activityAgeSec`]: -1,
2835
+ [`${identity}.health.heartbeatAgeSec`]: -1,
2836
+ [`${identity}.health.meterAgeSec`]: -1,
2837
+ [`${identity}.health.powerAgeSec`]: -1,
2838
+ [`${identity}.health.exportPowerAgeSec`]: -1,
2839
+ [`${identity}.health.currentAgeSec`]: -1,
2840
+ [`${identity}.health.statusAgeSec`]: -1,
2841
+ [`${identity}.health.socAgeSec`]: -1,
2842
+ [`${identity}.health.refreshStatus`]: 'offline',
2843
+ [`${identity}.health.staleReason`]: String(reason || 'socket-disconnected'),
2844
+ [`${identity}.configuration.reportInProgress`]: false,
2845
+ [`${identity}.configuration.status`]: 'offline',
2846
+ };
2847
+ for (const [id, value] of Object.entries(writes)) {
2848
+ if (this.runtimeIndex.get(identity) !== entry) return;
2849
+ const category = id.includes('.health.') ? 'health' : id.includes('.configuration.') ? 'configuration' : 'status';
2850
+ await this._setStateFreshAsync(id, value, true, category);
2851
+ }
2852
+ }
2853
+
2854
+ async _resetPersistedHealth() {
2855
+ const identities = new Set();
2856
+ const queries = [];
2857
+ if (typeof this.getStatesAsync === 'function') {
2858
+ queries.push(['getStatesAsync', '*.health.online'], ['getStatesAsync', '*.info.connection']);
2859
+ }
2860
+ if (typeof this.getForeignStatesAsync === 'function') {
2861
+ queries.push(
2862
+ ['getForeignStatesAsync', `${this.namespace}.*.health.online`],
2863
+ ['getForeignStatesAsync', `${this.namespace}.*.info.connection`],
2864
+ );
2865
+ }
2866
+ for (const [method, pattern] of queries) {
2867
+ try {
2868
+ const states = await this[method](pattern);
2869
+ for (const id of Object.keys(states || {})) {
2870
+ const rel = this._stripNs(id);
2871
+ const suffix = rel.endsWith('.health.online') ? '.health.online' : rel.endsWith('.info.connection') ? '.info.connection' : '';
2872
+ if (suffix) identities.add(rel.slice(0, -suffix.length));
2873
+ }
2874
+ } catch (e) {
2875
+ this.log.debug(`Could not inspect persisted OCPP health states (${pattern}): ${e && e.message || e}`);
2876
+ }
2877
+ }
2878
+ for (const identity of identities) {
2879
+ if (!identity) continue;
2880
+ try {
2881
+ await this._setDisconnectedHealth(identity, 'adapter-restarted-awaiting-station');
2882
+ } catch (e) {
2883
+ this.log.warn(`Could not reset persisted health for ${identity}: ${e && e.message || e}`);
2884
+ }
2885
+ }
2886
+ }
2887
+
2888
+ async onReady() {
2889
+ if (typeof this.assertCanOperate === 'function') this.assertCanOperate();
2890
+ // Never leave persisted online/fresh flags true after an unclean restart.
2891
+ await this._resetPersistedHealth();
2892
+
2893
+ const allowlist = Array.isArray(this.config.identityAllowlist)
2894
+ ? this.config.identityAllowlist.map(String).map((v) => v.trim()).filter(Boolean)
2895
+ : String(this.config.identityAllowlist || '').split(',').map((v) => v.trim()).filter(Boolean);
2896
+
2897
+ const ctx = {
2898
+ assertCanOperate: () => { if (typeof this.assertCanOperate === 'function') this.assertCanOperate(); },
2899
+ log: this.log,
2900
+ config: {
2901
+ ...this.config,
2902
+ port: Math.max(1, Math.min(65535, Number(this.config.port) || 9220)),
2903
+ enable16: this.config.enable16 !== false,
2904
+ enable201: this.config.enable201 !== false,
2905
+ enable21: this.config.enable21 !== false,
2906
+ heartbeatIntervalSec: Math.max(10, Number(this.config.heartbeatIntervalSec) || 300),
2907
+ identityAllowlist: allowlist,
2908
+ callTimeoutSec: Math.max(5, Number(this.config.callTimeoutSec) || 20),
2909
+ },
2910
+ states: {
2911
+ setConnection: async (id, online, meta = {}) => {
2912
+ const entry = this.runtimeIndex.get(id);
2913
+ await this.ensureStructure(id);
2914
+ if (this.runtimeIndex.get(id) !== entry) return;
2915
+ const socketConnected = meta.socketConnected !== undefined ? !!meta.socketConnected : !!online;
2916
+ if (entry) entry.socketConnected = socketConnected;
2917
+ await this._setStateFreshAsync(`${id}.info.connection`, socketConnected, true, 'status');
2918
+ await this._setStateFreshAsync(`${id}.info.socketConnected`, socketConnected, true, 'status');
2919
+ await this._setStateFreshAsync(`${id}.health.online`, !!online && socketConnected, true, 'health');
2920
+ await this._setStateFreshAsync(`${id}.health.activityFresh`, !!online && socketConnected, true, 'health');
2921
+ await this._setStateFreshAsync(`${id}.health.socketConnected`, socketConnected, true, 'health');
2922
+ if (this.runtimeIndex.get(id) !== entry) return;
2923
+ if (!socketConnected) {
2924
+ await this._setDisconnectedHealth(id, 'socket-disconnected', entry);
2925
+ } else {
2926
+ for (const key of ['heartbeatAlive', 'meterFresh', 'powerFresh', 'exportPowerFresh', 'currentFresh', 'dataFresh', 'socFresh', 'safeZeroApplied']) {
2927
+ await this._setStateFreshAsync(`${id}.health.${key}`, false, true, 'health');
2928
+ }
2929
+ await this._setStateFreshAsync(`${id}.health.safeZeroReason`, '', true, 'health');
2930
+ await this._setStateFreshAsync(`${id}.health.staleReason`, 'awaiting-power-or-idle-status', true, 'health');
2931
+ }
2932
+ if (meta.rawIdentity !== undefined) {
2933
+ await this._setStateFreshAsync(`${id}.info.identity`, String(meta.rawIdentity), true, 'static');
2934
+ await this._setStateFreshAsync(`${id}.info.stateIdentity`, id, true, 'static');
2935
+ }
2936
+ if (meta.protocol !== undefined) await this._setStateFreshAsync(`${id}.info.protocol`, String(meta.protocol), true, 'static');
2937
+ },
2938
+ upsertIdentityMeta: async (id, meta) => {
2939
+ await this.ensureStructure(id);
2940
+ const infoKeys = ['protocol', 'vendor', 'model', 'firmwareVersion', 'serialNumber', 'chargePointSerialNumber', 'chargeBoxSerialNumber', 'iccid', 'imsi', 'meterType', 'meterSerialNumber'];
2941
+ const map = { firmwareVersion: 'firmware' };
2942
+ for (const key of infoKeys) {
2943
+ if (meta[key] !== undefined && meta[key] !== null) {
2944
+ await this._setStateFreshAsync(`${id}.info.${map[key] || key}`, meta[key], true, 'static');
2945
+ }
2946
+ }
2947
+ const rawIdentity = this._stateToRawIdentity.get(id) || id;
2948
+ await this._setStateFreshAsync(`${id}.info.identity`, rawIdentity, true, 'static');
2949
+ await this._setStateFreshAsync(`${id}.info.stateIdentity`, id, true, 'static');
2950
+ },
2951
+ upsertEvseState: async (id, evseId, connectorId, patch) => {
2952
+ await this.ensureStructure(id, evseId, connectorId);
2953
+ const base = await this.ensureConnectorStructure(id, evseId, connectorId);
2954
+ if (patch.errorCode !== undefined) await this._setStateFreshAsync(`${id}.info.errorCode`, patch.errorCode, true, 'status');
2955
+ if (patch.info !== undefined) await this._setStateFreshAsync(`${id}.info.statusInfo`, patch.info, true, 'status');
2956
+ if (patch.vendorErrorCode !== undefined) await this._setStateFreshAsync(`${id}.info.vendorErrorCode`, patch.vendorErrorCode, true, 'status');
2957
+ if (patch.vendorId !== undefined) await this._setStateFreshAsync(`${id}.info.vendorId`, patch.vendorId, true, 'status');
2958
+ if (!base) return;
2959
+ if (patch.status !== undefined) await this._setStateFreshAsync(`${base}.status`, patch.status, true, 'status');
2960
+ if (patch.errorCode !== undefined) await this._setStateFreshAsync(`${base}.errorCode`, patch.errorCode, true, 'status');
2961
+ if (patch.timestamp !== undefined) await this._setStateFreshAsync(`${base}.lastUpdate`, patch.timestamp, true, 'status');
2962
+ if (patch.info !== undefined) await this._setStateFreshAsync(`${base}.info`, patch.info, true, 'status');
2963
+ if (patch.vendorErrorCode !== undefined) await this._setStateFreshAsync(`${base}.vendorErrorCode`, patch.vendorErrorCode, true, 'status');
2964
+ if (patch.vendorId !== undefined) await this._setStateFreshAsync(`${base}.vendorId`, patch.vendorId, true, 'status');
2965
+ },
2966
+ pushTransactionEvent: async (id, evt) => {
2967
+ await this.ensureStructure(id, evt.evseId || 1, evt.connectorId || 1);
2968
+ const base = `${id}.transactions`;
2969
+ if (evt.type !== undefined) await this._setStateFreshAsync(`${base}.lastType`, evt.type, true, 'transaction');
2970
+ if (evt.txId !== undefined) await this._setStateFreshAsync(`${base}.lastId`, String(evt.txId), true, 'transaction');
2971
+ if (evt.evseId !== undefined) await this._setStateFreshAsync(`${base}.lastEvseId`, Number(evt.evseId), true, 'transaction');
2972
+ if (evt.connectorId !== undefined) await this._setStateFreshAsync(`${base}.lastConnectorId`, Number(evt.connectorId), true, 'transaction');
2973
+ if (evt.idTag !== undefined) {
2974
+ await this._setStateFreshAsync(`${base}.lastIdTag`, evt.idTag, true, 'transaction');
2975
+ await this._setStateFreshAsync(`${id}.transactions.idTag`, evt.idTag, true, 'transaction');
2976
+ await this._setStateFreshAsync(`${id}.info.rfid`, evt.idTag, true, 'status');
2977
+ }
2978
+ if (evt.idTokenType !== undefined) {
2979
+ await this._setStateFreshAsync(`${id}.transactions.idTagType`, String(evt.idTokenType), true, 'transaction');
2980
+ await this._setStateFreshAsync(`${id}.info.rfidType`, String(evt.idTokenType), true, 'status');
2981
+ }
2982
+ const meterEntry = this.runtimeIndex.get(id);
2983
+ const meterStarts = meterEntry && (meterEntry.transactionMeterStarts || (meterEntry.transactionMeterStarts = new Map()));
2984
+ const meterTxKey = evt.txId == null ? '' : String(evt.txId);
2985
+ if (evt.meterStart !== undefined && Number.isFinite(Number(evt.meterStart))) {
2986
+ const wh = Number(evt.meterStart);
2987
+ if (meterStarts && meterTxKey && (meterStarts.size < 1000 || meterStarts.has(meterTxKey))) meterStarts.set(meterTxKey, wh);
2988
+ await this._setStateFreshAsync(`${base}.lastMeterStartWh`, wh, true, 'counter');
2989
+ await this._setStateFreshAsync(`${base}.lastMeterStartKWh`, wh / 1000, true, 'counter');
2990
+ await this._setStateFreshAsync(`${id}.transactions.transactionStartMeter`, wh, true, 'counter');
2991
+ await this._setStateFreshAsync(`${id}.transactions.transactionStartMeter_kWh`, wh / 1000, true, 'counter');
2992
+ }
2993
+ if (evt.meterStop !== undefined && Number.isFinite(Number(evt.meterStop))) {
2994
+ const whStop = Number(evt.meterStop);
2995
+ await this._setStateFreshAsync(`${base}.lastMeterStopWh`, whStop, true, 'counter');
2996
+ await this._setStateFreshAsync(`${base}.lastMeterStopKWh`, whStop / 1000, true, 'counter');
2997
+ await this._setStateFreshAsync(`${id}.transactions.transactionEndMeter`, whStop, true, 'counter');
2998
+ await this._setStateFreshAsync(`${id}.transactions.transactionEndMeter_kWh`, whStop / 1000, true, 'counter');
2999
+ const startWh = meterStarts?.get(meterTxKey);
3000
+ meterStarts?.delete(meterTxKey);
3001
+ if (Number.isFinite(startWh)) {
3002
+ const consumptionWh = Math.max(0, whStop - startWh);
3003
+ await this._setStateFreshAsync(`${id}.transactions.lastTransactionConsumption`, consumptionWh, true, 'counter');
3004
+ await this._setStateFreshAsync(`${id}.transactions.lastTransactionConsumption_kWh`, consumptionWh / 1000, true, 'counter');
3005
+ }
3006
+ }
3007
+ if (evt.reason !== undefined) {
3008
+ await this._setStateFreshAsync(`${base}.lastReason`, evt.reason, true, 'transaction');
3009
+ if (evt.type === 'Stop') await this._setStateFreshAsync(`${id}.health.lastTransactionStopReason`, String(evt.reason || ''), true, 'health');
3010
+ }
3011
+ if (evt.ts !== undefined) await this._setStateFreshAsync(`${base}.lastTimestamp`, evt.ts, true, 'transaction');
3012
+ if (evt.triggerReason !== undefined) await this._setStateFreshAsync(`${id}.transactions.triggerReason`, String(evt.triggerReason || ''), true, 'transaction');
3013
+ if (evt.seqNo !== undefined && Number.isFinite(Number(evt.seqNo))) await this._setStateFreshAsync(`${id}.transactions.seqNo`, Number(evt.seqNo), true, 'transaction');
3014
+ await this._noteTransaction(id, evt);
3015
+ },
3016
+ setRfid: async (id, token, tokenType) => {
3017
+ await this.ensureStructure(id);
3018
+ if (token !== undefined && token !== null && String(token).length) {
3019
+ await this._setStateFreshAsync(`${id}.info.rfid`, String(token), true, 'status');
3020
+ await this._setStateFreshAsync(`${id}.transactions.idTag`, String(token), true, 'transaction');
3021
+ }
3022
+ if (tokenType !== undefined && tokenType !== null && String(tokenType).length) {
3023
+ await this._setStateFreshAsync(`${id}.info.rfidType`, String(tokenType), true, 'status');
3024
+ await this._setStateFreshAsync(`${id}.transactions.idTagType`, String(tokenType), true, 'transaction');
3025
+ }
3026
+ },
3027
+ connectorBase: this._connectorBase.bind(this),
3028
+ ensureConnectorStructure: this.ensureConnectorStructure.bind(this),
3029
+ ensureMeasurementState: this.ensureMeasurement.bind(this),
3030
+ ensureTextMeasurementState: this.ensureTextMeasurement.bind(this),
3031
+ ensureMetricState: this.ensureMetric.bind(this),
3032
+ ensureAggState: this.ensureAgg.bind(this),
3033
+ ensureStructure: this.ensureStructure.bind(this),
3034
+ },
3035
+ runtime: {
3036
+ resolveIdentity: this.resolveStationIdentity.bind(this),
3037
+ indexClient: this._indexClient.bind(this),
3038
+ unindexClient: this._unindexClient.bind(this),
3039
+ noteDisconnect: this._noteDisconnect.bind(this),
3040
+ getClient: (id) => (this.runtimeIndex.get(id) || {}).client,
3041
+ noteMessage: this._noteMessage.bind(this),
3042
+ noteBoot: this._noteBoot.bind(this),
3043
+ noteHeartbeat: this._noteHeartbeat.bind(this),
3044
+ noteStatus: this._noteStatus.bind(this),
3045
+ noteMeterValue: this._noteMeterValue.bind(this),
3046
+ publishScopedMeter: this._publishScopedMeter.bind(this),
3047
+ publishScopedSoc: this._publishScopedSoc.bind(this),
3048
+ noteSoc: this._noteSoc.bind(this),
3049
+ recordPhaseMetric: this._recordPhaseMetric.bind(this),
3050
+ getPhaseMetricTotal: this._getPhaseMetricTotal.bind(this),
3051
+ },
3052
+ defer: this._deferStationTask.bind(this),
3053
+ dp: { capture: this.captureOcppPayload.bind(this) },
3054
+ dm: { ingestNotifyReport: this.ingestNotifyReport.bind(this) },
3055
+ setStateChangedAsync: this.setStateChangedAsync.bind(this),
3056
+ setStateFreshAsync: this._setStateFreshAsync.bind(this),
3057
+ };
3058
+
3059
+ const protocols = []
3060
+ .concat(ctx.config.enable16 ? ['ocpp1.6'] : [])
3061
+ .concat(ctx.config.enable201 ? ['ocpp2.0.1'] : [])
3062
+ .concat(ctx.config.enable21 ? ['ocpp2.1'] : []);
3063
+ if (protocols.length === 0) throw new Error('At least one OCPP protocol must be enabled');
3064
+
3065
+ this.server = new OcppRpcServer(ctx, { port: ctx.config.port, protocols, strictMode: false });
3066
+ await this.server.listen();
3067
+ if (typeof this.subscribeStatesAsync === 'function') await this.subscribeStatesAsync('*');
3068
+ else this.subscribeStates('*');
3069
+ if (typeof this.assertCanOperate === 'function') this.assertCanOperate();
3070
+
3071
+ const healthCheckMs = Math.max(2, Number(this.config.healthCheckIntervalSec) || 5) * 1000;
3072
+ this._watchdogTimer = setInterval(() => this._watchdogCycle(), healthCheckMs);
3073
+ this._eosLeaseTimer = setInterval(() => this._eosLeaseWatchdogCycle(), 1000);
3074
+ await this._watchdogCycle();
3075
+ this.log.info('NexoWatt OCPP adapter ready for NexoWatt EOS');
3076
+ }
3077
+
3078
+ async onStateChange(id, state) {
3079
+ if (!state || state.ack || this._shuttingDown) return;
3080
+ const rel = this._stripNs(id);
3081
+ const leaseMatch = rel.match(/^([^\.]+)\.control\.eosLeaseUntilMs$/);
3082
+ if (leaseMatch) {
3083
+ try { await this._renewEosLease(leaseMatch[1], state); }
3084
+ catch (error) { this.log.warn(`EOS lease renewal failed: ${error.message}`); }
3085
+ return;
3086
+ }
3087
+ const match = (patterns) => {
3088
+ for (const pattern of Array.isArray(patterns) ? patterns : [patterns]) {
3089
+ const found = rel.match(pattern);
3090
+ if (found) return found;
3091
+ }
3092
+ return null;
3093
+ };
3094
+
3095
+ const mHard = match([/^([^\.]+)\.control\.hardReset$/, /^([^\.]+)\.control\.hardReset\.trigger$/]);
3096
+ const mSoft = match([/^([^\.]+)\.control\.softReset$/, /^([^\.]+)\.control\.softReset\.trigger$/]);
3097
+ const mAvail = match(/^([^\.]+)\.control\.availability$/);
3098
+ const mLimit = match(/^([^\.]+)\.control\.chargeLimit$/);
3099
+ const mLimitType = match(/^([^\.]+)\.control\.chargeLimitType$/);
3100
+ const mPhases = match(/^([^\.]+)\.control\.numberOfPhases$/);
3101
+ const mRpcExec = match([/^([^\.]+)\.control\.rpcExecute$/, /^([^\.]+)\.control\.rpc\.execute$/]);
3102
+ const mRpcMethod = match([/^([^\.]+)\.control\.rpcMethod$/, /^([^\.]+)\.control\.rpc\.method$/]);
3103
+ const mRpcPayload = match([/^([^\.]+)\.control\.rpcPayload$/, /^([^\.]+)\.control\.rpc\.payload$/]);
3104
+ const mReqStartTrigger = match([/^([^\.]+)\.control\.startTrigger$/, /^([^\.]+)\.control\.requestStartTransaction\.trigger$/]);
3105
+ const mReqStartIdToken = match([/^([^\.]+)\.control\.startIdToken$/, /^([^\.]+)\.control\.requestStartTransaction\.idToken$/]);
3106
+ const mReqStartIdTokenType = match([/^([^\.]+)\.control\.startIdTokenType$/, /^([^\.]+)\.control\.requestStartTransaction\.idTokenType$/]);
3107
+ const mReqStartEvseId = match([/^([^\.]+)\.control\.startEvseId$/, /^([^\.]+)\.control\.requestStartTransaction\.evseId$/]);
3108
+ const mReqStartRemoteStartId = match([/^([^\.]+)\.control\.startRemoteStartId$/, /^([^\.]+)\.control\.requestStartTransaction\.remoteStartId$/]);
3109
+ const mReqStartProfile = match([/^([^\.]+)\.control\.startChargingProfile$/, /^([^\.]+)\.control\.requestStartTransaction\.chargingProfile$/]);
3110
+ const mReqStopTrigger = match([/^([^\.]+)\.control\.stopTrigger$/, /^([^\.]+)\.control\.requestStopTransaction\.trigger$/]);
3111
+ const mReqStopTxId = match([/^([^\.]+)\.control\.stopTransactionId$/, /^([^\.]+)\.control\.requestStopTransaction\.transactionId$/]);
3112
+ const rawConfigurationMatch = match(/^([^\.]+)\.configuration\.([^\.]+)$/);
3113
+ const mConfigurationRefresh = rawConfigurationMatch && rawConfigurationMatch[2] === 'refresh' ? rawConfigurationMatch : null;
3114
+ const mConfigurationValue = rawConfigurationMatch && !RESERVED_CONFIGURATION_KEYS.has(rawConfigurationMatch[2]) ? rawConfigurationMatch : null;
3115
+
3116
+ const matches = [mHard, mSoft, mAvail, mLimit, mLimitType, mPhases, mRpcExec, mRpcMethod, mRpcPayload,
3117
+ mReqStartTrigger, mReqStartIdToken, mReqStartIdTokenType, mReqStartEvseId, mReqStartRemoteStartId,
3118
+ mReqStartProfile, mReqStopTrigger, mReqStopTxId, mConfigurationRefresh, mConfigurationValue];
3119
+ const identityMatch = matches.find(Boolean);
3120
+ if (!identityMatch) return;
3121
+ const identity = identityMatch[1];
3122
+
3123
+ if (mConfigurationRefresh) {
3124
+ if (!state.val) {
3125
+ await this._setStateFreshAsync(rel, false, true, 'configuration');
3126
+ return;
3127
+ }
3128
+ try {
3129
+ await this._refreshConfiguration(identity, { automatic: false });
3130
+ } catch (error) {
3131
+ this.log.warn(`OCPP configuration refresh failed (${identity}): ${error && error.message || error}`);
3132
+ } finally {
3133
+ await this._setStateFreshAsync(rel, false, true, 'configuration');
3134
+ }
3135
+ return;
3136
+ }
3137
+
3138
+ if (mConfigurationValue) {
3139
+ try {
3140
+ const result = await this._queueConfigurationWrite(identity, rel, state.val);
3141
+ if (result && result.status === 'Superseded') return;
3142
+ } catch (error) {
3143
+ this.log.warn(`OCPP configuration write failed (${identity}, ${mConfigurationValue[2]}): ${error && error.message || error}`);
3144
+ const meta = await this._resolveConfigurationMeta(rel);
3145
+ const connected = !!this.runtimeIndex.get(identity)?.client;
3146
+ const writable = configurationWritable(meta, this.config.configurationWriteEnabled !== false);
3147
+ await this._recordConfigurationStatus(identity, {
3148
+ status: !connected ? 'offline' : !writable ? 'write-disabled' : 'write-error',
3149
+ error: String(error && error.message || error),
3150
+ lastChangedKey: meta ? (meta.kind === 'ocpp16' ? meta.key : this._configurationDisplayName(meta)) : mConfigurationValue[2],
3151
+ lastChangedAt: new Date().toISOString(),
3152
+ lastChangeStatus: 'Error',
3153
+ });
3154
+ await this._restoreConfigurationState(rel, meta);
3155
+ }
3156
+ return;
3157
+ }
3158
+
3159
+ const ack = async (value) => {
3160
+ const current = await this.getStateAsync(rel);
3161
+ if (!current || current.ack || current.val !== state.val || (state.ts != null && current.ts !== state.ts)) return;
3162
+ return this._setStateFreshAsync(rel, value, true, 'control');
3163
+ };
3164
+ const ackIfStillCurrent = async () => {
3165
+ const current = await this.getStateAsync(rel);
3166
+ if (!current || current.ack) return;
3167
+ const currentVal = current.val;
3168
+ const originalVal = state.val;
3169
+ const same = (typeof currentVal === 'number' || typeof originalVal === 'number')
3170
+ ? Number.isFinite(Number(currentVal)) && Number.isFinite(Number(originalVal)) && Number(currentVal) === Number(originalVal)
3171
+ : String(currentVal) === String(originalVal);
3172
+ if (same) await ack(currentVal);
3173
+ };
3174
+ const readControl = async (flatKey, legacyPath, fallback = undefined) => {
3175
+ const flat = await this.getStateAsync(`${identity}.control.${flatKey}`);
3176
+ if (flat && flat.val !== undefined && flat.val !== null && flat.val !== '') return flat.val;
3177
+ if (legacyPath) {
3178
+ const legacy = await this.getStateAsync(`${identity}.control.${legacyPath}`);
3179
+ if (legacy && legacy.val !== undefined && legacy.val !== null && legacy.val !== '') return legacy.val;
3180
+ }
3181
+ return fallback;
3182
+ };
3183
+ const setSpecificResult = async (section, response, error) => {
3184
+ if (!section) return;
3185
+ const keys = section === 'rpc'
3186
+ ? ['rpcLastResponse', 'rpcLastError']
3187
+ : section === 'start'
3188
+ ? ['startLastResponse', 'startLastError']
3189
+ : ['stopLastResponse', 'stopLastError'];
3190
+ const errorText = error ? String(error && error.message || error) : '';
3191
+ await this._setStateFreshAsync(`${identity}.control.${keys[0]}`, errorText ? '' : this._stringifyControlValue(response), true, 'control');
3192
+ await this._setStateFreshAsync(`${identity}.control.${keys[1]}`, errorText, true, 'control');
3193
+ };
3194
+ const succeed = async (method, response, ackValue, section) => {
3195
+ await this._recordControlResult(identity, method, response, undefined);
3196
+ await setSpecificResult(section, response, undefined);
3197
+ await ack(ackValue);
3198
+ };
3199
+ const fail = async (method, error, ackValue, section) => {
3200
+ this.log.warn(`NexoWatt OCPP control failed (${identity}, ${method}): ${error && error.message || error}`);
3201
+ await this._recordControlResult(identity, method, undefined, error);
3202
+ await setSpecificResult(section, undefined, error);
3203
+ await ack(ackValue);
3204
+ };
3205
+
3206
+ // These are local input states. They are acknowledged without issuing a
3207
+ // protocol command until their matching trigger or limit state is written.
3208
+ if (mRpcMethod || mRpcPayload || mLimitType || mReqStartIdToken || mReqStartIdTokenType
3209
+ || mReqStartEvseId || mReqStartRemoteStartId || mReqStartProfile || mReqStopTxId) {
3210
+ await ack(state.val);
3211
+ return;
3212
+ }
3213
+
3214
+ const entry = this.runtimeIndex.get(identity);
3215
+ const proto = entry && entry.proto;
3216
+ const call = (method, payload) => this._callClient(identity, method, payload);
3217
+ const action = mHard || mSoft ? 'Reset'
3218
+ : mAvail ? 'ChangeAvailability'
3219
+ : mLimit || mPhases ? 'SetChargingProfile'
3220
+ : mRpcExec ? 'RPC'
3221
+ : mReqStartTrigger ? (proto === 'ocpp1.6' ? 'RemoteStartTransaction' : 'RequestStartTransaction')
3222
+ : mReqStopTrigger ? (proto === 'ocpp1.6' ? 'RemoteStopTransaction' : 'RequestStopTransaction')
3223
+ : 'Control';
3224
+ const section = mRpcExec ? 'rpc' : mReqStartTrigger ? 'start' : mReqStopTrigger ? 'stop' : undefined;
3225
+
3226
+ let offlineAckValue = state.val;
3227
+ if (mHard || mSoft || mRpcExec || mReqStartTrigger || mReqStopTrigger) offlineAckValue = false;
3228
+ if (mAvail) offlineAckValue = !!state.val;
3229
+ if (mLimit) offlineAckValue = Math.max(0, Number.isFinite(Number(state.val)) ? Number(state.val) : 0);
3230
+ if (mPhases) offlineAckValue = Math.max(1, Math.min(3, Math.round(Number(state.val) || 3)));
3231
+
3232
+ if (!entry || !entry.client) {
3233
+ await fail(action, new Error('Charging station is not connected'), offlineAckValue, section);
3234
+ return;
3235
+ }
3236
+
3237
+ try {
3238
+ if (mRpcExec) {
3239
+ if (!state.val) { await ack(false); return; }
3240
+ const method = String(await readControl('rpcMethod', 'rpc.method', '') || '').trim();
3241
+ const payloadText = String(await readControl('rpcPayload', 'rpc.payload', '') || '').trim();
3242
+ if (!method) throw new Error('Missing OCPP method/action');
3243
+ let payload = {};
3244
+ if (payloadText) {
3245
+ try { payload = JSON.parse(payloadText); } catch (error) { throw new Error(`Payload is not valid JSON: ${error.message}`); }
3246
+ }
3247
+ if (['SetChargingProfile', 'ClearChargingProfile', 'RemoteStartTransaction', 'RequestStartTransaction'].includes(method)) {
3248
+ const lease = await this._ensureEosLease(identity);
3249
+ if (lease.armed && (!this._eosLeaseFresh(lease) || lease.stopRequired)) throw new Error('EOS_LEASE_EXPIRED');
3250
+ }
3251
+ if (method === 'SetChargingProfile' || method === 'ClearChargingProfile') {
3252
+ entry.lastSmartCharging = undefined;
3253
+ await this._publishChargeLimitStatus(identity, entry, { valid: false, reason: 'manual-profile-command' });
3254
+ }
3255
+ const response = await call(method, payload);
3256
+ await succeed(method, response, false, 'rpc');
3257
+ return;
3258
+ }
3259
+
3260
+ if (mReqStartTrigger) {
3261
+ if (!state.val) { await ack(false); return; }
3262
+ const idToken = String(await readControl('startIdToken', 'requestStartTransaction.idToken', '') || '').trim();
3263
+ const idTokenType = String(await readControl('startIdTokenType', 'requestStartTransaction.idTokenType', 'Central') || 'Central').trim() || 'Central';
3264
+ const evseId = Math.max(0, Number(await readControl('startEvseId', 'requestStartTransaction.evseId', 1) || 1));
3265
+ let remoteStartId = Number(await readControl('startRemoteStartId', 'requestStartTransaction.remoteStartId', 0) || 0);
3266
+ if (!Number.isFinite(remoteStartId) || remoteStartId <= 0) remoteStartId = Math.floor(Math.random() * 0x7ffffffe) + 1;
3267
+ if (!idToken) throw new Error('Missing idToken/idTag');
3268
+
3269
+ let response;
3270
+ if (proto === 'ocpp1.6') {
3271
+ response = await call('RemoteStartTransaction', { connectorId: evseId || 1, idTag: idToken });
3272
+ this._assertCallAccepted('RemoteStartTransaction', response);
3273
+ } else {
3274
+ const payload = { idToken: { idToken, type: idTokenType }, remoteStartId };
3275
+ if (evseId > 0) payload.evseId = evseId;
3276
+ const profileText = String(await readControl('startChargingProfile', 'requestStartTransaction.chargingProfile', '') || '').trim();
3277
+ if (profileText) {
3278
+ try { payload.chargingProfile = JSON.parse(profileText); } catch (error) { throw new Error(`chargingProfile is not valid JSON: ${error.message}`); }
3279
+ }
3280
+ response = await call('RequestStartTransaction', payload);
3281
+ this._assertCallAccepted('RequestStartTransaction', response);
3282
+ }
3283
+ await this._setStateFreshAsync(`${identity}.control.startRemoteStartId`, remoteStartId, true, 'control');
3284
+ await succeed(proto === 'ocpp1.6' ? 'RemoteStartTransaction' : 'RequestStartTransaction', response, false, 'start');
3285
+ return;
3286
+ }
3287
+
3288
+ if (mReqStopTrigger) {
3289
+ if (!state.val) { await ack(false); return; }
3290
+ let transactionId = String(await readControl('stopTransactionId', 'requestStopTransaction.transactionId', '') || '').trim();
3291
+ if (!transactionId) {
3292
+ const active = [...this._getStationTelemetry(identity, entry).transactions.values()].filter(t => t.active && t.id);
3293
+ if (active.length !== 1) throw new Error('Select an explicit active transactionId');
3294
+ transactionId = active[0].id;
3295
+ }
3296
+ if (!transactionId) throw new Error('Missing transactionId and no last transaction is known');
3297
+ const response = proto === 'ocpp1.6'
3298
+ ? await call('RemoteStopTransaction', { transactionId: Number.isFinite(Number(transactionId)) ? Number(transactionId) : transactionId })
3299
+ : await call('RequestStopTransaction', { transactionId });
3300
+ this._assertCallAccepted(proto === 'ocpp1.6' ? 'RemoteStopTransaction' : 'RequestStopTransaction', response);
3301
+ await this._setStateFreshAsync(`${identity}.control.stopTransactionId`, transactionId, true, 'control');
3302
+ await succeed(proto === 'ocpp1.6' ? 'RemoteStopTransaction' : 'RequestStopTransaction', response, false, 'stop');
3303
+ return;
3304
+ }
3305
+
3306
+ if (mHard || mSoft) {
3307
+ if (!state.val) { await ack(false); return; }
3308
+ const type = proto === 'ocpp1.6' ? (mHard ? 'Hard' : 'Soft') : (mHard ? 'Immediate' : 'OnIdle');
3309
+ const response = await call('Reset', { type });
3310
+ this._assertCallAccepted('Reset', response);
3311
+ await succeed('Reset', response, false);
3312
+ return;
3313
+ }
3314
+
3315
+ if (mAvail) {
3316
+ if (typeof state.val !== 'boolean') throw new Error('Invalid availability');
3317
+ const available = state.val;
3318
+ const response = proto === 'ocpp1.6'
3319
+ ? await call('ChangeAvailability', { connectorId: 0, type: available ? 'Operative' : 'Inoperative' })
3320
+ : await call('ChangeAvailability', { operationalStatus: available ? 'Operative' : 'Inoperative' });
3321
+ this._assertCallAccepted('ChangeAvailability', response);
3322
+ await succeed('ChangeAvailability', response, available);
3323
+ return;
3324
+ }
3325
+
3326
+ if (mPhases) {
3327
+ const phases = Math.max(1, Math.min(3, Math.round(Number(state.val) || 3)));
3328
+ const currentLimit = Math.max(0, Number((await this.getStateAsync(`${identity}.control.chargeLimit`))?.val || 0));
3329
+ if (currentLimit <= 0) {
3330
+ await succeed('numberOfPhases', { stored: true, profileReapplied: false, reason: 'no-active-limit' }, phases);
3331
+ return;
3332
+ }
3333
+ const rawUnit = String((await this.getStateAsync(`${identity}.control.chargeLimitType`))?.val || 'W').trim().toUpperCase();
3334
+ if (!['A','W'].includes(rawUnit)) throw new Error('Invalid limit unit');
3335
+ const rateUnit = rawUnit;
3336
+ const result = await this._queueSmartCharging(identity, currentLimit, rateUnit, phases);
3337
+ if (result.status === 'Superseded') {
3338
+ await ackIfStillCurrent();
3339
+ return;
3340
+ }
3341
+ await succeed(result.method || 'SetChargingProfile', result, phases);
3342
+ return;
3343
+ }
3344
+
3345
+ if (mLimit) {
3346
+ if (typeof state.val !== 'number' || !Number.isFinite(state.val) || state.val < 0) throw new Error('Invalid charging limit');
3347
+ const limit = state.val;
3348
+ const rawUnit = String((await this.getStateAsync(`${identity}.control.chargeLimitType`))?.val || 'W').trim().toUpperCase();
3349
+ if (!['A','W'].includes(rawUnit)) throw new Error('Invalid limit unit');
3350
+ const rateUnit = rawUnit;
3351
+ const phases = Math.max(1, Math.min(3, Math.round(Number((await this.getStateAsync(`${identity}.control.numberOfPhases`))?.val || 3))));
3352
+ const result = await this._queueSmartCharging(identity, limit, rateUnit, phases);
3353
+ if (result.status === 'Superseded') {
3354
+ await ackIfStillCurrent();
3355
+ return;
3356
+ }
3357
+ await succeed(result.method || (result.action === 'clear' ? 'ClearChargingProfile' : 'SetChargingProfile'), result, limit);
3358
+ }
3359
+ } catch (error) {
3360
+ await fail(action, error, offlineAckValue, section);
3361
+ }
3362
+ }
3363
+
3364
+ async onUnload(cb) {
3365
+ this._shuttingDown = true;
3366
+ if (this._eosLeaseTimer) {
3367
+ clearInterval(this._eosLeaseTimer);
3368
+ this._eosLeaseTimer = null;
3369
+ }
3370
+ if (this._watchdogTimer) {
3371
+ clearInterval(this._watchdogTimer);
3372
+ this._watchdogTimer = null;
3373
+ }
3374
+ const identities = [...this.runtimeIndex.keys()];
3375
+ try {
3376
+ if (this.server) await this.server.close();
3377
+ for (const identity of identities) {
3378
+ try { await this._setDisconnectedHealth(identity, 'adapter-stopped'); } catch (e) { /* best effort during shutdown */ }
3379
+ }
3380
+ } catch (e) {
3381
+ this.log.warn(`NexoWatt OCPP shutdown warning: ${e && e.message || e}`);
3382
+ } finally {
3383
+ this.server = null;
3384
+ cb();
3385
+ }
3386
+ }
3387
+ }
3388
+ return NexoWattOcppAdapter;
3389
+ }
3390
+ module.exports = { createOcppRuntime };
3391
+