test_mqtt_lifetime_energy_3582.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """#3582: an MQTT plug's lifetime energy counter, beside its daily one.
  2. Per-print energy is the difference of two "total" readings. An MQTT plug had
  3. one energy value and used it as both today and total, so with a daily counter
  4. (Tasmota ``ENERGY.Today``) a print running across midnight came out negative
  5. (and was dropped) or too small. A plug with ``mqtt_energy_total_path`` reads
  6. the lifetime counter from the same topic; one without keeps the old reading.
  7. """
  8. import json
  9. from contextlib import asynccontextmanager
  10. from types import SimpleNamespace
  11. from unittest.mock import patch
  12. import pytest
  13. from sqlalchemy import select
  14. from backend.app.services.energy_plug import select_energy_reading
  15. from backend.app.services.mqtt_smart_plug import MQTTSmartPlugService, subscribe_plug_to_mqtt
  16. from backend.app.services.plug_energy import get_plug_energy
  17. TOPIC = "tele/tasmota_plug/SENSOR"
  18. def _sensor(today: float, total: float) -> SimpleNamespace:
  19. """A Tasmota SENSOR message carrying both counters."""
  20. payload = {"ENERGY": {"Today": today, "Total": total, "Power": 150}}
  21. return SimpleNamespace(topic=TOPIC, payload=json.dumps(payload).encode())
  22. def _plug(plug_id: int = 7, total_path: str | None = "ENERGY.Total", total_multiplier: float = 1.0):
  23. return SimpleNamespace(
  24. id=plug_id,
  25. plug_type="mqtt",
  26. mqtt_topic=None,
  27. mqtt_multiplier=None,
  28. mqtt_power_topic=TOPIC,
  29. mqtt_power_path="ENERGY.Power",
  30. mqtt_power_multiplier=1.0,
  31. mqtt_energy_topic=TOPIC,
  32. mqtt_energy_path="ENERGY.Today",
  33. mqtt_energy_multiplier=1.0,
  34. mqtt_energy_total_path=total_path,
  35. mqtt_energy_total_multiplier=total_multiplier,
  36. mqtt_state_topic=None,
  37. mqtt_state_path=None,
  38. mqtt_state_on_value=None,
  39. )
  40. def _service_with(plug) -> MQTTSmartPlugService:
  41. service = MQTTSmartPlugService()
  42. subscribe_plug_to_mqtt(service, plug)
  43. return service
  44. class TestSubscription:
  45. def test_both_counters_are_read_from_one_message(self):
  46. plug = _plug()
  47. service = _service_with(plug)
  48. service._on_message(None, None, _sensor(today=1.25, total=842.5))
  49. data = service.get_plug_data(plug.id)
  50. assert data.energy == pytest.approx(1.25)
  51. assert data.energy_total == pytest.approx(842.5)
  52. def test_lifetime_multiplier_is_its_own(self):
  53. """A device reporting Wh for the lifetime counter only."""
  54. plug = _plug(total_multiplier=0.001)
  55. service = _service_with(plug)
  56. service._on_message(None, None, _sensor(today=1.25, total=842500))
  57. data = service.get_plug_data(plug.id)
  58. assert data.energy == pytest.approx(1.25)
  59. assert data.energy_total == pytest.approx(842.5)
  60. def test_without_a_lifetime_path_nothing_is_read_for_it(self):
  61. plug = _plug(total_path=None)
  62. service = _service_with(plug)
  63. service._on_message(None, None, _sensor(today=1.25, total=842.5))
  64. data = service.get_plug_data(plug.id)
  65. assert data.energy == pytest.approx(1.25)
  66. assert data.energy_total is None
  67. def test_blank_lifetime_path_counts_as_unset(self):
  68. plug = _plug(total_path=" ")
  69. service = _service_with(plug)
  70. service._on_message(None, None, _sensor(today=1.25, total=842.5))
  71. assert service.get_plug_data(plug.id).energy_total is None
  72. assert "energy_total" not in service.plug_configs[plug.id]
  73. class TestPerPrintAcrossMidnight:
  74. async def _reading(self, service, plug):
  75. with patch("backend.app.services.plug_energy.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
  76. return await get_plug_energy(plug, None)
  77. @pytest.mark.asyncio
  78. async def test_a_print_across_midnight_keeps_its_energy(self):
  79. plug = _plug()
  80. service = _service_with(plug)
  81. # 23:00: 4.8 kWh today, 842.5 lifetime. 01:00: the daily counter
  82. # restarted at midnight, the lifetime one kept counting.
  83. service._on_message(None, None, _sensor(today=4.8, total=842.5))
  84. start = await self._reading(service, plug)
  85. service._on_message(None, None, _sensor(today=0.3, total=843.4))
  86. end = await self._reading(service, plug)
  87. assert end["total"] - start["total"] == pytest.approx(0.9)
  88. assert end["today"] == pytest.approx(0.3)
  89. @pytest.mark.asyncio
  90. async def test_without_a_lifetime_path_the_one_value_is_both(self):
  91. """Unchanged for existing plugs: right when the topic is a lifetime counter."""
  92. plug = _plug(total_path=None)
  93. service = _service_with(plug)
  94. service._on_message(None, None, _sensor(today=4.8, total=842.5))
  95. reading = await self._reading(service, plug)
  96. assert reading["today"] == pytest.approx(4.8)
  97. assert reading["total"] == pytest.approx(4.8)
  98. @pytest.mark.asyncio
  99. async def test_no_lifetime_reading_yet_is_not_picked_as_the_counter(self):
  100. """Only the daily value has arrived: the plug must not stand in for a
  101. lifetime counter, or the print's start reading is the daily one."""
  102. plug = _plug()
  103. service = MQTTSmartPlugService()
  104. subscribe_plug_to_mqtt(service, plug)
  105. service._on_message(
  106. None,
  107. None,
  108. SimpleNamespace(topic=TOPIC, payload=json.dumps({"ENERGY": {"Today": 4.8}}).encode()),
  109. )
  110. async def read(p, db):
  111. return await self._reading(service, p)
  112. assert await select_energy_reading([plug], read, None) is None
  113. @pytest.fixture
  114. def patched_session(db_session):
  115. @asynccontextmanager
  116. async def _session():
  117. yield db_session
  118. with patch("backend.app.core.database.async_session", _session):
  119. yield
  120. class TestSnapshotsAndTotals:
  121. @pytest.mark.asyncio
  122. async def test_hourly_snapshot_takes_the_lifetime_counter(self, db_session, smart_plug_factory, patched_session):
  123. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  124. from backend.app.services import smart_plug_manager as manager_module
  125. lifetime = await smart_plug_factory(
  126. name="Tasmota",
  127. plug_type="mqtt",
  128. mqtt_energy_topic=TOPIC,
  129. mqtt_energy_path="ENERGY.Today",
  130. mqtt_energy_total_path="ENERGY.Total",
  131. )
  132. daily_only = await smart_plug_factory(
  133. name="Daily", plug_type="mqtt", mqtt_energy_topic=TOPIC, mqtt_energy_path="ENERGY.Today"
  134. )
  135. service = MQTTSmartPlugService()
  136. subscribe_plug_to_mqtt(service, lifetime)
  137. subscribe_plug_to_mqtt(service, daily_only)
  138. service._on_message(None, None, _sensor(today=4.8, total=842.5))
  139. with patch("backend.app.services.plug_energy.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
  140. await manager_module.SmartPlugManager()._capture_energy_snapshots()
  141. rows = (await db_session.execute(select(SmartPlugEnergySnapshot))).scalars().all()
  142. # The daily-only plug may hold a daily counter: never snapshotted.
  143. assert [(row.plug_id, row.lifetime_kwh) for row in rows] == [(lifetime.id, pytest.approx(842.5))]
  144. @pytest.mark.asyncio
  145. async def test_statistics_lifetime_total_reads_the_lifetime_counter(self, db_session, smart_plug_factory):
  146. from backend.app.api.routes.archives import _sum_live_plug_totals
  147. lifetime = await smart_plug_factory(
  148. name="Tasmota",
  149. plug_type="mqtt",
  150. mqtt_energy_topic=TOPIC,
  151. mqtt_energy_path="ENERGY.Today",
  152. mqtt_energy_total_path="ENERGY.Total",
  153. )
  154. daily_only = await smart_plug_factory(
  155. name="Daily", plug_type="mqtt", mqtt_energy_topic=TOPIC, mqtt_energy_path="ENERGY.Today"
  156. )
  157. service = MQTTSmartPlugService()
  158. subscribe_plug_to_mqtt(service, lifetime)
  159. subscribe_plug_to_mqtt(service, daily_only)
  160. service._on_message(None, None, _sensor(today=4.8, total=842.5))
  161. with patch("backend.app.services.mqtt_relay.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
  162. total = await _sum_live_plug_totals(db_session)
  163. # 842.5 lifetime from the first, the one value (4.8) from the second.
  164. assert total == pytest.approx(842.5 + 4.8)
  165. class TestValidation:
  166. def test_lifetime_path_needs_an_energy_topic(self):
  167. from pydantic import ValidationError
  168. from backend.app.schemas.smart_plug import SmartPlugCreate
  169. with pytest.raises(ValidationError, match="lifetime energy path needs an energy topic"):
  170. SmartPlugCreate(
  171. name="P",
  172. plug_type="mqtt",
  173. mqtt_power_topic="p/power",
  174. mqtt_energy_total_path="ENERGY.Total",
  175. )
  176. def test_legacy_topic_serves_as_the_energy_topic(self):
  177. from backend.app.schemas.smart_plug import SmartPlugCreate
  178. plug = SmartPlugCreate(name="P", plug_type="mqtt", mqtt_topic=TOPIC, mqtt_energy_total_path="ENERGY.Total")
  179. assert plug.mqtt_energy_total_path == "ENERGY.Total"