Selaa lähdekoodia

Smart plugs: monitor-only MQTT plugs are not switched by automation (#3583)

- An MQTT plug can be neither turned on nor off, so queue power-on,
  auto-on at print start, auto-off at print end, auto-off after a
  queue job or drying, plug schedules and the AI failure power-off
  all skip it.
- The queue powers a printer on with a plug that can switch, and a
  printer whose only plug is an MQTT plug is not counted as one it
  can wake.
- A pending auto-off left on an MQTT plug is cleared at startup.
- HA scripts linked to a printer still run at print start.
maziggy 3 päivää sitten
vanhempi
sitoutus
d47e011f38

+ 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
+- **Monitor-only MQTT plugs are no longer switched by automation (#3583, reported by @paulleonartcalvo)** — Bambuddy only listens to an MQTT plug, so it cannot turn one on or off, but its Auto On and Auto Off were on by default, hidden in the plug's settings, and every automation tried anyway. With an MQTT plug for metering and a switchable plug on the same printer, the queue could pick the MQTT plug to power the printer on, fail, and hold the job with "the smart plug could not power it on". A printer whose only plug was an MQTT plug counted as one the queue could switch on, so its job said "Offline" instead of that it has no Auto On plug. Auto-off at print end, "auto off after this job", auto-off after drying, plug schedules and the AI failure detection's power-off all logged a failed turn-off for it. All of them now leave MQTT plugs alone, and an auto-off still pending on one from an earlier version is cleared at startup. Home Assistant scripts linked to a printer still run at print start as before.
 - **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.

+ 7 - 2
backend/app/api/routes/smart_plugs.py

@@ -56,7 +56,12 @@ from backend.app.services.secret_fields import (
     reject_placeholder,
     same_value,
 )
-from backend.app.services.smart_plug_manager import publish_plug_state, run_linked_scripts, smart_plug_manager
+from backend.app.services.smart_plug_manager import (
+    can_turn_off,
+    publish_plug_state,
+    run_linked_scripts,
+    smart_plug_manager,
+)
 from backend.app.services.tasmota import tasmota_service
 from backend.app.utils.local_time import utcnow_naive
 
@@ -219,7 +224,7 @@ def _can_be_switched(plug: SmartPlug) -> bool:
       is exactly the kind that reports watts, so without this it would win the
       power tiebreak below and take the row off a plug that can be switched.
     """
-    return not _is_script_plug(plug) and plug.plug_type != "mqtt"
+    return can_turn_off(plug)
 
 
 def _reports_power(plug: SmartPlug) -> bool:

+ 4 - 3
backend/app/services/obico_actions.py

@@ -63,7 +63,7 @@ def _pause_print(printer_id: int) -> None:
 
 async def _turn_off_linked_plugs(printer_id: int) -> None:
     from backend.app.services.smart_plug_manager import (
-        _is_script_plug,
+        can_turn_off,
         publish_plug_state,
         run_linked_scripts_after_automatic_switch,
         smart_plug_manager,
@@ -74,8 +74,9 @@ async def _turn_off_linked_plugs(printer_id: int) -> None:
         plugs = await smart_plug_manager._get_plugs_for_printer(printer_id, db)
         for plug in plugs:
             # A script can only be run, not turned off; the "printer turns
-            # off" ones run below, after the plug that feeds the printer.
-            if not plug.enabled or _is_script_plug(plug):
+            # off" ones run below, after the plug that feeds the printer. An
+            # MQTT plug cannot be switched at all (#3583).
+            if not plug.enabled or not can_turn_off(plug):
                 continue
             try:
                 service = await smart_plug_manager.get_service_for_plug(plug, db)

+ 12 - 3
backend/app/services/print_scheduler.py

@@ -68,7 +68,7 @@ from backend.app.services.printer_manager import (
 )
 from backend.app.services.queue_item_printer import drop_printer_resolved
 from backend.app.services.slot_nozzle import reports_two_nozzles
-from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
+from backend.app.services.smart_plug_manager import is_monitor_only, publish_plug_state, smart_plug_manager
 from backend.app.services.spool_assignment_notifications import (
     _global_tray_from_assignment,
     _slot_label_from_global_tray,
@@ -2311,7 +2311,7 @@ class PrintScheduler:
                     # If printer not connected, try to power on via smart plug
                     if not printer_connected:
                         plugs = await self._get_smart_plugs(db, item.printer_id)
-                        auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
+                        auto_on_plugs = self._auto_on_plugs(plugs)
                         if auto_on_plugs:
                             logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
                             # Power on using the plug that actually feeds the printer, and
@@ -3451,6 +3451,8 @@ class PrintScheduler:
             .where(SmartPlug.printer_id.is_not(None))
             .where(SmartPlug.enabled == True)  # noqa: E712
             .where(SmartPlug.auto_on == True)  # noqa: E712
+            # Same rule as _auto_on_plugs: an MQTT plug cannot power a printer on (#3583).
+            .where(SmartPlug.plug_type != "mqtt")
         )
         return {pid for (pid,) in result.all() if pid is not None}
 
@@ -3563,7 +3565,7 @@ class PrintScheduler:
                     continue
 
                 plugs = await self._get_smart_plugs(db, printer.id)
-                auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
+                auto_on_plugs = self._auto_on_plugs(plugs)
                 if not auto_on_plugs:
                     # wakeable_ids said otherwise — the plug changed under us
                     # mid-pass. Nothing to do but move on.
@@ -7271,6 +7273,13 @@ class PrintScheduler:
         result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
         return list(result.scalars().all())
 
+    @staticmethod
+    def _auto_on_plugs(plugs: list[SmartPlug]) -> list[SmartPlug]:
+        """The plugs that may power a printer on: enabled, auto on, and not a
+        monitor-only MQTT plug, which Bambuddy cannot switch (#3583). Must
+        match the query in :meth:`_wakeable_printer_ids`."""
+        return [p for p in plugs if p.auto_on and p.enabled and not is_monitor_only(p)]
+
     @staticmethod
     def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
         """Pick the plug to power-cycle a printer back online with (#2629).

+ 42 - 9
backend/app/services/smart_plug_manager.py

@@ -70,6 +70,23 @@ def _is_script_plug(plug) -> bool:
     )
 
 
+def is_monitor_only(plug) -> bool:
+    """An MQTT plug: Bambuddy subscribes to it and never publishes, so it can
+    be neither turned on nor off (#3583). Its auto on / auto off default to on
+    and the UI hides both, so every switching path must skip it itself."""
+    return getattr(plug, "plug_type", None) == "mqtt"
+
+
+def can_turn_off(plug) -> bool:
+    """Whether an automatic turn-off can switch this plug off (#3583).
+
+    Not a Home Assistant script, which can only be run, and not a monitor-only
+    MQTT plug. Turning on is narrower on purpose: a script linked to a printer
+    is run by the auto-on paths, so they skip only :func:`is_monitor_only`.
+    """
+    return not _is_script_plug(plug) and not is_monitor_only(plug)
+
+
 async def run_linked_scripts(printer_id: int, plug_state: str, db: AsyncSession) -> None:
     """Run the HA scripts linked to a printer after its power plug switched.
 
@@ -379,6 +396,9 @@ class SmartPlugManager:
             plugs = result.scalars().all()
 
             for plug in plugs:
+                # A schedule cannot switch a monitor-only MQTT plug (#3583).
+                if is_monitor_only(plug):
+                    continue
                 service = await self.get_service_for_plug(plug, db)
 
                 # Check if we should turn on
@@ -445,6 +465,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_on is disabled", plug.name)
                 continue
 
+            if is_monitor_only(plug):
+                logger.debug("Smart plug '%s' is monitor-only, skipping auto-on", plug.name)
+                continue
+
             # Turn on the plug
             logger.info("Print started on printer %s, turning on plug '%s'", printer_id, plug.name)
             try:
@@ -492,9 +516,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_off is disabled", plug.name)
                 continue
 
-            # Skip auto-off for HA script entities (scripts can only be triggered, not turned off)
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping auto-off", plug.name)
+            # Skip auto-off for HA script entities (scripts can only be triggered,
+            # not turned off) and monitor-only MQTT plugs (#3583).
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping auto-off", plug.name)
                 continue
 
             logger.info(
@@ -539,8 +564,8 @@ class SmartPlugManager:
             if not plug.enabled:
                 logger.debug("Smart plug '%s' is disabled, skipping queue auto-off", plug.name)
                 continue
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping queue auto-off", plug.name)
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping queue auto-off", plug.name)
                 continue
             logger.info(
                 "Queue job finished on printer %s, scheduling turn-off for plug '%s'",
@@ -574,10 +599,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_off_after_drying is disabled, skipping", plug.name)
                 continue
 
-            # HA script entities can only be triggered, not turned off — same
-            # guard the print-finish path uses.
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping drying auto-off", plug.name)
+            # HA script entities can only be triggered, not turned off, and MQTT
+            # plugs not switched at all — same guard the print-finish path uses.
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping drying auto-off", plug.name)
                 continue
 
             logger.info(
@@ -922,6 +947,14 @@ class SmartPlugManager:
                 pending_plugs = result.scalars().all()
 
                 for plug in pending_plugs:
+                    # A pending off left on an MQTT plug by an earlier version
+                    # can never run (#3583): clear it.
+                    if is_monitor_only(plug):
+                        plug.auto_off_pending = False
+                        plug.auto_off_pending_since = None
+                        await db.commit()
+                        continue
+
                     # Check how long it's been pending (timeout after 2 hours)
                     if plug.auto_off_pending_since:
                         pending_since = to_naive_utc(plug.auto_off_pending_since)

+ 285 - 0
backend/tests/unit/test_monitor_only_plugs_3583.py

@@ -0,0 +1,285 @@
+"""#3583: monitor-only MQTT plugs are never switched by automation.
+
+Bambuddy subscribes to an MQTT plug and never publishes, so it can be neither
+turned on nor off. Its auto on / auto off default to on and the UI hides both,
+yet every automation path tried to switch it -- through the Tasmota service,
+with no IP. Linked beside a plug that can switch, it could take the queue's
+power-on and hold the job, and every auto-off logged a failed turn-off.
+"""
+
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.app.models.smart_plug import SmartPlug
+from backend.app.services.print_scheduler import PrintScheduler
+from backend.app.services.smart_plug_manager import SmartPlugManager, can_turn_off, is_monitor_only
+from backend.tests.unit.test_scheduler_class_target_smart_plug_2786 import (  # noqa: F401 - fixture
+    _add_item,
+    _get_item,
+    _run,
+    queue_db,
+)
+
+
+def _plug(plug_id, plug_type="tasmota", **kw):
+    fields = {
+        "id": plug_id,
+        "name": f"{plug_type} {plug_id}",
+        "plug_type": plug_type,
+        "ip_address": None if plug_type == "mqtt" else f"10.0.1.{plug_id}",
+        "username": None,
+        "password": None,
+        "ha_entity_id": None,
+        "enabled": True,
+        "auto_on": True,
+        "auto_off": True,
+        "auto_off_after_drying": True,
+        "off_delay_after_drying_minutes": 10,
+        "off_delay_mode": "time",
+        "off_delay_minutes": 5,
+        "off_temp_threshold": 70,
+        "printer_id": 1,
+        "controls_printer_power": True,
+        "auto_off_executed": False,
+        "auto_off_pending": False,
+        "auto_off_pending_since": None,
+        "schedule_enabled": True,
+        "schedule_on_time": "08:00",
+        "schedule_off_time": "22:00",
+        "last_state": "OFF",
+    }
+    fields.update(kw)
+    plug = MagicMock()
+    for key, value in fields.items():
+        setattr(plug, key, value)
+    return plug
+
+
+class TestCapability:
+    def test_mqtt_is_monitor_only(self):
+        assert is_monitor_only(SimpleNamespace(plug_type="mqtt"))
+        assert not is_monitor_only(SimpleNamespace(plug_type="rest"))
+
+    @pytest.mark.parametrize(
+        ("plug_type", "entity", "expected"),
+        [
+            ("tasmota", None, True),
+            ("rest", None, True),
+            ("homeassistant", "switch.printer", True),
+            ("homeassistant", "script.printer_off", False),
+            ("mqtt", None, False),
+        ],
+    )
+    def test_can_turn_off(self, plug_type, entity, expected):
+        assert can_turn_off(SimpleNamespace(plug_type=plug_type, ha_entity_id=entity)) is expected
+
+    def test_auto_on_plugs_leave_out_mqtt(self):
+        mqtt, rest = _plug(1, "mqtt"), _plug(2, "rest")
+
+        assert PrintScheduler._auto_on_plugs([mqtt, rest]) == [rest]
+
+
+class TestPrintCycle:
+    @pytest.mark.asyncio
+    async def test_print_start_does_not_switch_on_an_mqtt_plug(self):
+        manager = SmartPlugManager()
+        mqtt, tasmota = _plug(1, "mqtt"), _plug(2)
+        with (
+            patch.object(manager, "_get_plugs_for_printer", AsyncMock(return_value=[mqtt, tasmota])),
+            patch("backend.app.services.smart_plug_manager.tasmota_service") as service,
+        ):
+            service.turn_on = AsyncMock(return_value=True)
+            await manager.on_print_start(printer_id=1, db=AsyncMock())
+
+        service.turn_on.assert_awaited_once_with(tasmota)
+
+    @pytest.mark.asyncio
+    async def test_print_start_still_runs_a_linked_script(self):
+        """Turning on is narrower than switching: a script is run on purpose."""
+        manager = SmartPlugManager()
+        script = _plug(3, "homeassistant", ha_entity_id="script.printer_on")
+        with (
+            patch.object(manager, "_get_plugs_for_printer", AsyncMock(return_value=[script])),
+            patch.object(manager, "_configure_ha_service", AsyncMock()),
+            patch("backend.app.services.smart_plug_manager.homeassistant_service") as service,
+        ):
+            service.turn_on = AsyncMock(return_value=True)
+            await manager.on_print_start(printer_id=1, db=AsyncMock())
+
+        service.turn_on.assert_awaited_once_with(script)
+
+    @pytest.mark.asyncio
+    async def test_print_end_schedules_no_off_for_an_mqtt_plug(self):
+        manager = SmartPlugManager()
+        mqtt, tasmota = _plug(1, "mqtt"), _plug(2)
+        with (
+            patch.object(manager, "_get_plugs_for_printer", AsyncMock(return_value=[mqtt, tasmota])),
+            patch.object(manager, "_schedule_delayed_off") as schedule,
+        ):
+            await manager.on_print_complete(printer_id=1, status="completed", db=AsyncMock())
+
+        assert [c.args[0] for c in schedule.call_args_list] == [tasmota]
+
+    @pytest.mark.asyncio
+    async def test_auto_off_after_a_queue_job_skips_an_mqtt_plug(self):
+        manager = SmartPlugManager()
+        mqtt, tasmota = _plug(1, "mqtt"), _plug(2)
+        with (
+            patch.object(manager, "_get_plugs_for_printer", AsyncMock(return_value=[mqtt, tasmota])),
+            patch.object(manager, "_schedule_off_per_mode") as schedule,
+        ):
+            await manager.schedule_off_after_queue_job(printer_id=1, db=AsyncMock())
+
+        assert [c.args[0] for c in schedule.call_args_list] == [tasmota]
+
+    @pytest.mark.asyncio
+    async def test_drying_auto_off_skips_an_mqtt_plug(self):
+        manager = SmartPlugManager()
+        mqtt, tasmota = _plug(1, "mqtt"), _plug(2)
+        with (
+            patch.object(manager, "_get_plugs_for_printer", AsyncMock(return_value=[mqtt, tasmota])),
+            patch.object(manager, "_schedule_delayed_off") as schedule,
+        ):
+            await manager.on_drying_complete(printer_id=1, db=AsyncMock())
+
+        assert [c.args[0] for c in schedule.call_args_list] == [tasmota]
+
+
+def _session_returning(plugs):
+    db = AsyncMock()
+    result = MagicMock()
+    result.scalars.return_value.all.return_value = plugs
+    db.execute = AsyncMock(return_value=result)
+    session = MagicMock()
+    session.return_value.__aenter__ = AsyncMock(return_value=db)
+    session.return_value.__aexit__ = AsyncMock()
+    return session, db
+
+
+class TestSchedulesAndRestart:
+    @pytest.mark.asyncio
+    async def test_a_schedule_does_not_switch_an_mqtt_plug(self):
+        manager = SmartPlugManager()
+        mqtt = _plug(1, "mqtt")
+        session, _db = _session_returning([mqtt])
+        now = MagicMock()
+        now.strftime.return_value = "08:00"
+        with (
+            patch("backend.app.services.smart_plug_manager.datetime") as clock,
+            patch("backend.app.core.database.async_session", session),
+            patch("backend.app.services.smart_plug_manager.tasmota_service") as service,
+        ):
+            clock.now.return_value = now
+            clock.utcnow.return_value = datetime.now(timezone.utc)
+            service.turn_on = AsyncMock(return_value=True)
+            await manager._check_schedules()
+
+        service.turn_on.assert_not_awaited()
+
+    @pytest.mark.asyncio
+    async def test_a_pending_off_left_on_an_mqtt_plug_is_cleared(self):
+        manager = SmartPlugManager()
+        mqtt = _plug(1, "mqtt", auto_off_pending=True, auto_off_pending_since=datetime.now(timezone.utc))
+        session, db = _session_returning([mqtt])
+        with (
+            patch("backend.app.core.database.async_session", session),
+            patch.object(manager, "_schedule_delayed_off") as delayed,
+            patch.object(manager, "_schedule_temp_based_off") as temp,
+            patch("backend.app.services.smart_plug_manager.tasmota_service") as service,
+        ):
+            service.turn_off = AsyncMock(return_value=True)
+            await manager.resume_pending_auto_offs()
+
+        service.turn_off.assert_not_awaited()
+        delayed.assert_not_called()
+        temp.assert_not_called()
+        assert mqtt.auto_off_pending is False
+        db.commit.assert_awaited()
+
+
+class TestObicoPowerOff:
+    @pytest.mark.asyncio
+    async def test_failure_power_off_skips_an_mqtt_plug(self):
+        from backend.app.services import obico_actions
+
+        mqtt, tasmota = _plug(1, "mqtt"), _plug(2)
+        session, _db = _session_returning([])
+        with (
+            patch("backend.app.services.obico_actions.async_session", session),
+            patch(
+                "backend.app.services.smart_plug_manager.smart_plug_manager._get_plugs_for_printer",
+                AsyncMock(return_value=[mqtt, tasmota]),
+            ),
+            patch("backend.app.services.smart_plug_manager.tasmota_service") as service,
+            patch("backend.app.services.smart_plug_manager.publish_plug_state", AsyncMock()),
+            patch(
+                "backend.app.services.smart_plug_manager.run_linked_scripts_after_automatic_switch",
+                AsyncMock(),
+            ),
+        ):
+            service.turn_off = AsyncMock(return_value=True)
+            await obico_actions._turn_off_linked_plugs(1)
+
+        service.turn_off.assert_awaited_once_with(tasmota)
+
+
+async def _add_typed_plug(ctx, printer_id, plug_type, *, controls_printer_power=True):
+    async with ctx.session_maker() as db:
+        fields = {"ip_address": f"10.0.1.{printer_id}"} if plug_type != "mqtt" else {"mqtt_topic": "tele/p/SENSOR"}
+        if plug_type == "rest":
+            fields = {"rest_on_url": "http://plug.example/on", "rest_off_url": "http://plug.example/off"}
+        plug = SmartPlug(
+            name=f"{plug_type} {printer_id}",
+            plug_type=plug_type,
+            printer_id=printer_id,
+            enabled=True,
+            auto_on=True,
+            controls_printer_power=controls_printer_power,
+            **fields,
+        )
+        db.add(plug)
+        await db.commit()
+        return plug.id
+
+
+def _powered_plug_types(power_on):
+    return [call.args[0].plug_type for call in power_on.await_args_list]
+
+
+class TestQueuePowerOn:
+    @pytest.mark.asyncio
+    async def test_a_job_on_a_printer_powers_on_with_the_plug_that_can_switch(self, queue_db):
+        """The bug: the MQTT plug came first and was picked, and the job held."""
+        await _add_typed_plug(queue_db, 1, "mqtt")
+        await _add_typed_plug(queue_db, 1, "rest")
+        await _add_item(queue_db, printer_id=1)
+
+        power_on = await _run(queue_db, PrintScheduler(), power_on=AsyncMock(return_value=False))
+
+        assert _powered_plug_types(power_on) == ["rest"]
+
+    @pytest.mark.asyncio
+    async def test_an_any_model_job_wakes_with_the_plug_that_can_switch(self, queue_db):
+        await _add_typed_plug(queue_db, 1, "mqtt")
+        await _add_typed_plug(queue_db, 1, "rest")
+        await _add_item(queue_db, target_model="X1C")
+
+        power_on = await _run(queue_db, PrintScheduler(), power_on=AsyncMock(return_value=True))
+
+        assert _powered_plug_types(power_on) == ["rest"]
+
+    @pytest.mark.asyncio
+    async def test_a_printer_with_only_an_mqtt_plug_is_not_woken(self, queue_db):
+        """And says why: it has no plug that can switch it on."""
+        await _add_typed_plug(queue_db, 1, "mqtt")
+        await _add_typed_plug(queue_db, 2, "mqtt")
+        item_id = await _add_item(queue_db, target_model="X1C")
+
+        power_on = await _run(queue_db, PrintScheduler(), power_on=AsyncMock(return_value=True))
+
+        power_on.assert_not_awaited()
+        item = await _get_item(queue_db, item_id)
+        assert "no Auto On smart plug" in (item.waiting_reason or "")