test_energy_flow.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. """Tests for the energy-flow fallback mapping.
  2. Covers the fallback added for inverter / WiFi-dongle firmware families that
  3. never populate the historical time-series endpoint, leaving every realtime
  4. entity "unknown" while the portal shows live data (issue #7).
  5. The field names and the sample values in ``ISSUE_7_NIGHT_PAYLOAD`` are taken
  6. verbatim from that report, which was captured at night — hence the zeros.
  7. The daylight payloads (``ISSUE_7_AC_PV_CHARGING`` / ``ISSUE_7_NOAC_PV_DISCHARGING``)
  8. are trimmed from hidemichixt-creator's four-state capture set posted
  9. 2026-09-15, which settled the unit and sign questions the night capture
  10. could not.
  11. """
  12. from __future__ import annotations
  13. import pytest
  14. from custom_components.solar_of_things.api import (
  15. SolarOfThingsAPI,
  16. TokenExpiredError,
  17. has_realtime_values,
  18. map_energy_flow_fields,
  19. )
  20. from custom_components.solar_of_things.const import ENERGY_FLOW_UNVERIFIED
  21. # Exactly the fields reported in issue #7 (UWB1 inverter, night-time reading).
  22. ISSUE_7_NIGHT_PAYLOAD = {
  23. "pv1Power": 0,
  24. "pv2Power": 0,
  25. "generationPower": 0,
  26. "batteryPower": 9,
  27. "positiveTerminalBatteryCurrent": 0.4,
  28. "negativeTerminalBatteryCurrent": 0,
  29. "positiveTerminalBatteryVoltage": 26.6,
  30. "bmsBatteryVoltage": 26.6,
  31. "batteryPercentage": 100,
  32. "bmsSOC": 100,
  33. "load_power": 0,
  34. "aPhaseOutputVoltage": 222.8,
  35. "aPhaseOutputFrequency": 50,
  36. }
  37. # Trimmed from UPS_AC_PV_BatteryCharging.txt (issue #7, 2026-09-15): AC
  38. # connected, PV producing, battery charging.
  39. ISSUE_7_AC_PV_CHARGING = {
  40. "pv1Power": 234,
  41. "pv2Power": 0,
  42. "load_power": 0.614, # kW, per the payload's own "unit" field
  43. "aPhaseMainsPower": -1100, # W, per the payload's own "unit" field
  44. "bPhaseMainsPower": 0,
  45. "cPhaseMainsPower": 0,
  46. "positiveTerminalBatteryCurrent": -27,
  47. "negativeTerminalBatteryCurrent": 0,
  48. "batteryPower": -720,
  49. "bmsSOC": 54,
  50. }
  51. # Trimmed from UPS_NoAC_PV_BatteryDischarging.txt (issue #7, 2026-09-15): AC
  52. # disconnected, PV producing, battery discharging.
  53. ISSUE_7_NOAC_PV_DISCHARGING = {
  54. "pv1Power": 262,
  55. "pv2Power": 0,
  56. "load_power": 0.635,
  57. "aPhaseMainsPower": 0,
  58. "bPhaseMainsPower": 0,
  59. "cPhaseMainsPower": 0,
  60. "positiveTerminalBatteryCurrent": 17.6,
  61. "negativeTerminalBatteryCurrent": 0,
  62. "batteryPower": 462,
  63. "bmsSOC": 54,
  64. }
  65. # ─── Pure mapping ──────────────────────────────────────────────────────────────
  66. def test_issue_7_payload_maps_to_canonical_keys() -> None:
  67. """The reported payload must populate the previously-unknown sensors."""
  68. mapped = map_energy_flow_fields(ISSUE_7_NIGHT_PAYLOAD)
  69. # Units confirmed by a non-zero observed value in the report — publishable.
  70. assert mapped["pvInputPower"] == 0.0
  71. assert mapped["batteryVoltage"] == 26.6
  72. assert mapped["batterySOC"] == 100.0
  73. assert mapped["batteryPower"] == 9.0
  74. # Confirmed by the 2026-09-15 daylight captures (see below) — 0 at night
  75. # is a real reading now, not an unconfirmed guess.
  76. assert mapped["acOutputActivePower"] == 0.0
  77. assert mapped["batteryChargingCurrent"] == 0.0
  78. assert mapped["batteryDischargeCurrent"] == 0.4 # idle trickle, per the report
  79. # loadPower (camelCase) has no confirmed source — must stay ABSENT rather
  80. # than publish a possibly-wrong value. See ENERGY_FLOW_UNVERIFIED in const.py.
  81. assert "loadPower" not in mapped
  82. def test_ac_output_power_mapped_from_load_power_kw() -> None:
  83. """load_power is confirmed kW by the payload's own "unit" tag → x1000."""
  84. mapped = map_energy_flow_fields(ISSUE_7_AC_PV_CHARGING)
  85. assert mapped["acOutputActivePower"] == 614.0
  86. def test_grid_import_and_feed_in_split_from_signed_mains_power() -> None:
  87. """aPhaseMainsPower is confirmed W; negative means importing from mains.
  88. Sign confirmed by conservation of power: load (614 W) + battery charging
  89. (720 W) - PV (234 W) = 1100 W, matching |aPhaseMainsPower| exactly.
  90. """
  91. mapped = map_energy_flow_fields(ISSUE_7_AC_PV_CHARGING)
  92. assert mapped["gridPower"] == 1100.0
  93. assert mapped["feedInPower"] == 0.0 # not exporting while importing
  94. # No AC connection at all -> the field reads 0, which is a real
  95. # "no grid" measurement, not a missing one.
  96. mapped_no_ac = map_energy_flow_fields(ISSUE_7_NOAC_PV_DISCHARGING)
  97. assert mapped_no_ac["gridPower"] == 0.0
  98. assert mapped_no_ac["feedInPower"] == 0.0
  99. def test_battery_charging_and_discharge_current_split_by_sign() -> None:
  100. """positiveTerminalBatteryCurrent flips sign with charge direction.
  101. Confirmed across all four states captured for issue #7: negative while
  102. charging, positive while discharging.
  103. """
  104. charging = map_energy_flow_fields(ISSUE_7_AC_PV_CHARGING)
  105. assert charging["batteryChargingCurrent"] == 27.0
  106. assert charging["batteryDischargeCurrent"] == 0.0
  107. discharging = map_energy_flow_fields(ISSUE_7_NOAC_PV_DISCHARGING)
  108. assert discharging["batteryChargingCurrent"] == 0.0
  109. assert discharging["batteryDischargeCurrent"] == 17.6
  110. def test_unverified_fields_are_never_mapped() -> None:
  111. """No field in ENERGY_FLOW_UNVERIFIED may produce a sensor value.
  112. A 1000x-wrong power value feeds the HA Energy dashboard and long-term
  113. statistics, which a later fix cannot un-poison; an inverted charge/discharge
  114. current is actively misleading. Both are worse than an unknown sensor.
  115. This is the guard that stops a well-meaning change from re-enabling one of
  116. these before a confirming capture exists.
  117. """
  118. for field in ENERGY_FLOW_UNVERIFIED:
  119. assert map_energy_flow_fields({field: 500}) == {}, field
  120. # And as a group, mirroring the shape of a real payload.
  121. assert map_energy_flow_fields({f: 500 for f in ENERGY_FLOW_UNVERIFIED}) == {}
  122. def test_multi_string_pv_is_summed_at_face_value() -> None:
  123. """Per-string PV inputs are reported in W and summed without scaling."""
  124. mapped = map_energy_flow_fields(
  125. {"pv1Power": 1200, "pv2Power": 800, "load_power": 1.5}
  126. )
  127. assert mapped["pvInputPower"] == 2000.0
  128. # load_power would need an unconfirmed kW→W conversion, so it stays out.
  129. assert "loadPower" not in mapped
  130. def test_generation_power_is_not_used_as_a_pv_fallback() -> None:
  131. """generationPower is an aggregate in kW and its x1000 is unconfirmed.
  132. Excluding it means a device reporting ONLY generationPower gets an unknown
  133. PV sensor rather than one that may be 1000x wrong.
  134. """
  135. assert map_energy_flow_fields({"generationPower": 2.4}) == {}
  136. # A per-string reading is still mapped when one is present.
  137. assert (
  138. map_energy_flow_fields({"pv1Power": 500, "generationPower": 2.4})[
  139. "pvInputPower"
  140. ]
  141. == 500.0
  142. )
  143. @pytest.mark.parametrize(
  144. ("raw", "expected"),
  145. [
  146. (77, 77.0),
  147. ("77", 77.0),
  148. ({"value": 63}, 63.0),
  149. ([10, 20, 44], 44.0), # latest-wins, as the time-series endpoint returns
  150. ],
  151. )
  152. def test_accepts_the_value_shapes_this_portal_uses(raw, expected) -> None:
  153. assert map_energy_flow_fields({"bmsSOC": raw})["batterySOC"] == expected
  154. @pytest.mark.parametrize("raw", [None, True, False, "n/a", "", {}, []])
  155. def test_rejects_unusable_values_rather_than_publishing_garbage(raw) -> None:
  156. assert "batterySOC" not in map_energy_flow_fields({"bmsSOC": raw})
  157. @pytest.mark.parametrize("payload", [None, {}, [1, 2], "text", 0])
  158. def test_hostile_input_returns_empty_mapping(payload) -> None:
  159. assert map_energy_flow_fields(payload) == {}
  160. def test_unknown_firmware_fields_are_ignored() -> None:
  161. assert map_energy_flow_fields({"someBrandNewKey": 5}) == {}
  162. # ─── Realtime probe ────────────────────────────────────────────────────────────
  163. def test_probe_treats_zero_as_a_real_reading() -> None:
  164. """A device reporting 0 W at night is working — must not trigger fallback."""
  165. assert has_realtime_values({"pvInputPower": 0}) is True
  166. @pytest.mark.parametrize(
  167. "values", [{}, {"pvInputPower": None}, {"loadPower": 5}, None, "text"]
  168. )
  169. def test_probe_false_when_no_realtime_key_has_a_value(values) -> None:
  170. assert has_realtime_values(values) is False
  171. # ─── fetch_latest_data integration ─────────────────────────────────────────────
  172. @pytest.fixture
  173. def api_factory():
  174. """Build an API instance with stubbed transport, tracking endpoint calls."""
  175. def _factory(history_fields, flow_fields=None, flow_error=None):
  176. api = SolarOfThingsAPI(iot_token="test-token")
  177. api._ensure_token_valid = lambda: None # no network
  178. calls = {"time_series": 0, "energy_flow": 0}
  179. def fake_post(path, payload, **kwargs):
  180. calls["time_series"] += 1
  181. return {"code": 0, "data": {"payload": {"fields": history_fields}}}
  182. def fake_get(path, params, **kwargs):
  183. calls["energy_flow"] += 1
  184. if flow_error is not None:
  185. raise flow_error
  186. return {
  187. "code": 0,
  188. "data": {"deviceAttributeState": {"fields": flow_fields or {}}},
  189. }
  190. api._post = fake_post
  191. api._get = fake_get
  192. return api, calls
  193. return _factory
  194. def test_working_device_is_unaffected(api_factory) -> None:
  195. """Regression guard: values and call pattern must match pre-fallback code."""
  196. history = {
  197. "pvInputPower": [100],
  198. "acOutputActivePower": [1.2],
  199. "batteryVoltage": [52.0],
  200. "batteryDischargeCurrent": [2.0],
  201. "batteryChargingCurrent": [0.0],
  202. "feedInPower": [0],
  203. "batterySOC": [90],
  204. }
  205. api, calls = api_factory(history, flow_fields={"bmsSOC": 1})
  206. result = api.fetch_latest_data("device-1")
  207. assert result["acOutputActivePower"] == 1200.0 # kW → W
  208. assert result["batteryPower"] == 104.0 # (2.0 - 0.0) * 52.0
  209. assert result["gridPower"] == 1204.0 # max(0, 1200-100+104+0)
  210. assert result["loadPower"] == 1200.0
  211. # The fallback must cost a working install nothing.
  212. assert calls["energy_flow"] == 0
  213. def test_hpvinv02_alternate_key_names_are_mapped_to_canonical(api_factory) -> None:
  214. """Siseli HPVINV02 ("Inverter Top One" gather protocol) reports PV/AC/SOC
  215. under pvPower / outputActivePower / batteryCapacity instead of the
  216. documented pvInputPower / acOutputActivePower / batterySOC — these stayed
  217. "unknown" forever until the alias mapping was added.
  218. """
  219. history = {
  220. "pvPower": [1.5],
  221. "outputActivePower": [1.1],
  222. "batteryCapacity": [77],
  223. "batteryVoltage": [52.0],
  224. "batteryDischargeCurrent": [2.0],
  225. "batteryChargingCurrent": [0.0],
  226. "feedInPower": [0],
  227. }
  228. api, calls = api_factory(history, flow_fields={"bmsSOC": 1})
  229. result = api.fetch_latest_data("device-hpvinv02")
  230. assert result["pvInputPower"] == 1500.0 # kW → W, via the alias
  231. assert result["acOutputActivePower"] == 1100.0 # kW → W, via the alias
  232. assert result["batterySOC"] == 77
  233. # The alternate keys must not leak into the published values.
  234. assert "pvPower" not in result
  235. assert "outputActivePower" not in result
  236. assert "batteryCapacity" not in result
  237. # Derived values still come from the shared _apply_derived_values path.
  238. assert result["batteryPower"] == 104.0 # (2.0 - 0.0) * 52.0
  239. assert result["loadPower"] == 1100.0
  240. assert calls["energy_flow"] == 0
  241. def test_documented_keys_win_when_a_device_reports_both(api_factory) -> None:
  242. """A device that already uses the documented key names must be unaffected
  243. by the alias — the canonical value always wins, the alias is discarded,
  244. and (critically) pvInputPower is NOT kW->W converted on this path: it's
  245. already W for every device this integration supported before HPVINV02,
  246. and converting it unconditionally regressed test_working_device_is_unaffected.
  247. """
  248. history = {
  249. "pvInputPower": [2.0],
  250. "pvPower": [999],
  251. "acOutputActivePower": [1.0],
  252. "batterySOC": [55],
  253. "batteryCapacity": [10],
  254. }
  255. api, _ = api_factory(history, flow_fields={})
  256. result = api.fetch_latest_data("device-both-keys")
  257. assert result["pvInputPower"] == 2.0
  258. assert result["batterySOC"] == 55
  259. def test_fallback_populates_sensors_when_time_series_is_empty(api_factory) -> None:
  260. api, calls = api_factory({}, flow_fields=ISSUE_7_NIGHT_PAYLOAD)
  261. result = api.fetch_latest_data("device-2")
  262. assert calls["energy_flow"] == 1
  263. assert result["batteryVoltage"] == 26.6
  264. assert result["batterySOC"] == 100.0
  265. assert result["batteryPower"] == 9.0
  266. def test_measured_battery_power_is_not_overwritten_by_the_estimate(api_factory) -> None:
  267. """The flow endpoint reports batteryPower directly; keep it.
  268. The terminal currents are no longer mapped from flow data (direction
  269. unconfirmed), so no voltage x current estimate can be derived from this
  270. payload at all — but the no-clobber precedence must still hold for devices
  271. that get their currents from the time-series path.
  272. """
  273. api, _ = api_factory({}, flow_fields=ISSUE_7_NIGHT_PAYLOAD)
  274. assert api.fetch_latest_data("device-3")["batteryPower"] == 9.0
  275. def test_time_series_values_win_over_the_fallback(api_factory) -> None:
  276. api, calls = api_factory({"batterySOC": [42]}, flow_fields={"bmsSOC": 99})
  277. result = api.fetch_latest_data("device-4")
  278. assert result["batterySOC"] == 42
  279. assert calls["energy_flow"] == 0
  280. def test_flow_endpoint_failure_degrades_quietly(api_factory) -> None:
  281. """An unsupported endpoint must not fail the whole coordinator update."""
  282. api, _ = api_factory({}, flow_error=RuntimeError("404 not supported"))
  283. result = api.fetch_latest_data("device-5")
  284. assert isinstance(result, dict)
  285. assert result["loadPower"] == 0.0
  286. def test_token_expiry_propagates_for_reauth(api_factory) -> None:
  287. """TokenExpiredError must reach the coordinator so re-auth can start."""
  288. api, _ = api_factory({}, flow_error=TokenExpiredError("expired"))
  289. with pytest.raises(TokenExpiredError):
  290. api.fetch_latest_data("device-6")
  291. def test_unknown_firmware_logs_field_names_for_reporting(api_factory, caplog) -> None:
  292. api, _ = api_factory({}, flow_fields={"someBrandNewKey": 5, "another": 7})
  293. api.fetch_latest_data("device-7")
  294. assert "another" in caplog.text and "someBrandNewKey" in caplog.text