test_energy_flow.py 15 KB

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