Преглед изворни кода

Smart plugs: an MQTT plug keeps a print's energy across midnight (#3582)

- MQTT plugs get a lifetime energy path and multiplier, read from
  the energy topic (Tasmota ENERGY.Total beside ENERGY.Today).
- With it set, per-print energy and cost use the counter that
  never resets, the plug feeds the hourly snapshots and the
  lifetime total, and its status shows Today and Total.
- Without it, the one energy value is read as both, as before.
- Migration adds the two columns on SQLite and Postgres.
- Translated in all locales.
maziggy пре 3 дана
родитељ
комит
220be65e5b
34 измењених фајлова са 684 додато и 17 уклоњено
  1. 1 0
      CHANGELOG.md
  2. 7 3
      backend/app/api/routes/archives.py
  3. 12 1
      backend/app/api/routes/smart_plugs.py
  4. 12 0
      backend/app/core/database.py
  5. 7 0
      backend/app/models/smart_plug.py
  6. 9 0
      backend/app/schemas/smart_plug.py
  7. 27 1
      backend/app/services/mqtt_smart_plug.py
  8. 20 5
      backend/app/services/plug_energy.py
  9. 11 7
      backend/app/services/smart_plug_manager.py
  10. 99 0
      backend/tests/integration/test_mqtt_plug_lifetime_energy_3582.py
  11. 2 0
      backend/tests/unit/services/test_mqtt_smart_plug_subscribe.py
  12. 233 0
      backend/tests/unit/test_mqtt_lifetime_energy_3582.py
  13. 114 0
      backend/tests/unit/test_mqtt_lifetime_energy_migration_3582.py
  14. 38 0
      frontend/src/__tests__/components/AddSmartPlugModalWiring.test.tsx
  15. 2 0
      frontend/src/__tests__/components/SmartPlugCard.test.tsx
  16. 2 0
      frontend/src/__tests__/components/spoolbuddy/SpoolBuddyQuickMenu.test.tsx
  17. 6 0
      frontend/src/api/client.ts
  18. 34 0
      frontend/src/components/AddSmartPlugModal.tsx
  19. 3 0
      frontend/src/i18n/locales/de.ts
  20. 3 0
      frontend/src/i18n/locales/en.ts
  21. 3 0
      frontend/src/i18n/locales/es.ts
  22. 3 0
      frontend/src/i18n/locales/fr.ts
  23. 3 0
      frontend/src/i18n/locales/it.ts
  24. 3 0
      frontend/src/i18n/locales/ja.ts
  25. 3 0
      frontend/src/i18n/locales/ko.ts
  26. 3 0
      frontend/src/i18n/locales/nl.ts
  27. 3 0
      frontend/src/i18n/locales/pl.ts
  28. 3 0
      frontend/src/i18n/locales/pt-BR.ts
  29. 3 0
      frontend/src/i18n/locales/ru.ts
  30. 3 0
      frontend/src/i18n/locales/sv.ts
  31. 3 0
      frontend/src/i18n/locales/tr.ts
  32. 3 0
      frontend/src/i18n/locales/uk.ts
  33. 3 0
      frontend/src/i18n/locales/zh-CN.ts
  34. 3 0
      frontend/src/i18n/locales/zh-TW.ts

+ 1 - 0
CHANGELOG.md

@@ -14,6 +14,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **An MQTT plug keeps a print's energy across midnight (#3582, reported by @paulleonartcalvo)** — A print's energy is what the plug's counter went up by between its start and its end, and an MQTT plug had one energy value that Bambuddy used as both today's and the lifetime counter. Many devices publish a daily counter there (Tasmota's `ENERGY.Today`), which drops back to zero at midnight: a print that ran past midnight came out negative and got no energy or energy cost, or ended above its start and silently lost everything before midnight. MQTT plugs now have an **Energy JSON Path (lifetime)** and its own multiplier, read from the energy topic, for the counter that never resets (Tasmota's `ENERGY.Total`, in the same message). With it set, per-print energy and cost use the lifetime counter, the plug feeds the hourly snapshots behind the Statistics date filters and the all-time total, and the energy summary under Settings > Smart Plugs counts it in the lifetime total. A topic with only the lifetime counter still gets a Today, worked out from the snapshots. Without it, a plug reads its one energy value as before, so nothing changes for a topic that already carries a lifetime counter. Translated in all locales; wiki updated. Covered by backend and frontend tests.
 - **A first Git backup to an empty GitHub repository works (#3565, reported by @pike00)** — GitHub answers a repository with no commits with HTTP 409 "Git Repository is empty", and Bambuddy stopped there with "Failed to get branch ref", although Test Connection passed. Its fallback for an empty repository could not have helped either: it builds the first commit from blobs and trees, and GitHub refuses those too until the repository has a commit. The first backup now makes that commit through GitHub's Contents API, which writes one file, and pushes the rest on top, so no README or placeholder file is needed. Any other 409 is still reported as an error. Wiki updated.
 - **A printer that reconnects no longer waits out its upload backoff (#3563, reported by @Costyv95)** — When a printer's file service stops answering, Bambuddy sends it no jobs for a while, five minutes after the first refused upload and doubling up to an hour. Restarting the printer fixed its file service, but the queue still waited out the rest of that hour, and only restarting Bambuddy sent the job. A printer that reconnects is now tried again on the next pass, and the FTP cool-off from before the reconnect no longer blocks that try. If it still refuses, the next wait is the longer one and no second Job Waiting notification is sent. Wiki updated.
 - **Spoolman mode reads the subtype and colour from a filament named after its product (#3561, reported by @ARGACE)** — Spoolman has no subtype or colour-name field, so Bambuddy reads both from the filament's name, and it only understood names it writes itself ("PLA Matte"). A filament named "Matte Scarlet Red", "Silk+ Baby Blue" or "Gold - Basic PLA" got its whole name as the subtype and no colour, so the spool form left the colour blank. The finish words (Basic, Matte, Silk, HF, ...) are now the subtype and the rest of the name is the colour, wherever the material stands in it. Saving a spool also renamed its Spoolman filament to "material subtype" on every save; the name is now only rebuilt when the material or subtype is changed.

+ 7 - 3
backend/app/api/routes/archives.py

@@ -1942,6 +1942,7 @@ async def _sum_live_plug_totals(db: AsyncSession) -> float:
     from backend.app.models.smart_plug import SmartPlug
     from backend.app.services.homeassistant import homeassistant_service
     from backend.app.services.mqtt_relay import mqtt_relay
+    from backend.app.services.plug_energy import mqtt_has_lifetime_counter
     from backend.app.services.rest_smart_plug import rest_smart_plug_service
     from backend.app.services.tasmota import tasmota_service
 
@@ -1962,10 +1963,13 @@ async def _sum_live_plug_totals(db: AsyncSession) -> float:
             if energy and energy.get("total") is not None:
                 total += energy["total"]
         elif plug.plug_type == "mqtt":
-            # MQTT plugs only expose today's counter, not lifetime.
+            # The lifetime counter when the plug has one (#3582), else its one
+            # energy value, as before.
             mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
-            if mqtt_data and mqtt_data.energy is not None:
-                total += mqtt_data.energy
+            if mqtt_data:
+                value = mqtt_data.energy_total if mqtt_has_lifetime_counter(plug) else mqtt_data.energy
+                if value is not None:
+                    total += value
         elif plug.plug_type == "rest":
             # A REST device that exposes only a lifetime counter (Shelly
             # ``aenergy.total`` via ``rest_energy_total_path``) returns no

+ 12 - 1
backend/app/api/routes/smart_plugs.py

@@ -43,6 +43,7 @@ from backend.app.services.discovery import tasmota_scanner
 from backend.app.services.homeassistant import homeassistant_service
 from backend.app.services.mqtt_relay import mqtt_relay
 from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
+from backend.app.services.plug_energy import mqtt_has_lifetime_counter
 from backend.app.services.plug_energy_history import fill_derived_energy
 from backend.app.services.printer_manager import printer_manager
 from backend.app.services.rest_smart_plug import rest_smart_plug_service
@@ -675,6 +676,8 @@ async def update_smart_plug(
         "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
         "energy_path": plug.mqtt_energy_path,
         "energy_multiplier": plug.mqtt_energy_multiplier,
+        "energy_total_path": plug.mqtt_energy_total_path,
+        "energy_total_multiplier": plug.mqtt_energy_total_multiplier,
         "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
         "state_path": plug.mqtt_state_path,
         "state_on_value": plug.mqtt_state_on_value,
@@ -699,6 +702,8 @@ async def update_smart_plug(
             "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
             "energy_path": plug.mqtt_energy_path,
             "energy_multiplier": plug.mqtt_energy_multiplier,
+            "energy_total_path": plug.mqtt_energy_total_path,
+            "energy_total_multiplier": plug.mqtt_energy_total_multiplier,
             "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
             "state_path": plug.mqtt_state_path,
             "state_on_value": plug.mqtt_state_on_value,
@@ -864,7 +869,13 @@ async def get_plug_status(
                 await db.commit()
 
             energy_data = None
-            if data.power is not None or data.energy is not None:
+            if mqtt_has_lifetime_counter(plug):
+                # Today and Yesterday come from the hourly snapshots when the
+                # topic carries only the lifetime counter (#3582).
+                if data.power is not None or data.energy is not None or data.energy_total is not None:
+                    energy = {"power": data.power, "today": data.energy, "total": data.energy_total}
+                    energy_data = SmartPlugEnergy(**await fill_derived_energy(db, plug.id, energy))
+            elif data.power is not None or data.energy is not None:
                 energy_data = SmartPlugEnergy(
                     power=data.power,
                     today=data.energy,

+ 12 - 0
backend/app/core/database.py

@@ -6126,6 +6126,18 @@ async def _run_migrations(conn):
         "ALTER TABLE spool_assignment ADD COLUMN assigned_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL",
     )
 
+    # Migration: an MQTT plug's lifetime energy counter, separate from its daily
+    # one (#3582). A print's energy is the difference of two readings, so a
+    # daily counter that resets at midnight lost any print running across it.
+    # Nullable path, no backfill: existing plugs read their one energy value as
+    # before. The multiplier is NOT NULL with the model's server default, and
+    # gets the model's float type on Postgres from the start.
+    float_type = "REAL" if is_sqlite() else "DOUBLE PRECISION"
+    await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_total_path VARCHAR(100)")
+    await _safe_execute(
+        conn, f"ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_total_multiplier {float_type} NOT NULL DEFAULT '1.0'"
+    )
+
     await _backfill_archive_run_photos(conn)
     await _migrate_h3c_queue_tray_ids(conn)
 

+ 7 - 0
backend/app/models/smart_plug.py

@@ -39,6 +39,13 @@ class SmartPlug(Base):
     mqtt_energy_topic: Mapped[str | None] = mapped_column(String(200), nullable=True)  # Topic for energy data
     mqtt_energy_path: Mapped[str | None] = mapped_column(String(100), nullable=True)  # e.g., "energy_l1"
     mqtt_energy_multiplier: Mapped[float] = mapped_column(Float, default=1.0)  # Unit conversion for energy
+    # Lifetime counter that never resets, read from the energy topic (#3582).
+    # A Tasmota publishes ENERGY.Today and ENERGY.Total in the same SENSOR
+    # message. Per-print energy is the difference of two readings, so it needs
+    # this counter: a daily one drops back to zero at midnight and loses the
+    # print. Unset, the energy path is still used as both, as before.
+    mqtt_energy_total_path: Mapped[str | None] = mapped_column(String(100), nullable=True)
+    mqtt_energy_total_multiplier: Mapped[float] = mapped_column(Float, nullable=False, server_default="1.0")
 
     # State monitoring
     mqtt_state_topic: Mapped[str | None] = mapped_column(String(200), nullable=True)  # Topic for state data

+ 9 - 0
backend/app/schemas/smart_plug.py

@@ -47,6 +47,10 @@ class SmartPlugBase(BaseModel):
     mqtt_energy_topic: str | None = Field(default=None, max_length=200)  # Topic for energy data
     mqtt_energy_path: str | None = Field(default=None, max_length=100)  # e.g., "energy_l1"
     mqtt_energy_multiplier: float = Field(default=1.0, gt=0, le=10000)  # Unit conversion for energy
+    # Lifetime counter on the energy topic that never resets (#3582), e.g.
+    # Tasmota's ENERGY.Total. Per-print energy reads it when set.
+    mqtt_energy_total_path: str | None = Field(default=None, max_length=100)
+    mqtt_energy_total_multiplier: float = Field(default=1.0, gt=0, le=10000)
 
     # State monitoring
     mqtt_state_topic: str | None = Field(default=None, max_length=200)  # Topic for state data
@@ -125,6 +129,9 @@ class SmartPlugBase(BaseModel):
             # At least one data source must be configured (path is optional)
             if not has_power and not has_energy and not has_state:
                 raise ValueError("At least one MQTT topic must be configured for power, energy, or state monitoring")
+            # The lifetime counter is read from the energy topic's JSON.
+            if (self.mqtt_energy_total_path or "").strip() and not (self.mqtt_energy_topic or self.mqtt_topic):
+                raise ValueError("The lifetime energy path needs an energy topic")
         if self.plug_type == "rest":
             if not self.rest_on_url and not self.rest_off_url:
                 raise ValueError("At least one of ON URL or OFF URL is required for REST plugs")
@@ -156,6 +163,8 @@ class SmartPlugUpdate(IgnoresNullForRequiredColumns):
     mqtt_energy_topic: str | None = None
     mqtt_energy_path: str | None = None
     mqtt_energy_multiplier: float | None = Field(default=None, gt=0, le=10000)
+    mqtt_energy_total_path: str | None = None
+    mqtt_energy_total_multiplier: float | None = Field(default=None, gt=0, le=10000)
     # MQTT state fields
     mqtt_state_topic: str | None = None
     mqtt_state_path: str | None = None

+ 27 - 1
backend/app/services/mqtt_smart_plug.py

@@ -25,6 +25,7 @@ class SmartPlugMQTTData:
     plug_id: int
     power: float | None = None  # Current power in watts
     energy: float | None = None  # Energy in kWh (today)
+    energy_total: float | None = None  # Lifetime kWh, never resets (#3582)
     state: str | None = None  # "ON" or "OFF"
     # Aware, like the value a received message sets: is_reachable subtracts it
     # from an aware now, which raised TypeError before the first message.
@@ -51,7 +52,8 @@ class MQTTSmartPlugService:
         self.client: mqtt.Client | None = None
         self.connected = False
         self._lock = threading.Lock()
-        # topic -> list of (plug_id, data_type) where data_type is "power", "energy", or "state"
+        # topic -> list of (plug_id, data_type) where data_type is "power",
+        # "energy", "energy_total" or "state"
         self.subscriptions: dict[str, list[tuple[int, str]]] = {}
         # plug_id -> {data_type: MQTTDataSourceConfig}
         self.plug_configs: dict[int, dict[str, MQTTDataSourceConfig]] = {}
@@ -279,6 +281,13 @@ class MQTTSmartPlugService:
                     except (ValueError, TypeError):
                         pass  # Ignore unparseable energy reading from MQTT
 
+                elif data_type == "energy_total":
+                    try:
+                        data.energy_total = float(raw_value) * config.multiplier
+                        logger.debug("MQTT smart plug %s: energy_total=%s", plug_id, data.energy_total)
+                    except (ValueError, TypeError):
+                        pass  # Ignore unparseable energy reading from MQTT
+
                 elif data_type == "state":
                     state_str = str(raw_value)
                     # Check against configured ON value if set
@@ -343,6 +352,9 @@ class MQTTSmartPlugService:
         energy_topic: str | None = None,
         energy_path: str | None = None,
         energy_multiplier: float = 1.0,
+        # Lifetime energy counter, read from the energy topic (#3582)
+        energy_total_path: str | None = None,
+        energy_total_multiplier: float = 1.0,
         # State source
         state_topic: str | None = None,
         state_path: str | None = None,
@@ -390,6 +402,17 @@ class MQTTSmartPlugService:
                 self.plug_configs[plug_id]["energy"] = config
                 self._add_subscription(plug_id, effective_energy_topic, "energy")
 
+            # The lifetime counter sits beside the daily one in the same message
+            # (Tasmota's ENERGY.Total next to ENERGY.Today), so it needs a path:
+            # a raw payload can only be one of the two.
+            if effective_energy_topic and energy_total_path:
+                self.plug_configs[plug_id]["energy_total"] = MQTTDataSourceConfig(
+                    topic=effective_energy_topic,
+                    path=energy_total_path,
+                    multiplier=energy_total_multiplier,
+                )
+                self._add_subscription(plug_id, effective_energy_topic, "energy_total")
+
             # Configure state subscription (path is optional - empty means use raw payload)
             if effective_state_topic:
                 config = MQTTDataSourceConfig(
@@ -408,6 +431,7 @@ class MQTTSmartPlugService:
                 f"MQTT smart plug {plug_id}: configured with "
                 f"power={effective_power_topic if power_path else None}, "
                 f"energy={effective_energy_topic if energy_path else None}, "
+                f"energy_total={effective_energy_topic if energy_total_path else None}, "
                 f"state={effective_state_topic if state_path else None}"
             )
 
@@ -518,6 +542,8 @@ def subscribe_plug_to_mqtt(service: "MQTTSmartPlugService", plug: Any) -> list[s
         energy_topic=energy_topic,
         energy_path=plug.mqtt_energy_path,
         energy_multiplier=plug.mqtt_energy_multiplier or legacy_mult,
+        energy_total_path=(plug.mqtt_energy_total_path or "").strip() or None,
+        energy_total_multiplier=plug.mqtt_energy_total_multiplier or 1.0,
         state_topic=state_topic,
         state_path=plug.mqtt_state_path,
         state_on_value=plug.mqtt_state_on_value,

+ 20 - 5
backend/app/services/plug_energy.py

@@ -17,6 +17,11 @@ async def _configured_homeassistant(db: AsyncSession):
     return homeassistant_service
 
 
+def mqtt_has_lifetime_counter(plug: SmartPlug) -> bool:
+    """Whether an MQTT plug reads a lifetime counter beside its daily one (#3582)."""
+    return bool((plug.mqtt_energy_total_path or "").strip())
+
+
 async def get_plug_energy(plug: SmartPlug, db: AsyncSession) -> dict | None:
     """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
 
@@ -27,16 +32,26 @@ async def get_plug_energy(plug: SmartPlug, db: AsyncSession) -> dict | None:
     if plug.plug_type == "homeassistant":
         return await (await _configured_homeassistant(db)).get_energy(plug)
     elif plug.plug_type == "mqtt":
-        # MQTT plugs report "today" energy, not lifetime total
-        # For per-print tracking, we use "today" as the counter (resets at midnight)
         mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
-        if mqtt_data:
+        if not mqtt_data:
+            return None
+        if mqtt_has_lifetime_counter(plug):
+            # Per-print energy is the difference of two "total" readings, so it
+            # must come from the counter that never resets (#3582). None until
+            # the first message, so the plug is not picked as the counter.
             return {
                 "power": mqtt_data.power,
                 "today": mqtt_data.energy,
-                "total": mqtt_data.energy,  # Use today as total for per-print calculations
+                "total": mqtt_data.energy_total,
             }
-        return None
+        # One energy value and no telling which counter it is: used as both,
+        # as always. Right for a lifetime counter; a daily one loses a print
+        # across midnight, which is what the lifetime path is for.
+        return {
+            "power": mqtt_data.power,
+            "today": mqtt_data.energy,
+            "total": mqtt_data.energy,
+        }
     elif plug.plug_type == "rest":
         return await rest_smart_plug_service.get_energy(plug)
     else:

+ 11 - 7
backend/app/services/smart_plug_manager.py

@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
 from backend.app.core.tasks import spawn_background_task
 from backend.app.services.homeassistant import homeassistant_service
 from backend.app.services.mqtt_relay import mqtt_relay
-from backend.app.services.plug_energy import get_plug_energy
+from backend.app.services.plug_energy import get_plug_energy, mqtt_has_lifetime_counter
 from backend.app.services.printer_manager import printer_manager
 from backend.app.services.rest_smart_plug import rest_smart_plug_service
 from backend.app.services.tasmota import tasmota_service
@@ -329,14 +329,18 @@ class SmartPlugManager:
             price = await current_price(db, remember=True)
             captured = 0
             for plug in plugs:
-                # MQTT plugs only publish a "today" counter that resets at midnight —
-                # they can never feed cumulative snapshots, so skip them outright to
-                # avoid a noisy tasmota-service fallback attempt on an IP-less plug.
-                if plug.plug_type == "mqtt":
+                # An MQTT plug feeds the snapshots only with its lifetime counter
+                # (#3582); its one legacy energy value may be a daily counter that
+                # resets at midnight. Read through get_plug_energy, not the
+                # service lookup, which would fall back to Tasmota on an IP-less plug.
+                if plug.plug_type == "mqtt" and not mqtt_has_lifetime_counter(plug):
                     continue
                 try:
-                    service = await self.get_service_for_plug(plug, db)
-                    energy = await service.get_energy(plug)
+                    if plug.plug_type == "mqtt":
+                        energy = await get_plug_energy(plug, db)
+                    else:
+                        service = await self.get_service_for_plug(plug, db)
+                        energy = await service.get_energy(plug)
                 except Exception as e:
                     logger.debug("Snapshot: failed to read energy from plug %s: %s", plug.id, e)
                     continue

+ 99 - 0
backend/tests/integration/test_mqtt_plug_lifetime_energy_3582.py

@@ -0,0 +1,99 @@
+"""#3582: the MQTT plug's lifetime energy path through the smart plug API."""
+
+import pytest
+from httpx import AsyncClient
+
+from backend.app.services.mqtt_smart_plug import SmartPlugMQTTData
+
+TOPIC = "tele/tasmota_plug/SENSOR"
+
+
+def _payload(**overrides) -> dict:
+    data = {
+        "name": "Tasmota MQTT",
+        "plug_type": "mqtt",
+        "mqtt_energy_topic": TOPIC,
+        "mqtt_energy_path": "ENERGY.Today",
+        "mqtt_energy_total_path": "ENERGY.Total",
+        "mqtt_energy_total_multiplier": 0.001,
+        "enabled": True,
+    }
+    data.update(overrides)
+    return data
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_create_stores_and_subscribes_the_lifetime_path(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    response = await async_client.post("/api/v1/smart-plugs/", json=_payload())
+
+    assert response.status_code == 200, response.text
+    body = response.json()
+    assert body["mqtt_energy_total_path"] == "ENERGY.Total"
+    assert body["mqtt_energy_total_multiplier"] == 0.001
+    kwargs = mock_mqtt_smart_plug_service.smart_plug_service.subscribe.call_args.kwargs
+    assert kwargs["energy_topic"] == TOPIC
+    assert kwargs["energy_total_path"] == "ENERGY.Total"
+    assert kwargs["energy_total_multiplier"] == 0.001
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_create_without_energy_topic_is_refused(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    response = await async_client.post(
+        "/api/v1/smart-plugs/",
+        json=_payload(mqtt_energy_topic=None, mqtt_power_topic="p/power"),
+    )
+
+    assert response.status_code == 422
+    assert "lifetime energy path needs an energy topic" in response.text
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_changing_only_the_lifetime_path_resubscribes(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload(mqtt_energy_total_path=None))).json()
+    assert service.subscribe.call_args.kwargs["energy_total_path"] is None
+    service.subscribe.reset_mock()
+
+    response = await async_client.patch(
+        f"/api/v1/smart-plugs/{created['id']}", json={"mqtt_energy_total_path": "ENERGY.Total"}
+    )
+
+    assert response.status_code == 200, response.text
+    service.unsubscribe.assert_called_once_with(created["id"])
+    assert service.subscribe.call_args.kwargs["energy_total_path"] == "ENERGY.Total"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_status_reports_today_and_lifetime_separately(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload())).json()
+    service.get_plug_data.return_value = SmartPlugMQTTData(
+        plug_id=created["id"], power=150.0, energy=0.3, energy_total=843.4, state="ON"
+    )
+    service.is_reachable.return_value = True
+
+    response = await async_client.get(f"/api/v1/smart-plugs/{created['id']}/status")
+
+    assert response.status_code == 200, response.text
+    energy = response.json()["energy"]
+    assert energy["today"] == pytest.approx(0.3)
+    assert energy["total"] == pytest.approx(843.4)
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_status_without_lifetime_path_is_unchanged(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload(mqtt_energy_total_path=None))).json()
+    service.get_plug_data.return_value = SmartPlugMQTTData(plug_id=created["id"], power=150.0, energy=4.8, state="ON")
+    service.is_reachable.return_value = True
+
+    response = await async_client.get(f"/api/v1/smart-plugs/{created['id']}/status")
+
+    energy = response.json()["energy"]
+    assert energy["today"] == pytest.approx(4.8)
+    assert energy["total"] is None

+ 2 - 0
backend/tests/unit/services/test_mqtt_smart_plug_subscribe.py

@@ -27,6 +27,8 @@ def _plug(**overrides):
         "mqtt_energy_topic": None,
         "mqtt_energy_path": None,
         "mqtt_energy_multiplier": None,
+        "mqtt_energy_total_path": None,
+        "mqtt_energy_total_multiplier": None,
         "mqtt_state_topic": None,
         "mqtt_state_path": None,
         "mqtt_state_on_value": None,

+ 233 - 0
backend/tests/unit/test_mqtt_lifetime_energy_3582.py

@@ -0,0 +1,233 @@
+"""#3582: an MQTT plug's lifetime energy counter, beside its daily one.
+
+Per-print energy is the difference of two "total" readings. An MQTT plug had
+one energy value and used it as both today and total, so with a daily counter
+(Tasmota ``ENERGY.Today``) a print running across midnight came out negative
+(and was dropped) or too small. A plug with ``mqtt_energy_total_path`` reads
+the lifetime counter from the same topic; one without keeps the old reading.
+"""
+
+import json
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+from sqlalchemy import select
+
+from backend.app.services.energy_plug import select_energy_reading
+from backend.app.services.mqtt_smart_plug import MQTTSmartPlugService, subscribe_plug_to_mqtt
+from backend.app.services.plug_energy import get_plug_energy
+
+TOPIC = "tele/tasmota_plug/SENSOR"
+
+
+def _sensor(today: float, total: float) -> SimpleNamespace:
+    """A Tasmota SENSOR message carrying both counters."""
+    payload = {"ENERGY": {"Today": today, "Total": total, "Power": 150}}
+    return SimpleNamespace(topic=TOPIC, payload=json.dumps(payload).encode())
+
+
+def _plug(plug_id: int = 7, total_path: str | None = "ENERGY.Total", total_multiplier: float = 1.0):
+    return SimpleNamespace(
+        id=plug_id,
+        plug_type="mqtt",
+        mqtt_topic=None,
+        mqtt_multiplier=None,
+        mqtt_power_topic=TOPIC,
+        mqtt_power_path="ENERGY.Power",
+        mqtt_power_multiplier=1.0,
+        mqtt_energy_topic=TOPIC,
+        mqtt_energy_path="ENERGY.Today",
+        mqtt_energy_multiplier=1.0,
+        mqtt_energy_total_path=total_path,
+        mqtt_energy_total_multiplier=total_multiplier,
+        mqtt_state_topic=None,
+        mqtt_state_path=None,
+        mqtt_state_on_value=None,
+    )
+
+
+def _service_with(plug) -> MQTTSmartPlugService:
+    service = MQTTSmartPlugService()
+    subscribe_plug_to_mqtt(service, plug)
+    return service
+
+
+class TestSubscription:
+    def test_both_counters_are_read_from_one_message(self):
+        plug = _plug()
+        service = _service_with(plug)
+
+        service._on_message(None, None, _sensor(today=1.25, total=842.5))
+
+        data = service.get_plug_data(plug.id)
+        assert data.energy == pytest.approx(1.25)
+        assert data.energy_total == pytest.approx(842.5)
+
+    def test_lifetime_multiplier_is_its_own(self):
+        """A device reporting Wh for the lifetime counter only."""
+        plug = _plug(total_multiplier=0.001)
+        service = _service_with(plug)
+
+        service._on_message(None, None, _sensor(today=1.25, total=842500))
+
+        data = service.get_plug_data(plug.id)
+        assert data.energy == pytest.approx(1.25)
+        assert data.energy_total == pytest.approx(842.5)
+
+    def test_without_a_lifetime_path_nothing_is_read_for_it(self):
+        plug = _plug(total_path=None)
+        service = _service_with(plug)
+
+        service._on_message(None, None, _sensor(today=1.25, total=842.5))
+
+        data = service.get_plug_data(plug.id)
+        assert data.energy == pytest.approx(1.25)
+        assert data.energy_total is None
+
+    def test_blank_lifetime_path_counts_as_unset(self):
+        plug = _plug(total_path="   ")
+        service = _service_with(plug)
+
+        service._on_message(None, None, _sensor(today=1.25, total=842.5))
+
+        assert service.get_plug_data(plug.id).energy_total is None
+        assert "energy_total" not in service.plug_configs[plug.id]
+
+
+class TestPerPrintAcrossMidnight:
+    async def _reading(self, service, plug):
+        with patch("backend.app.services.plug_energy.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
+            return await get_plug_energy(plug, None)
+
+    @pytest.mark.asyncio
+    async def test_a_print_across_midnight_keeps_its_energy(self):
+        plug = _plug()
+        service = _service_with(plug)
+
+        # 23:00: 4.8 kWh today, 842.5 lifetime. 01:00: the daily counter
+        # restarted at midnight, the lifetime one kept counting.
+        service._on_message(None, None, _sensor(today=4.8, total=842.5))
+        start = await self._reading(service, plug)
+        service._on_message(None, None, _sensor(today=0.3, total=843.4))
+        end = await self._reading(service, plug)
+
+        assert end["total"] - start["total"] == pytest.approx(0.9)
+        assert end["today"] == pytest.approx(0.3)
+
+    @pytest.mark.asyncio
+    async def test_without_a_lifetime_path_the_one_value_is_both(self):
+        """Unchanged for existing plugs: right when the topic is a lifetime counter."""
+        plug = _plug(total_path=None)
+        service = _service_with(plug)
+
+        service._on_message(None, None, _sensor(today=4.8, total=842.5))
+        reading = await self._reading(service, plug)
+
+        assert reading["today"] == pytest.approx(4.8)
+        assert reading["total"] == pytest.approx(4.8)
+
+    @pytest.mark.asyncio
+    async def test_no_lifetime_reading_yet_is_not_picked_as_the_counter(self):
+        """Only the daily value has arrived: the plug must not stand in for a
+        lifetime counter, or the print's start reading is the daily one."""
+        plug = _plug()
+        service = MQTTSmartPlugService()
+        subscribe_plug_to_mqtt(service, plug)
+        service._on_message(
+            None,
+            None,
+            SimpleNamespace(topic=TOPIC, payload=json.dumps({"ENERGY": {"Today": 4.8}}).encode()),
+        )
+
+        async def read(p, db):
+            return await self._reading(service, p)
+
+        assert await select_energy_reading([plug], read, None) is None
+
+
+@pytest.fixture
+def patched_session(db_session):
+    @asynccontextmanager
+    async def _session():
+        yield db_session
+
+    with patch("backend.app.core.database.async_session", _session):
+        yield
+
+
+class TestSnapshotsAndTotals:
+    @pytest.mark.asyncio
+    async def test_hourly_snapshot_takes_the_lifetime_counter(self, db_session, smart_plug_factory, patched_session):
+        from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
+        from backend.app.services import smart_plug_manager as manager_module
+
+        lifetime = await smart_plug_factory(
+            name="Tasmota",
+            plug_type="mqtt",
+            mqtt_energy_topic=TOPIC,
+            mqtt_energy_path="ENERGY.Today",
+            mqtt_energy_total_path="ENERGY.Total",
+        )
+        daily_only = await smart_plug_factory(
+            name="Daily", plug_type="mqtt", mqtt_energy_topic=TOPIC, mqtt_energy_path="ENERGY.Today"
+        )
+        service = MQTTSmartPlugService()
+        subscribe_plug_to_mqtt(service, lifetime)
+        subscribe_plug_to_mqtt(service, daily_only)
+        service._on_message(None, None, _sensor(today=4.8, total=842.5))
+
+        with patch("backend.app.services.plug_energy.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
+            await manager_module.SmartPlugManager()._capture_energy_snapshots()
+
+        rows = (await db_session.execute(select(SmartPlugEnergySnapshot))).scalars().all()
+        # The daily-only plug may hold a daily counter: never snapshotted.
+        assert [(row.plug_id, row.lifetime_kwh) for row in rows] == [(lifetime.id, pytest.approx(842.5))]
+
+    @pytest.mark.asyncio
+    async def test_statistics_lifetime_total_reads_the_lifetime_counter(self, db_session, smart_plug_factory):
+        from backend.app.api.routes.archives import _sum_live_plug_totals
+
+        lifetime = await smart_plug_factory(
+            name="Tasmota",
+            plug_type="mqtt",
+            mqtt_energy_topic=TOPIC,
+            mqtt_energy_path="ENERGY.Today",
+            mqtt_energy_total_path="ENERGY.Total",
+        )
+        daily_only = await smart_plug_factory(
+            name="Daily", plug_type="mqtt", mqtt_energy_topic=TOPIC, mqtt_energy_path="ENERGY.Today"
+        )
+        service = MQTTSmartPlugService()
+        subscribe_plug_to_mqtt(service, lifetime)
+        subscribe_plug_to_mqtt(service, daily_only)
+        service._on_message(None, None, _sensor(today=4.8, total=842.5))
+
+        with patch("backend.app.services.mqtt_relay.mqtt_relay", SimpleNamespace(smart_plug_service=service)):
+            total = await _sum_live_plug_totals(db_session)
+
+        # 842.5 lifetime from the first, the one value (4.8) from the second.
+        assert total == pytest.approx(842.5 + 4.8)
+
+
+class TestValidation:
+    def test_lifetime_path_needs_an_energy_topic(self):
+        from pydantic import ValidationError
+
+        from backend.app.schemas.smart_plug import SmartPlugCreate
+
+        with pytest.raises(ValidationError, match="lifetime energy path needs an energy topic"):
+            SmartPlugCreate(
+                name="P",
+                plug_type="mqtt",
+                mqtt_power_topic="p/power",
+                mqtt_energy_total_path="ENERGY.Total",
+            )
+
+    def test_legacy_topic_serves_as_the_energy_topic(self):
+        from backend.app.schemas.smart_plug import SmartPlugCreate
+
+        plug = SmartPlugCreate(name="P", plug_type="mqtt", mqtt_topic=TOPIC, mqtt_energy_total_path="ENERGY.Total")
+
+        assert plug.mqtt_energy_total_path == "ENERGY.Total"

+ 114 - 0
backend/tests/unit/test_mqtt_lifetime_energy_migration_3582.py

@@ -0,0 +1,114 @@
+"""Migration test for #3582 — smart_plugs.mqtt_energy_total_path / _multiplier.
+
+An existing MQTT plug has no lifetime path, so it keeps reading its one energy
+value as before. The added columns must come out as a fresh install builds
+them: the path nullable, the multiplier NOT NULL with the model's default.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from backend.app.core.database import load_all_models, run_migrations
+
+NEW_COLUMNS = ("mqtt_energy_total_path", "mqtt_energy_total_multiplier")
+
+
+@pytest.fixture(autouse=True)
+def force_sqlite_dialect(monkeypatch):
+    """settings.database_url may point at Postgres in dev configs; the test engine
+    is SQLite, so force the dialect both places run_migrations reads it from."""
+    from backend.app.core import database as database_module, db_dialect
+
+    monkeypatch.setattr(db_dialect, "is_sqlite", lambda: True)
+    monkeypatch.setattr(db_dialect, "is_postgres", lambda: False)
+    monkeypatch.setattr(database_module, "is_sqlite", lambda: True)
+
+
+async def _columns(conn) -> dict[str, tuple]:
+    """name -> (type, notnull, default) for smart_plugs, the default unquoted."""
+    rows = await conn.execute(text("PRAGMA table_info(smart_plugs)"))
+    return {row[1]: (row[2], row[3], row[4] and row[4].strip("'")) for row in rows}
+
+
+@pytest.fixture
+async def fresh_engine():
+    engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
+    async with engine.begin() as conn:
+        await conn.run_sync(load_all_models().create_all)
+    yield engine
+    await engine.dispose()
+
+
+@pytest.fixture
+async def legacy_engine():
+    """A current schema whose smart_plugs predates #3582, holding one MQTT plug."""
+    engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
+    async with engine.begin() as conn:
+        metadata = load_all_models()
+        await conn.run_sync(metadata.create_all)
+        await conn.execute(
+            metadata.tables["smart_plugs"]
+            .insert()
+            .values(
+                id=1,
+                name="Tasmota MQTT",
+                plug_type="mqtt",
+                mqtt_energy_topic="tele/plug/SENSOR",
+                mqtt_energy_path="ENERGY.Today",
+            )
+        )
+        for column in NEW_COLUMNS:
+            await conn.execute(text(f"ALTER TABLE smart_plugs DROP COLUMN {column}"))
+    yield engine
+    await engine.dispose()
+
+
+async def test_columns_missing_before_migration(legacy_engine):
+    """Sanity check so the assertions below can't pass by accident."""
+    async with legacy_engine.begin() as conn:
+        columns = await _columns(conn)
+    assert not set(NEW_COLUMNS) & set(columns)
+
+
+async def test_existing_plug_has_no_lifetime_path(legacy_engine):
+    async with legacy_engine.begin() as conn:
+        await run_migrations(conn)
+
+    async with legacy_engine.begin() as conn:
+        row = (
+            await conn.execute(
+                text("SELECT mqtt_energy_total_path, mqtt_energy_total_multiplier FROM smart_plugs WHERE id = 1")
+            )
+        ).one()
+    assert tuple(row) == (None, 1.0)
+
+
+async def test_upgraded_columns_match_a_fresh_install(legacy_engine, fresh_engine):
+    async with legacy_engine.begin() as conn:
+        await run_migrations(conn)
+        upgraded = await _columns(conn)
+    async with fresh_engine.begin() as conn:
+        fresh = await _columns(conn)
+
+    # NOT NULL and default as a fresh install; the type name differs (REAL from
+    # the migration, FLOAT from create_all), the REAL affinity does not.
+    for column in NEW_COLUMNS:
+        assert upgraded[column][1:] == fresh[column][1:], column
+    assert upgraded["mqtt_energy_total_multiplier"][1] == 1, "the multiplier must be NOT NULL"
+
+
+async def test_migration_is_idempotent(legacy_engine):
+    """A second boot must not fail on the columns already being there."""
+    async with legacy_engine.begin() as conn:
+        await run_migrations(conn)
+    async with legacy_engine.begin() as conn:
+        await run_migrations(conn)
+
+    async with legacy_engine.begin() as conn:
+        multiplier = (
+            await conn.execute(text("SELECT mqtt_energy_total_multiplier FROM smart_plugs WHERE id = 1"))
+        ).scalar_one()
+    assert multiplier == 1.0

+ 38 - 0
frontend/src/__tests__/components/AddSmartPlugModalWiring.test.tsx

@@ -184,6 +184,44 @@ describe('AddSmartPlugModal wiring: create', () => {
     });
   });
 
+  it('MQTT: sends the lifetime energy path and its multiplier (#3582)', async () => {
+    const user = userEvent.setup();
+    render(<AddSmartPlugModal onClose={() => undefined} />);
+
+    await user.click(screen.getByRole('button', { name: 'MQTT' }));
+    await user.type((await screen.findAllByPlaceholderText('Same as power topic, or different'))[0], 'tele/wiring/SENSOR');
+    await user.type(screen.getByPlaceholderText('energy_l1'), 'ENERGY.Today');
+    await user.type(screen.getByLabelText('Energy JSON Path (lifetime)'), 'ENERGY.Total');
+    const multiplier = screen.getByLabelText('Lifetime Multiplier');
+    await user.clear(multiplier);
+    await user.type(multiplier, '0.001');
+    await user.type(nameInput(), 'Tasmota');
+    await user.click(screen.getByRole('button', { name: 'Add' }));
+
+    await waitFor(() => expect(writes()).toHaveLength(1));
+    expect(writes()[0].body).toMatchObject({
+      plug_type: 'mqtt',
+      mqtt_energy_topic: 'tele/wiring/SENSOR',
+      mqtt_energy_path: 'ENERGY.Today',
+      mqtt_energy_total_path: 'ENERGY.Total',
+      mqtt_energy_total_multiplier: 0.001,
+    });
+  });
+
+  it('MQTT: no lifetime path sends null, and other types never send one', async () => {
+    const user = userEvent.setup();
+    render(<AddSmartPlugModal onClose={() => undefined} />);
+
+    await user.click(screen.getByRole('button', { name: 'MQTT' }));
+    await user.type((await screen.findAllByPlaceholderText('Same as power topic, or different'))[0], 'tele/wiring/SENSOR');
+    await user.type(screen.getByLabelText('Energy JSON Path (lifetime)'), '   ');
+    await user.type(nameInput(), 'Daily');
+    await user.click(screen.getByRole('button', { name: 'Add' }));
+
+    await waitFor(() => expect(writes()).toHaveLength(1));
+    expect(writes()[0].body).toMatchObject({ mqtt_energy_total_path: null, mqtt_energy_total_multiplier: 1 });
+  });
+
   it('REST: sends the REST URLs and method only', async () => {
     const user = userEvent.setup();
     render(<AddSmartPlugModal onClose={() => undefined} />);

+ 2 - 0
frontend/src/__tests__/components/SmartPlugCard.test.tsx

@@ -35,6 +35,8 @@ const createMockPlug = (overrides: Partial<SmartPlug> = {}): SmartPlug => ({
   mqtt_energy_topic: null,
   mqtt_energy_path: null,
   mqtt_energy_multiplier: 1.0,
+  mqtt_energy_total_path: null,
+  mqtt_energy_total_multiplier: 1.0,
   // MQTT state fields
   mqtt_state_topic: null,
   mqtt_state_path: null,

+ 2 - 0
frontend/src/__tests__/components/spoolbuddy/SpoolBuddyQuickMenu.test.tsx

@@ -59,6 +59,8 @@ const mockSmartPlug = {
   mqtt_power_multiplier: 1,
   mqtt_energy_topic: null,
   mqtt_energy_multiplier: 1,
+  mqtt_energy_total_path: null,
+  mqtt_energy_total_multiplier: 1,
   mqtt_state_topic: null,
   rest_on_url: null,
   rest_off_url: null,

+ 6 - 0
frontend/src/api/client.ts

@@ -2446,6 +2446,8 @@ export interface SmartPlug {
   mqtt_energy_topic: string | null;  // Topic for energy data
   mqtt_energy_path: string | null;  // e.g., "energy_l1"
   mqtt_energy_multiplier: number;  // Unit conversion for energy
+  mqtt_energy_total_path: string | null;  // Lifetime counter on the energy topic (#3582)
+  mqtt_energy_total_multiplier: number;
   // State monitoring
   mqtt_state_topic: string | null;  // Topic for state data
   mqtt_state_path: string | null;  // e.g., "state_l1" for ON/OFF
@@ -2527,6 +2529,8 @@ export interface SmartPlugCreate {
   mqtt_energy_topic?: string | null;
   mqtt_energy_path?: string | null;
   mqtt_energy_multiplier?: number;
+  mqtt_energy_total_path?: string | null;
+  mqtt_energy_total_multiplier?: number;
   // State monitoring
   mqtt_state_topic?: string | null;
   mqtt_state_path?: string | null;
@@ -2597,6 +2601,8 @@ export interface SmartPlugUpdate {
   mqtt_energy_topic?: string | null;
   mqtt_energy_path?: string | null;
   mqtt_energy_multiplier?: number;
+  mqtt_energy_total_path?: string | null;
+  mqtt_energy_total_multiplier?: number;
   // MQTT state fields
   mqtt_state_topic?: string | null;
   mqtt_state_path?: string | null;

+ 34 - 0
frontend/src/components/AddSmartPlugModal.tsx

@@ -39,6 +39,10 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {
   const [mqttEnergyMultiplier, setMqttEnergyMultiplier] = useState<string>(
     (plug?.mqtt_energy_multiplier ?? 1).toString()
   );
+  const [mqttEnergyTotalPath, setMqttEnergyTotalPath] = useState(plug?.mqtt_energy_total_path || '');
+  const [mqttEnergyTotalMultiplier, setMqttEnergyTotalMultiplier] = useState<string>(
+    (plug?.mqtt_energy_total_multiplier ?? 1).toString()
+  );
   // MQTT fields - State
   const [mqttStateTopic, setMqttStateTopic] = useState(plug?.mqtt_state_topic || '');
   const [mqttStatePath, setMqttStatePath] = useState(plug?.mqtt_state_path || '');
@@ -376,6 +380,8 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {
       mqtt_energy_topic: plugType === 'mqtt' ? (mqttEnergyTopic.trim() || null) : null,
       mqtt_energy_path: plugType === 'mqtt' ? (mqttEnergyPath.trim() || null) : null,
       mqtt_energy_multiplier: plugType === 'mqtt' ? (parseFloat(mqttEnergyMultiplier) || 1) : 1,
+      mqtt_energy_total_path: plugType === 'mqtt' ? (mqttEnergyTotalPath.trim() || null) : null,
+      mqtt_energy_total_multiplier: plugType === 'mqtt' ? (parseFloat(mqttEnergyTotalMultiplier) || 1) : 1,
       // MQTT state fields
       mqtt_state_topic: plugType === 'mqtt' ? (mqttStateTopic.trim() || null) : null,
       mqtt_state_path: plugType === 'mqtt' ? (mqttStatePath.trim() || null) : null,
@@ -1101,6 +1107,34 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {
                     <p className="text-xs text-bambu-gray" style={{ whiteSpace: 'pre-line' }}>
                       {t('smartPlugs.mqttEnergyHint')}
                     </p>
+                    {/* Lifetime counter on the same topic (#3582) — per-print energy reads it. */}
+                    <div className="grid grid-cols-2 gap-3">
+                      <div>
+                        <label htmlFor="mqtt-energy-total-path" className="block text-sm text-bambu-gray mb-1">{t('smartPlugs.restEnergyTotalPath')}</label>
+                        <input
+                          id="mqtt-energy-total-path"
+                          type="text"
+                          value={mqttEnergyTotalPath}
+                          onChange={(e) => setMqttEnergyTotalPath(e.target.value)}
+                          placeholder={t('smartPlugs.mqttEnergyTotalPathHint')}
+                          className="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"
+                        />
+                      </div>
+                      <div>
+                        <label htmlFor="mqtt-energy-total-multiplier" className="block text-sm text-bambu-gray mb-1">{t('smartPlugs.restEnergyTotalMultiplier')}</label>
+                        <input
+                          id="mqtt-energy-total-multiplier"
+                          type="text"
+                          value={mqttEnergyTotalMultiplier}
+                          onChange={(e) => setMqttEnergyTotalMultiplier(e.target.value)}
+                          placeholder="1"
+                          className="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"
+                        />
+                      </div>
+                    </div>
+                    <p className="text-xs text-bambu-gray">
+                      {t('smartPlugs.mqttEnergyTotalHint')}
+                    </p>
                   </div>
 
                   {/* State Section */}

+ 3 - 0
frontend/src/i18n/locales/de.ts

@@ -6799,6 +6799,9 @@ export default {
     onValue: 'EIN-Wert',
     mqttPowerHint: 'JSON-Pfad extrahiert Wert aus JSON-Payload (z.B. "power_l1"). Leer lassen wenn Topic rohe numerische Werte sendet.\nMultiplikator 0.001 für mW→W, 1000 für kW→W verwenden.',
     mqttEnergyHint: 'JSON-Pfad extrahiert Wert aus JSON-Payload. Leer lassen für rohe Werte.\nMultiplikator 0.001 für Wh→kWh, 1000 für MWh→kWh verwenden.',
+    mqttEnergyTotalPathHint: "z.B. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Ein Gesamtzähler, der nie zurückgesetzt wird, aus demselben Topic (Tasmota: ENERGY.Total). Die Energie pro Druck braucht ihn: Ein Tageszähler springt um Mitternacht auf null, sodass ein Druck über Mitternacht seine Energie verlor. Leer lassen, um den Energiewert oben wie bisher für beides zu verwenden.",
     mqttStateHint: 'JSON-Pfad extrahiert Wert aus JSON-Payload. Leer lassen für rohe Werte.\nEIN-Wert: der genaue String der "EIN" bedeutet. Leer lassen für Auto-Erkennung (ON, true, 1).',
     // REST smart plug
     restControl: 'Steuerung',

+ 3 - 0
frontend/src/i18n/locales/en.ts

@@ -6852,6 +6852,9 @@ export default {
     onValue: 'ON Value',
     mqttPowerHint: 'JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.\nUse multiplier 0.001 for mW→W, 1000 for kW→W.',
     mqttEnergyHint: 'JSON path extracts value from JSON payload. Leave empty for raw values.\nUse multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh.',
+    mqttEnergyTotalPathHint: "e.g. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "A lifetime counter that never resets, from the same topic (Tasmota: ENERGY.Total). Per-print energy needs it: a daily counter drops back to zero at midnight, so a print running past midnight lost its energy. Leave it empty to use the energy value above for both, as before.",
     mqttStateHint: 'JSON path extracts value from JSON payload. Leave empty for raw values.\nON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).',
     // REST smart plug
     restControl: 'Control',

+ 3 - 0
frontend/src/i18n/locales/es.ts

@@ -6807,6 +6807,9 @@ export default {
     onValue: 'Valor de ON',
     mqttPowerHint: 'La ruta JSON extrae el valor de la carga útil JSON (p. ej., "power_l1"). Déjelo vacío si el tema publica valores numéricos sin procesar.\nUse el multiplicador 0,001 para mW→W, 1000 para kW→W.',
     mqttEnergyHint: 'La ruta JSON extrae el valor de la carga útil JSON. Déjelo vacío para valores sin procesar.\nUse el multiplicador 0,001 para Wh→kWh, 1000 para MWh→kWh.',
+    mqttEnergyTotalPathHint: "p. ej. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Un contador total que nunca se reinicia, del mismo topic (Tasmota: ENERGY.Total). La energía por impresión lo necesita: un contador diario vuelve a cero a medianoche, así que una impresión que pasaba la medianoche perdía su energía. Déjalo vacío para usar el valor de energía de arriba para ambos, como antes.",
     mqttStateHint: 'La ruta JSON extrae el valor de la carga útil JSON. Déjelo vacío para valores sin procesar.\nValor de ON: la cadena exacta que significa «ON». Déjelo vacío para la detección automática (ON, true, 1).',
     // REST smart plug
     restControl: 'Control',

+ 3 - 0
frontend/src/i18n/locales/fr.ts

@@ -6787,6 +6787,9 @@ export default {
     onValue: 'Valeur ON',
     mqttPowerHint: 'Le chemin JSON extrait la valeur du payload JSON (ex: "power_l1"). Laisser vide si le topic publie des valeurs numériques brutes.\nUtiliser le multiplicateur 0.001 pour mW→W, 1000 pour kW→W.',
     mqttEnergyHint: 'Le chemin JSON extrait la valeur du payload JSON. Laisser vide pour les valeurs brutes.\nUtiliser le multiplicateur 0.001 pour Wh→kWh, 1000 pour MWh→kWh.',
+    mqttEnergyTotalPathHint: "ex. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Un compteur cumulé qui ne se remet jamais à zéro, sur le même topic (Tasmota : ENERGY.Total). L'énergie par impression en a besoin : un compteur journalier repart de zéro à minuit, donc une impression passant minuit perdait son énergie. Laissez vide pour utiliser la valeur d'énergie ci-dessus pour les deux, comme avant.",
     mqttStateHint: 'Le chemin JSON extrait la valeur du payload JSON. Laisser vide pour les valeurs brutes.\nValeur ON : la chaîne exacte signifiant "ON". Laisser vide pour la détection auto (ON, true, 1).',
     // REST smart plug
     restControl: 'Contrôle',

+ 3 - 0
frontend/src/i18n/locales/it.ts

@@ -6786,6 +6786,9 @@ export default {
     onValue: 'Valore ON',
     mqttPowerHint: 'Il percorso JSON estrae il valore dal payload JSON (es. "power_l1"). Lascia vuoto se il topic pubblica valori numerici grezzi.\nUsa moltiplicatore 0.001 per mW→W, 1000 per kW→W.',
     mqttEnergyHint: 'Il percorso JSON estrae il valore dal payload JSON. Lascia vuoto per valori grezzi.\nUsa moltiplicatore 0.001 per Wh→kWh, 1000 per MWh→kWh.',
+    mqttEnergyTotalPathHint: "es. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Un contatore totale che non si azzera mai, dallo stesso topic (Tasmota: ENERGY.Total). L'energia per stampa ne ha bisogno: un contatore giornaliero torna a zero a mezzanotte, quindi una stampa oltre la mezzanotte perdeva la sua energia. Lascia vuoto per usare il valore di energia sopra per entrambi, come prima.",
     mqttStateHint: 'Il percorso JSON estrae il valore dal payload JSON. Lascia vuoto per valori grezzi.\nValore ON: la stringa esatta che significa "ON". Lascia vuoto per rilevamento auto (ON, true, 1).',
     // REST smart plug
     restControl: 'Controllo',

+ 3 - 0
frontend/src/i18n/locales/ja.ts

@@ -6800,6 +6800,9 @@ export default {
     onValue: 'ON値',
     mqttPowerHint: 'JSONパスはJSONペイロードから値を抽出します(例: "power_l1")。トピックが生の数値を送信する場合は空のままにしてください。\n乗数: mW→Wは0.001、kW→Wは1000を使用。',
     mqttEnergyHint: 'JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。\n乗数: Wh→kWhは0.001、MWh→kWhは1000を使用。',
+    mqttEnergyTotalPathHint: "例: ENERGY.Total",
+    mqttEnergyTotalHint:
+      "同じトピックの、リセットされない累計カウンター(Tasmota: ENERGY.Total)。印刷ごとの電力量に必要です。日次カウンターは深夜0時にゼロに戻るため、0時をまたぐ印刷の電力量が失われていました。空欄の場合は、従来どおり上の電力量の値を両方に使用します。",
     mqttStateHint: 'JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。\nON値: "ON"を意味する正確な文字列。自動検出(ON、true、1)の場合は空のままにしてください。',
     // REST smart plug
     restControl: 'コントロール',

+ 3 - 0
frontend/src/i18n/locales/ko.ts

@@ -6525,6 +6525,9 @@ export default {
     onValue: 'ON 값',
     mqttPowerHint: 'JSON 경로는 JSON 페이로드에서 값을 추출합니다 (예: "power_l1"). 토픽이 원시 숫자 값을 게시하면 비워두세요.\nmW→W에는 배수 0.001, kW→W에는 1000을 사용하세요.',
     mqttEnergyHint: 'JSON 경로는 JSON 페이로드에서 값을 추출합니다. 원시 값에는 비워두세요.\nWh→kWh에는 배수 0.001, MWh→kWh에는 1000을 사용하세요.',
+    mqttEnergyTotalPathHint: "예: ENERGY.Total",
+    mqttEnergyTotalHint:
+      "같은 토픽의 초기화되지 않는 누적 카운터(Tasmota: ENERGY.Total). 출력별 에너지 계산에 필요합니다. 일일 카운터는 자정에 0으로 돌아가므로 자정을 넘긴 출력은 에너지가 사라졌습니다. 비워 두면 이전처럼 위의 에너지 값을 둘 다에 사용합니다.",
     mqttStateHint: 'JSON 경로는 JSON 페이로드에서 값을 추출합니다. 원시 값에는 비워두세요.\nON 값: "ON"을 의미하는 정확한 문자열. 자동 감지(ON, true, 1)를 위해 비워두세요.',
     restControl: '제어',
     restOnUrl: '켜기 URL',

+ 3 - 0
frontend/src/i18n/locales/nl.ts

@@ -6850,6 +6850,9 @@ export default {
     onValue: 'AAN-waarde',
     mqttPowerHint: 'JSON-pad haalt de waarde uit een JSON-payload (bijv. "power_l1"). Laat leeg als het topic ruwe numerieke waarden publiceert.\nGebruik vermenigvuldigingsfactor 0.001 voor mW→W, 1000 voor kW→W.',
     mqttEnergyHint: 'JSON-pad haalt de waarde uit een JSON-payload. Laat leeg voor ruwe waarden.\nGebruik vermenigvuldigingsfactor 0.001 voor Wh→kWh, 1000 voor MWh→kWh.',
+    mqttEnergyTotalPathHint: "bijv. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Een totaalteller die nooit wordt gereset, uit hetzelfde topic (Tasmota: ENERGY.Total). Energie per print heeft hem nodig: een dagteller gaat om middernacht terug naar nul, waardoor een print over middernacht zijn energie kwijtraakte. Laat leeg om de energiewaarde hierboven zoals voorheen voor beide te gebruiken.",
     mqttStateHint: 'JSON-pad haalt de waarde uit een JSON-payload. Laat leeg voor ruwe waarden.\nAAN-waarde: de exacte tekenreeks die "AAN" betekent. Laat leeg voor automatische detectie (ON, true, 1).',
     // REST smart plug
     restControl: 'Bedienen',

+ 3 - 0
frontend/src/i18n/locales/pl.ts

@@ -6852,6 +6852,9 @@ export default {
     onValue: 'Wartość ON',
     mqttPowerHint: 'Ścieżka JSON wyodrębnia wartość z ładunku JSON (np. „power_l1”). Pozostaw puste, jeśli temat publikuje surowe wartości liczbowe.\nUżyj mnożnika 0.001 dla mW→W, 1000 dla kW→W.',
     mqttEnergyHint: 'Ścieżka JSON wyodrębnia wartość z ładunku JSON. Pozostaw puste dla surowych wartości.\nUżyj mnożnika 0.001 dla Wh→kWh, 1000 dla MWh→kWh.',
+    mqttEnergyTotalPathHint: "np. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Licznik całkowity, który nigdy się nie zeruje, z tego samego tematu (Tasmota: ENERGY.Total). Energia na wydruk go potrzebuje: licznik dzienny wraca do zera o północy, więc wydruk trwający po północy tracił swoją energię. Pozostaw puste, aby jak dotąd używać powyższej wartości energii dla obu.",
     mqttStateHint: 'Ścieżka JSON wyodrębnia wartość z ładunku JSON. Pozostaw puste dla surowych wartości.\nWartość ON: dokładny ciąg oznaczający „ON”. Pozostaw puste, aby wykrywać automatycznie (ON, true, 1).',
     // REST smart plug
     restControl: 'Sterowanie',

+ 3 - 0
frontend/src/i18n/locales/pt-BR.ts

@@ -6786,6 +6786,9 @@ export default {
     onValue: 'Valor ON',
     mqttPowerHint: 'O caminho JSON extrai o valor do payload JSON (ex: "power_l1"). Deixe vazio se o tópico publica valores numéricos brutos.\nUse multiplicador 0.001 para mW→W, 1000 para kW→W.',
     mqttEnergyHint: 'O caminho JSON extrai o valor do payload JSON. Deixe vazio para valores brutos.\nUse multiplicador 0.001 para Wh→kWh, 1000 para MWh→kWh.',
+    mqttEnergyTotalPathHint: "ex.: ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Um contador total que nunca zera, do mesmo tópico (Tasmota: ENERGY.Total). A energia por impressão precisa dele: um contador diário volta a zero à meia-noite, então uma impressão que passava da meia-noite perdia sua energia. Deixe vazio para usar o valor de energia acima para ambos, como antes.",
     mqttStateHint: 'O caminho JSON extrai o valor do payload JSON. Deixe vazio para valores brutos.\nValor ON: a string exata que significa "ON". Deixe vazio para detecção automática (ON, true, 1).',
     // REST smart plug
     restControl: 'Controle',

+ 3 - 0
frontend/src/i18n/locales/ru.ts

@@ -6516,6 +6516,9 @@ export default {
     onValue: "Значение «включено»",
     mqttPowerHint: "Путь JSON извлекает значение из полезной нагрузки JSON, например «power_l1». Оставьте пустым, если тема публикует число напрямую.\nДля преобразования мВт→Вт используйте 0.001, для кВт→Вт — 1000.",
     mqttEnergyHint: "Путь JSON извлекает значение из полезной нагрузки JSON. Оставьте пустым для числового значения напрямую.\nДля преобразования Вт·ч→кВт·ч используйте 0.001, для МВт·ч→кВт·ч — 1000.",
+    mqttEnergyTotalPathHint: "например, ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Общий счётчик, который никогда не сбрасывается, из того же топика (Tasmota: ENERGY.Total). Он нужен для энергии на печать: дневной счётчик обнуляется в полночь, поэтому печать через полночь теряла свою энергию. Оставьте пустым, чтобы, как раньше, использовать значение энергии выше для обоих.",
     mqttStateHint: "Путь JSON извлекает значение из полезной нагрузки JSON. Оставьте пустым для значения напрямую.\nЗначение «включено» — точная строка, означающая включённое состояние. Оставьте пустым для автоматического распознавания ON, true и 1.",
     restControl: "Управление",
     restOnUrl: "URL включения",

+ 3 - 0
frontend/src/i18n/locales/sv.ts

@@ -6881,6 +6881,9 @@ errors: {
     onValue: 'PÅ-värde',
     mqttPowerHint: 'JSON-sökväg extraherar värde från JSON-nyttolast (t.ex. "power_l1"). Lämna tomt om ämnet publicerar råa numeriska värden.\nAnvänd multiplikator 0,001 för mW→W, 1000 för kW→W.',
     mqttEnergyHint: 'JSON-sökväg extraherar värde från JSON-nyttolast. Lämna tomt för råa värden.\nAnvänd multiplikator 0,001 för Wh→kWh, 1000 för MWh→kWh.',
+    mqttEnergyTotalPathHint: "t.ex. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "En totalräknare som aldrig nollställs, från samma topic (Tasmota: ENERGY.Total). Energi per utskrift behöver den: en dagsräknare går tillbaka till noll vid midnatt, så en utskrift över midnatt förlorade sin energi. Lämna tomt för att använda energivärdet ovan för båda, som tidigare.",
     mqttStateHint: 'JSON-sökväg extraherar värde från JSON-nyttolast. Lämna tomt för råa värden.\nPÅ-värde: den exakta strängen som betyder "PÅ". Lämna tomt för auto-upptäckt (PÅ, true, 1).',
     // REST kontakt
     restControl: 'Kontroll',

+ 3 - 0
frontend/src/i18n/locales/tr.ts

@@ -6761,6 +6761,9 @@ export default {
     onValue: 'ON Değeri',
     mqttPowerHint: 'JSON yolu JSON yükten değer çıkarır (örn., "power_l1"). Konu ham sayısal değerler yayınlıyorsa boş bırakın.\nmW→W için 0.001, kW→W için 1000 çarpanı kullanın.',
     mqttEnergyHint: 'JSON yolu JSON yükten değer çıkarır. Ham değerler için boş bırakın.\nWh→kWh için 0.001, MWh→kWh için 1000 çarpanı kullanın.',
+    mqttEnergyTotalPathHint: "örn. ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Aynı konudan, hiç sıfırlanmayan toplam sayaç (Tasmota: ENERGY.Total). Baskı başına enerji için gereklidir: günlük sayaç gece yarısı sıfıra döner, bu yüzden gece yarısını geçen bir baskı enerjisini kaybediyordu. Daha önce olduğu gibi yukarıdaki enerji değerini her ikisi için kullanmak için boş bırakın.",
     mqttStateHint: 'JSON yolu JSON yükten değer çıkarır. Ham değerler için boş bırakın.\nON değeri: "ON" anlamına gelen tam string. Otomatik algılama için boş bırakın (ON, true, 1).',
     // REST akıllı priz
     restControl: 'Kontrol',

+ 3 - 0
frontend/src/i18n/locales/uk.ts

@@ -6840,6 +6840,9 @@ export default {
     onValue: "Значення «увімкнено»",
     mqttPowerHint: "Шлях JSON витягує значення з корисного навантаження JSON (наприклад, \"power_l1\"). Залиште поле порожнім, якщо тема публікує безпосередньо числові значення.\nДля перетворення mW→W використовуйте множник 0.001, а для kW→W — 1000.",
     mqttEnergyHint: "Шлях JSON витягує значення з корисного навантаження JSON. Залиште поле порожнім для безпосередньо переданих значень.\nДля перетворення Wh→kWh використовуйте множник 0.001, а для MWh→kWh — 1000.",
+    mqttEnergyTotalPathHint: "наприклад, ENERGY.Total",
+    mqttEnergyTotalHint:
+      "Загальний лічильник, який ніколи не скидається, з того самого топіка (Tasmota: ENERGY.Total). Він потрібен для енергії на друк: денний лічильник обнуляється опівночі, тому друк через північ втрачав свою енергію. Залиште порожнім, щоб, як і раніше, використовувати значення енергії вище для обох.",
     mqttStateHint: "Шлях JSON витягує значення з корисного навантаження JSON. Залиште поле порожнім для безпосередньо переданих значень.\nЗначення «увімкнено»: точний рядок, що означає стан «увімкнено». Залиште поле порожнім для автоматичного визначення (ON, true, 1).",
     // REST smart plug
     restControl: "Керування",

+ 3 - 0
frontend/src/i18n/locales/zh-CN.ts

@@ -6785,6 +6785,9 @@ export default {
     onValue: 'ON值',
     mqttPowerHint: 'JSON路径从JSON负载中提取值(例如"power_l1")。如果主题发布原始数值,请留空。\n乘数:mW→W使用0.001,kW→W使用1000。',
     mqttEnergyHint: 'JSON路径从JSON负载中提取值。原始值请留空。\n乘数:Wh→kWh使用0.001,MWh→kWh使用1000。',
+    mqttEnergyTotalPathHint: "例如 ENERGY.Total",
+    mqttEnergyTotalHint:
+      "来自同一主题、永不重置的累计计数器(Tasmota:ENERGY.Total)。每次打印的能耗需要它:每日计数器在午夜归零,因此跨越午夜的打印会丢失能耗。留空则像以前一样,将上方的能耗值同时用于两者。",
     mqttStateHint: 'JSON路径从JSON负载中提取值。原始值请留空。\nON值:表示"ON"的确切字符串。留空以自动检测(ON、true、1)。',
     // REST smart plug
     restControl: '控制',

+ 3 - 0
frontend/src/i18n/locales/zh-TW.ts

@@ -6785,6 +6785,9 @@ export default {
     onValue: 'ON值',
     mqttPowerHint: 'JSON路徑從JSON負載中提取值(例如"power_l1")。如果主題發布原始數值,請留空。\n乘數:mW→W使用0.001,kW→W使用1000。',
     mqttEnergyHint: 'JSON路徑從JSON負載中提取值。原始值請留空。\n乘數:Wh→kWh使用0.001,MWh→kWh使用1000。',
+    mqttEnergyTotalPathHint: "例如 ENERGY.Total",
+    mqttEnergyTotalHint:
+      "來自同一主題、永不重置的累計計數器(Tasmota:ENERGY.Total)。每次列印的能耗需要它:每日計數器在午夜歸零,因此跨越午夜的列印會遺失能耗。留空則像以前一樣,將上方的能耗值同時用於兩者。",
     mqttStateHint: 'JSON路徑從JSON負載中提取值。原始值請留空。\nON值:表示"ON"的確切字串。留空以自動檢測(ON、true、1)。',
     // REST smart plug
     restControl: '控制',