test_finish_photo_moment_sync.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. """Regression tests for the #1790 producer-consumer synchronization.
  2. `on_finish_photo_moment` (producer) and `_background_finish_photo`
  3. (consumer) are dispatched back-to-back on the FINISH-state fallback path
  4. (`bambu_mqtt.py:3258-3297`). Before #1790, the consumer ran a single
  5. `pop()` on `_stage22_finish_frames` with no wait — racing past the
  6. producer with an empty result, then doing its own RTSP grab that
  7. collided with the producer's still-in-flight grab (Bambu printers allow
  8. one RTSP client). Net result: a captured frame was logged, the cache
  9. was populated ~1s later, but the notification went text-only.
  10. The fix is an `asyncio.Event` per printer registered in
  11. `_stage22_finish_in_flight` by the producer and awaited (with timeout)
  12. by the consumer. These tests pin the producer side of that contract.
  13. """
  14. import asyncio
  15. import logging
  16. from contextlib import asynccontextmanager
  17. from datetime import datetime, timezone
  18. from types import SimpleNamespace
  19. from unittest.mock import AsyncMock
  20. import pytest
  21. from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
  22. import backend.app.models # noqa: F401 - populate Base.metadata
  23. from backend.app import main as main_module
  24. from backend.app.core.database import Base
  25. from backend.app.main import on_finish_photo_moment
  26. from backend.app.models.archive import PrintArchive
  27. from backend.app.services import print_dispatch_context
  28. @asynccontextmanager
  29. async def _fake_session(printer):
  30. """Async-session stub that returns `printer` from scalar_one_or_none()."""
  31. result = SimpleNamespace(scalar_one_or_none=lambda: printer)
  32. session = SimpleNamespace(execute=AsyncMock(return_value=result))
  33. yield session
  34. @pytest.fixture
  35. def fake_printer():
  36. return SimpleNamespace(
  37. id=7,
  38. ip_address="192.0.2.7",
  39. access_code="x",
  40. model="X1C",
  41. external_camera_enabled=False,
  42. external_camera_url=None,
  43. external_camera_type=None,
  44. external_camera_snapshot_url=None,
  45. )
  46. @pytest.fixture(autouse=True)
  47. def _clean_state():
  48. """Don't leak event/cache dict entries across tests."""
  49. main_module._stage22_finish_in_flight.clear()
  50. main_module._stage22_finish_frames.clear()
  51. main_module._inprint_frame_bank.clear()
  52. main_module._inprint_frame_bank_ts.clear()
  53. print_dispatch_context.clear(7)
  54. yield
  55. main_module._stage22_finish_in_flight.clear()
  56. main_module._stage22_finish_frames.clear()
  57. main_module._inprint_frame_bank.clear()
  58. main_module._inprint_frame_bank_ts.clear()
  59. print_dispatch_context.clear(7)
  60. @pytest.fixture
  61. def patched_env(fake_printer, monkeypatch):
  62. monkeypatch.setattr(main_module, "async_session", lambda: _fake_session(fake_printer))
  63. async def _get_setting(_db, key):
  64. if key == "capture_finish_photo":
  65. return "true"
  66. return None
  67. monkeypatch.setattr(
  68. "backend.app.api.routes.settings.get_setting",
  69. _get_setting,
  70. )
  71. monkeypatch.setattr(
  72. "backend.app.api.routes.camera.get_buffered_frame",
  73. lambda _pid: None,
  74. )
  75. # #2547: default the plate restore to "print height unknown", so tests that
  76. # aren't about the restore never reach the G-code path. Tests that ARE about
  77. # it override these two.
  78. async def _no_height(_printer_id, _data, _logger, _archive_id, _plate_id=None):
  79. return None
  80. async def _not_blocked(_printer_id):
  81. return False
  82. monkeypatch.setattr(main_module, "_max_z_for_current_print", _no_height)
  83. monkeypatch.setattr(main_module, "_plate_restore_is_blocked_by_queue", _not_blocked)
  84. return fake_printer
  85. async def test_event_registered_before_first_await(patched_env, monkeypatch):
  86. """The consumer needs to find the event the moment it polls — that
  87. means registration must complete BEFORE any `await` yields control
  88. back to the loop."""
  89. # Slow the first await (DB session entry) so we can observe the dict
  90. # before the producer makes any real progress.
  91. seen_during_capture = {}
  92. async def _slow_capture(**_kwargs):
  93. seen_during_capture["registered"] = patched_env.id in main_module._stage22_finish_in_flight
  94. await asyncio.sleep(0)
  95. return b"\xff\xd8frame"
  96. monkeypatch.setattr(
  97. "backend.app.services.camera.capture_camera_frame_bytes",
  98. _slow_capture,
  99. )
  100. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  101. assert seen_during_capture["registered"] is True
  102. async def test_event_set_after_successful_capture(patched_env, monkeypatch):
  103. async def _capture(**_kwargs):
  104. return b"\xff\xd8frame"
  105. monkeypatch.setattr(
  106. "backend.app.services.camera.capture_camera_frame_bytes",
  107. _capture,
  108. )
  109. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  110. event = main_module._stage22_finish_in_flight[patched_env.id]
  111. assert event.is_set()
  112. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8frame"
  113. async def test_event_set_when_capture_returns_no_frame(patched_env, monkeypatch):
  114. """Producer gives up (RTSP timeout, no buffered frame, no external
  115. camera) — consumer must NOT wait the full 20s for nothing."""
  116. async def _capture(**_kwargs):
  117. return None
  118. monkeypatch.setattr(
  119. "backend.app.services.camera.capture_camera_frame_bytes",
  120. _capture,
  121. )
  122. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  123. event = main_module._stage22_finish_in_flight[patched_env.id]
  124. assert event.is_set()
  125. assert patched_env.id not in main_module._stage22_finish_frames
  126. async def test_event_set_even_when_capture_raises(patched_env, monkeypatch):
  127. """Producer hit a bug or network error — `finally` still has to
  128. release the consumer."""
  129. async def _capture(**_kwargs):
  130. raise RuntimeError("camera went away")
  131. monkeypatch.setattr(
  132. "backend.app.services.camera.capture_camera_frame_bytes",
  133. _capture,
  134. )
  135. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  136. event = main_module._stage22_finish_in_flight[patched_env.id]
  137. assert event.is_set()
  138. async def test_no_event_when_timelapse_was_active(patched_env):
  139. """On the timelapse-on path the consumer takes the
  140. `_capture_finish_photo_from_timelapse` branch and shouldn't be
  141. blocked by a producer wait — the producer doesn't enter the
  142. lifecycle."""
  143. await on_finish_photo_moment(
  144. patched_env.id,
  145. {"trigger": "stage_22", "timelapse_was_active": True},
  146. )
  147. assert patched_env.id not in main_module._stage22_finish_in_flight
  148. async def test_event_set_when_capture_setting_disabled(patched_env, monkeypatch):
  149. """Even on the early-return-before-capture path, the event must be
  150. released so the consumer doesn't hang on a no-op producer."""
  151. async def _disabled_setting(_db, _key):
  152. return "false"
  153. monkeypatch.setattr(
  154. "backend.app.api.routes.settings.get_setting",
  155. _disabled_setting,
  156. )
  157. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  158. event = main_module._stage22_finish_in_flight[patched_env.id]
  159. assert event.is_set()
  160. async def test_consumer_wait_unblocked_when_producer_completes(patched_env, monkeypatch):
  161. """End-to-end sync check: a consumer-style waiter awaiting the
  162. event finishes promptly once the producer's finally fires."""
  163. async def _capture(**_kwargs):
  164. await asyncio.sleep(0.05)
  165. return b"\xff\xd8frame"
  166. monkeypatch.setattr(
  167. "backend.app.services.camera.capture_camera_frame_bytes",
  168. _capture,
  169. )
  170. producer = asyncio.create_task(on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"}))
  171. await asyncio.sleep(0) # let the producer register
  172. event = main_module._stage22_finish_in_flight[patched_env.id]
  173. await asyncio.wait_for(event.wait(), timeout=1.0)
  174. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8frame"
  175. await producer
  176. async def test_finish_state_prefers_banked_frame_when_end_gcode_was_injected(patched_env, monkeypatch):
  177. """#1867: when Bambuddy injected End G-code, a SwapMod snippet may already
  178. have ejected the plate by FINISH — so the banked in-print frame is used and
  179. the live grab must not run."""
  180. print_dispatch_context.mark_pending(patched_env.id)
  181. print_dispatch_context.adopt(patched_env.id)
  182. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  183. live_called = {"n": 0}
  184. async def _live(**_kwargs):
  185. live_called["n"] += 1
  186. return b"\xff\xd8live-post-swap"
  187. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  188. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  189. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8banked"
  190. assert live_called["n"] == 0
  191. async def test_finish_state_grabs_live_when_no_end_gcode_was_injected(patched_env, monkeypatch):
  192. """#2547: the ordinary case. Nothing moved the plate, the toolhead is
  193. parked, and the print is still sitting there — so the live frame is the
  194. finished print, and a banked mid-print frame must NOT win over it.
  195. Preferring the bank here unconditionally, which is what this code used to
  196. do, is how the H2C shipped a photo with the toolhead over the part."""
  197. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked-midprint"
  198. async def _live(**_kwargs):
  199. return b"\xff\xd8live-finished-print"
  200. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  201. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  202. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live-finished-print"
  203. async def test_finish_state_falls_back_to_live_when_bank_is_empty(patched_env, monkeypatch):
  204. """End G-code was injected but nothing was ever banked (feature just
  205. enabled, tiny print, capture failures). Degrade to a live grab rather than
  206. sending a text-only notification."""
  207. print_dispatch_context.mark_pending(patched_env.id)
  208. print_dispatch_context.adopt(patched_env.id)
  209. async def _live(**_kwargs):
  210. return b"\xff\xd8live"
  211. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  212. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  213. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live"
  214. async def test_stage_22_trigger_ignores_bank(patched_env, monkeypatch):
  215. """The `stage_22` trigger fires before any End G-code and gives cleaner
  216. (parked-toolhead, plate-still-up) framing via a live grab — the bank is only
  217. for the post-swap `finish_state` path, so it must be ignored here."""
  218. print_dispatch_context.mark_pending(patched_env.id)
  219. print_dispatch_context.adopt(patched_env.id)
  220. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  221. async def _live(**_kwargs):
  222. return b"\xff\xd8live"
  223. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  224. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  225. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8live"
  226. # --- #1867 banking helper (_maybe_bank_inprint_frame) --------------------
  227. def _bank_env(monkeypatch, *, state="RUNNING", sub_stage=0, total_layers=10, printer=object()):
  228. """Wire printer_manager.get_client + the snapshot capture for the bank
  229. helper. Capture returns a distinct frame per call so updates are visible."""
  230. client = SimpleNamespace(
  231. state=SimpleNamespace(state=state, mc_print_sub_stage=sub_stage, total_layers=total_layers)
  232. )
  233. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: client)
  234. monkeypatch.setattr(main_module, "async_session", lambda: _fake_session(printer))
  235. counter = {"n": 0, "light": []}
  236. async def _capture(_pid, _printer, _logger, *, light=True):
  237. counter["n"] += 1
  238. counter["light"].append(light)
  239. return f"frame-{counter['n']}".encode()
  240. monkeypatch.setattr(main_module, "_capture_snapshot_for_notification", _capture)
  241. return counter
  242. async def test_bank_stores_frame_while_printing(monkeypatch):
  243. _bank_env(monkeypatch)
  244. await main_module._maybe_bank_inprint_frame(3, 5)
  245. assert main_module._inprint_frame_bank[3] == b"frame-1"
  246. async def test_bank_leaves_the_chamber_light_alone(monkeypatch):
  247. """#1655: the bank grabs a frame every 25 seconds all through a print, so
  248. holding the chamber light for it would make the light flash."""
  249. counter = _bank_env(monkeypatch)
  250. await main_module._maybe_bank_inprint_frame(3, 5)
  251. assert counter["light"] == [False]
  252. async def test_bank_throttles_within_interval(monkeypatch):
  253. counter = _bank_env(monkeypatch)
  254. await main_module._maybe_bank_inprint_frame(3, 5) # banks frame-1
  255. await main_module._maybe_bank_inprint_frame(3, 6) # within 25s -> skipped
  256. assert counter["n"] == 1
  257. assert main_module._inprint_frame_bank[3] == b"frame-1"
  258. async def test_bank_throttles_on_the_last_layer_too(monkeypatch):
  259. """#2547: the last layer used to bypass the throttle so it always got a
  260. fresh frame. Now that progress advances also drive banking, that exemption
  261. would fire a camera grab on every percent tick of a multi-minute last layer
  262. — and each grab contends with the live view for the single RTSP slot."""
  263. counter = _bank_env(monkeypatch, total_layers=10)
  264. await main_module._maybe_bank_inprint_frame(3, 5) # banks frame-1
  265. await main_module._maybe_bank_inprint_frame(3, 10) # last layer, within 25s
  266. assert counter["n"] == 1
  267. assert main_module._inprint_frame_bank[3] == b"frame-1"
  268. async def test_bank_refreshes_on_the_last_layer_once_the_throttle_elapses(monkeypatch):
  269. """The point of banking on progress: a three-minute last layer keeps
  270. refreshing instead of freezing at the moment that layer began."""
  271. counter = _bank_env(monkeypatch, total_layers=10)
  272. await main_module._maybe_bank_inprint_frame(3, 10) # banks frame-1
  273. # Pretend the throttle window has passed, as it does mid-last-layer.
  274. main_module._inprint_frame_bank_ts[3] -= main_module._INPRINT_BANK_MIN_INTERVAL + 1
  275. await main_module._maybe_bank_inprint_frame(3, 10)
  276. assert counter["n"] == 2
  277. assert main_module._inprint_frame_bank[3] == b"frame-2"
  278. async def test_bank_skips_when_not_running(monkeypatch):
  279. """End G-code (plate swap) runs after RUNNING ends — the bank must not
  280. update then, which is what freezes it on the finished print."""
  281. _bank_env(monkeypatch, state="FINISH")
  282. await main_module._maybe_bank_inprint_frame(3, 10)
  283. assert 3 not in main_module._inprint_frame_bank
  284. async def test_bank_skips_during_calibration_substage(monkeypatch):
  285. """layer_num ticks during pre-print calibration (non-zero sub-stage) —
  286. banking then would capture an empty bed."""
  287. _bank_env(monkeypatch, sub_stage=14)
  288. await main_module._maybe_bank_inprint_frame(3, 2)
  289. assert 3 not in main_module._inprint_frame_bank
  290. class TestStage22CacheHoldsExactlyOneRotation:
  291. """#2708. `_stage22_finish_frames` is fed from two kinds of source: live
  292. grabs, which are raw, and the #1867 in-print bank, whose bytes came from
  293. `_capture_snapshot_for_notification` and are therefore ALREADY rotated.
  294. The consumer cannot tell them apart, so the producer normalises: every
  295. entry in the cache has had the rotation applied exactly once.
  296. Rotating on the consumer side instead put two rotations on the banked
  297. path — at 180 degrees that is the reported bug reproduced exactly, and at
  298. 90/270 it lands the photo 180 degrees out.
  299. """
  300. @staticmethod
  301. def _jpeg(width, height):
  302. import io
  303. from PIL import Image
  304. buf = io.BytesIO()
  305. Image.new("RGB", (width, height), (0, 0, 255)).save(buf, format="JPEG")
  306. return buf.getvalue()
  307. @staticmethod
  308. def _size(data):
  309. import io
  310. from PIL import Image
  311. return Image.open(io.BytesIO(data)).size
  312. async def test_a_live_grab_is_rotated_before_caching(self, patched_env, monkeypatch):
  313. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  314. raw = self._jpeg(64, 32)
  315. async def _capture(**_kwargs):
  316. return raw
  317. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  318. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  319. cached = main_module._stage22_finish_frames[patched_env.id]
  320. assert self._size(cached) == (32, 64)
  321. async def test_the_banked_frame_is_cached_verbatim(self, patched_env, monkeypatch):
  322. """The bank is filled by `_capture_snapshot_for_notification`, which
  323. rotates before it returns — so the producer must pass those bytes
  324. through untouched rather than rotating them a second time.
  325. Note this pins the invariant forward; it does not on its own prove the
  326. bug fixed, because the old producer didn't rotate anything either. The
  327. pair that discriminates is `test_a_live_grab_is_rotated_before_caching`
  328. (producer now rotates) plus the source guard below (consumer no longer
  329. does).
  330. """
  331. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  332. # #2547: the bank is only preferred when End G-code was injected.
  333. print_dispatch_context.mark_pending(patched_env.id)
  334. print_dispatch_context.adopt(patched_env.id)
  335. already_rotated = self._jpeg(32, 64) # what one rotation of a 64x32 frame looks like
  336. main_module._inprint_frame_bank[patched_env.id] = already_rotated
  337. async def _capture(**_kwargs): # pragma: no cover - must not be reached
  338. raise AssertionError("the banked frame should have been preferred")
  339. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  340. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  341. cached = main_module._stage22_finish_frames[patched_env.id]
  342. assert cached is already_rotated
  343. assert self._size(cached) == (32, 64)
  344. async def test_a_stage22_grab_is_rotated_even_though_the_bank_is_full(self, patched_env, monkeypatch):
  345. """Only the `finish_state` trigger reads the bank. The `stage_22` and
  346. `last_layer` triggers take a live grab, which still needs rotating —
  347. a shared "did we use the bank" flag must not latch on the bank merely
  348. existing."""
  349. monkeypatch.setattr(patched_env, "camera_rotation", 90, raising=False)
  350. main_module._inprint_frame_bank[patched_env.id] = self._jpeg(999, 1)
  351. async def _capture(**_kwargs):
  352. return self._jpeg(64, 32)
  353. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  354. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  355. cached = main_module._stage22_finish_frames[patched_env.id]
  356. assert self._size(cached) == (32, 64)
  357. async def test_no_rotation_configured_caches_the_bytes_as_captured(self, patched_env, monkeypatch):
  358. raw = self._jpeg(64, 32)
  359. async def _capture(**_kwargs):
  360. return raw
  361. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _capture)
  362. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  363. assert main_module._stage22_finish_frames[patched_env.id] is raw
  364. def test_the_consumer_does_not_rotate_the_cached_frame():
  365. """The other half of the #2708 invariant, and the half with no runtime
  366. harness: `_background_finish_photo` is a closure nested inside
  367. `on_print_complete`, so nothing can drive its cached-frame branch
  368. directly. What it must NOT do is rotate what it pops from
  369. `_stage22_finish_frames` — the producer has already done that, and doing
  370. it again upside-downs the banked path, which is the bug this fixed.
  371. Checked against the source because the alternative is no check at all.
  372. """
  373. import ast
  374. from pathlib import Path
  375. main_py = Path(__file__).resolve().parents[2] / "app" / "main.py"
  376. assert main_py.exists(), f"guard is looking in the wrong place: {main_py}"
  377. tree = ast.parse(main_py.read_text())
  378. offenders = [
  379. node.lineno
  380. for node in ast.walk(tree)
  381. if isinstance(node, ast.Call)
  382. and isinstance(node.func, ast.Name)
  383. and node.func.id == "_apply_camera_rotation"
  384. and node.args
  385. and isinstance(node.args[0], ast.Name)
  386. and node.args[0].id == "cached_frame"
  387. ]
  388. assert not offenders, (
  389. f"main.py:{offenders} rotates the frame popped from _stage22_finish_frames. "
  390. "Those bytes are already rotated by on_finish_photo_moment (#2708); rotating "
  391. "again returns a 180-degree print to upside-down."
  392. )
  393. class TestPlateRestore:
  394. """#2547 / #1145 / #1397 / #1565: put the plate back into camera framing.
  395. Bambu's end G-code drops the plate ~100mm as the last thing it does, so by
  396. FINISH the finished print sits well below where the camera frames it. The
  397. restore commands an ABSOLUTE Z back to just above the last printed layer.
  398. Absolute is the safety argument, and these tests pin it: the target is a
  399. height the toolhead was physically at seconds earlier, so it is inside the
  400. travel limits and leaves the nozzle above the part. It is also unambiguous
  401. across model families — Z is the nozzle-to-bed gap whether the bed moves or
  402. the toolhead does — so there is no sign to get wrong the way the relative
  403. bed-jog path had (#1334).
  404. """
  405. @pytest.fixture
  406. def printer_client(self, monkeypatch):
  407. sent: list[str] = []
  408. client = SimpleNamespace(
  409. state=SimpleNamespace(state="FINISH"),
  410. send_gcode=lambda gcode: (sent.append(gcode), True)[1],
  411. )
  412. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: client)
  413. monkeypatch.setattr(main_module.asyncio, "sleep", AsyncMock())
  414. client.sent = sent
  415. return client
  416. async def test_commands_an_absolute_move_above_the_print(self, printer_client):
  417. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  418. assert ok is True
  419. assert printer_client.sent == ["G90\nG1 Z26.00 F600"]
  420. async def test_never_touches_m211(self, printer_client):
  421. """#2579: disabling soft endstops is what let a jog drive the nozzle
  422. into the bed. This path must not reintroduce it."""
  423. await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  424. assert not any("M211" in line for line in printer_client.sent)
  425. async def test_skipped_when_the_printer_is_no_longer_in_finish(self, printer_client):
  426. """The queue dispatches the next job the instant a print completes.
  427. Commanding a plate move into a starting print is not a race worth
  428. having, so state is re-read immediately before the move."""
  429. printer_client.state.state = "RUNNING"
  430. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  431. assert ok is False
  432. assert printer_client.sent == []
  433. async def test_skipped_when_the_printer_is_gone(self, monkeypatch):
  434. monkeypatch.setattr(main_module.printer_manager, "get_client", lambda _pid: None)
  435. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  436. assert ok is False
  437. async def test_reports_failure_when_the_send_fails(self, printer_client, monkeypatch):
  438. """A failed send means the plate never moved — the caller must not go on
  439. to owe it a move back down."""
  440. monkeypatch.setattr(printer_client, "send_gcode", lambda _g: False)
  441. ok = await main_module._restore_plate_for_finish_photo(7, 16.0, logging.getLogger(__name__))
  442. assert ok is False
  443. def test_park_lowers_the_plate_again(self, printer_client):
  444. main_module._park_plate_after_finish_photo(7, 16.0, logging.getLogger(__name__))
  445. assert printer_client.sent == ["G90\nG1 Z116.00 F600"]
  446. def test_park_skipped_once_the_next_print_has_started(self, printer_client):
  447. printer_client.state.state = "RUNNING"
  448. main_module._park_plate_after_finish_photo(7, 16.0, logging.getLogger(__name__))
  449. assert printer_client.sent == []
  450. class TestPlateRestoreWiring:
  451. """The restore only runs in the one situation it is correct for, and the
  452. plate always comes back down afterwards."""
  453. @pytest.fixture
  454. def restore_env(self, patched_env, monkeypatch):
  455. calls = {"restore": [], "park": [], "blocked": False, "height": 16.0, "bound": []}
  456. async def _height(_printer_id, _data, _logger, archive_id, plate_id=None):
  457. calls["bound"].append((archive_id, plate_id))
  458. return calls["height"]
  459. async def _blocked(_printer_id):
  460. return calls["blocked"]
  461. async def _restore(printer_id, max_z, _logger):
  462. calls["restore"].append((printer_id, max_z))
  463. return True
  464. def _park(printer_id, max_z, _logger):
  465. calls["park"].append((printer_id, max_z))
  466. monkeypatch.setattr(main_module, "_max_z_for_current_print", _height)
  467. monkeypatch.setattr(main_module, "_plate_restore_is_blocked_by_queue", _blocked)
  468. monkeypatch.setattr(main_module, "_restore_plate_for_finish_photo", _restore)
  469. monkeypatch.setattr(main_module, "_park_plate_after_finish_photo", _park)
  470. async def _live(**_kwargs):
  471. return b"\xff\xd8live"
  472. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  473. return calls
  474. async def test_restores_then_parks_on_the_finish_state_path(self, patched_env, restore_env):
  475. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  476. assert restore_env["restore"] == [(patched_env.id, 16.0)]
  477. assert restore_env["park"] == [(patched_env.id, 16.0)]
  478. async def test_reads_the_binding_before_on_print_complete_pops_it(self, patched_env, restore_env, monkeypatch):
  479. """#3240: on the FINISH-state path on_print_complete is dispatched right
  480. behind the producer and pops the print's archive binding and plate. The
  481. producer must have read them first, or the restore has nothing bound to
  482. move for and never runs."""
  483. async def _yielding_get_setting(_db, key):
  484. # A real settings read suspends; this is where on_print_complete
  485. # gets to run.
  486. await asyncio.sleep(0)
  487. return "true" if key == "capture_finish_photo" else None
  488. monkeypatch.setattr("backend.app.api.routes.settings.get_setting", _yielding_get_setting)
  489. main_module._active_prints[(patched_env.id, "job.3mf")] = 5
  490. main_module._print_plate_ids[5] = 3
  491. async def _on_print_complete_pops():
  492. main_module._active_prints.clear()
  493. main_module._print_plate_ids.clear()
  494. try:
  495. data = {"trigger": "finish_state", "filename": "job.3mf", "subtask_name": "job"}
  496. producer = asyncio.create_task(on_finish_photo_moment(patched_env.id, data))
  497. completion = asyncio.create_task(_on_print_complete_pops())
  498. await asyncio.gather(producer, completion)
  499. finally:
  500. main_module._active_prints.clear()
  501. main_module._print_plate_ids.clear()
  502. assert restore_env["bound"] == [(5, 3)]
  503. async def test_not_restored_on_the_stage_22_path(self, patched_env, restore_env):
  504. """Stage 22 fires before the end G-code drops the plate — it is already
  505. where we want it, and moving it would only cost the settle delay."""
  506. await on_finish_photo_moment(patched_env.id, {"trigger": "stage_22"})
  507. assert restore_env["restore"] == []
  508. assert restore_env["park"] == []
  509. async def test_not_restored_when_the_banked_frame_is_used(self, patched_env, restore_env):
  510. """The plate has been swapped out — no move brings the print back."""
  511. print_dispatch_context.mark_pending(patched_env.id)
  512. print_dispatch_context.adopt(patched_env.id)
  513. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  514. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  515. assert restore_env["restore"] == []
  516. assert restore_env["park"] == []
  517. async def test_not_restored_when_end_gcode_was_injected_but_the_bank_is_empty(self, patched_env, restore_env):
  518. """A plate-swap machine may have just ejected its plate. Even with no
  519. banked frame to fall back on, driving Z into whatever a swap mechanism
  520. is doing is not worth a photo of a bed we know may be bare."""
  521. print_dispatch_context.mark_pending(patched_env.id)
  522. print_dispatch_context.adopt(patched_env.id)
  523. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  524. assert restore_env["restore"] == []
  525. assert restore_env["park"] == []
  526. async def test_not_restored_when_the_print_height_is_unknown(self, patched_env, restore_env):
  527. restore_env["height"] = None
  528. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  529. assert restore_env["restore"] == []
  530. assert restore_env["park"] == []
  531. async def test_not_restored_when_another_job_is_queued(self, patched_env, restore_env):
  532. restore_env["blocked"] = True
  533. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  534. assert restore_env["restore"] == []
  535. assert restore_env["park"] == []
  536. async def test_not_restored_when_the_setting_is_off(self, patched_env, restore_env, monkeypatch):
  537. async def _get_setting(_db, key):
  538. if key == "capture_finish_photo":
  539. return "true"
  540. if key == "finish_photo_restore_plate":
  541. return "false"
  542. return None
  543. monkeypatch.setattr("backend.app.api.routes.settings.get_setting", _get_setting)
  544. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  545. assert restore_env["restore"] == []
  546. assert restore_env["park"] == []
  547. async def test_plate_is_parked_even_when_the_capture_throws(self, patched_env, restore_env, monkeypatch):
  548. """We raised it, so we owe the move back down — including when the grab
  549. between the two fails. Otherwise the user finds the print pinned under
  550. the nozzle."""
  551. async def _boom(**_kwargs):
  552. raise RuntimeError("camera gone")
  553. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _boom)
  554. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  555. assert restore_env["restore"] == [(patched_env.id, 16.0)]
  556. assert restore_env["park"] == [(patched_env.id, 16.0)]
  557. async def test_producer_event_is_still_set_after_a_restore(self, patched_env, restore_env):
  558. """#1790: the consumer's bounded wait must be released on every exit,
  559. and the restore added a new path through the producer."""
  560. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  561. assert main_module._stage22_finish_in_flight[patched_env.id].is_set()
  562. async def test_producer_wait_budget_covers_the_restore():
  563. """The consumer's wait has to outlast settle + a worst-case RTSP grab, and
  564. still finish inside the notification's own photo budget — otherwise the
  565. restore path is cut off by a timeout somewhere above it."""
  566. assert main_module._FINISH_PHOTO_PRODUCER_WAIT_SECONDS > main_module._PLATE_RESTORE_SETTLE_SECONDS + 15
  567. def test_producer_wait_budget_covers_the_chamber_light_delay():
  568. """#1655: the producer's live grab can first wait for the chamber light.
  569. Settle + the longest light delay + a worst-case grab must still fit, or the
  570. consumer gives up and its fallback grab races the producer's (#1790)."""
  571. from backend.app.services.camera_light import MAX_DELAY_SECONDS
  572. assert (
  573. main_module._FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  574. > main_module._PLATE_RESTORE_SETTLE_SECONDS + MAX_DELAY_SECONDS + 15
  575. )
  576. class TestMaxZResolution:
  577. """#2547 safety: the height that becomes a Z-move target must provably
  578. belong to the print that just finished.
  579. A height from another print is the one failure mode that could drive the
  580. nozzle into the model — 20mm carried onto a 200mm print commands the plate
  581. up through the part. So the resolver refuses on every ambiguity rather than
  582. falling back to "whatever ran last on this printer".
  583. Run against a real database (#3240): the earlier tests faked the session,
  584. so neither the query nor the path the archive's file is read from was ever
  585. exercised, and both were wrong.
  586. """
  587. @pytest.fixture
  588. async def resolver_env(self, monkeypatch, tmp_path):
  589. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  590. async with engine.begin() as conn:
  591. await conn.run_sync(Base.metadata.create_all)
  592. session_maker = async_sessionmaker(engine, expire_on_commit=False)
  593. env = {"reported_layers": 30, "height": 16.0, "read": [], "session_maker": session_maker}
  594. monkeypatch.setattr(main_module, "async_session", session_maker)
  595. monkeypatch.setattr(main_module.app_settings, "base_dir", tmp_path)
  596. monkeypatch.setattr(
  597. main_module.printer_manager,
  598. "get_client",
  599. lambda _pid: SimpleNamespace(state=SimpleNamespace(total_layers=env["reported_layers"])),
  600. )
  601. def _extract(path, plate):
  602. env["read"].append((path, plate))
  603. return env["height"]
  604. monkeypatch.setattr("backend.app.utils.threemf_tools.extract_max_z_height_from_3mf", _extract)
  605. try:
  606. yield env
  607. finally:
  608. await engine.dispose()
  609. @staticmethod
  610. async def _archive(env, **overrides) -> int:
  611. values = {
  612. "printer_id": 1,
  613. "filename": "job.gcode.3mf",
  614. "file_path": "archive/1/job/job.gcode.3mf",
  615. "file_size": 1,
  616. "print_name": "job",
  617. "status": "completed",
  618. "plate_id": 1,
  619. "total_layers": 30,
  620. }
  621. values.update(overrides)
  622. async with env["session_maker"]() as db:
  623. archive = PrintArchive(**values)
  624. db.add(archive)
  625. await db.commit()
  626. return archive.id
  627. @staticmethod
  628. async def _resolve(name, archive_id, plate_id=None):
  629. data = {"subtask_name": name} if name is not None else {}
  630. return await main_module._max_z_for_current_print(1, data, logging.getLogger(__name__), archive_id, plate_id)
  631. async def test_returns_the_height_when_binding_name_and_layers_agree(self, resolver_env):
  632. archive_id = await self._archive(resolver_env)
  633. assert await self._resolve("job", archive_id) == 16.0
  634. async def test_refuses_a_print_that_is_not_bound_to_an_archive(self, resolver_env):
  635. """A name alone is never enough: with no binding there is no move, even
  636. when an archive of exactly that name exists."""
  637. await self._archive(resolver_env)
  638. assert await self._resolve("job", None) is None
  639. assert resolver_env["read"] == []
  640. async def test_uses_the_bound_archive_not_a_newer_one_of_the_same_name(self, resolver_env):
  641. """The support-bundle case: a reprint reuses archive 169, while a newer
  642. archive of the same file (another plate) is 288. The name lookup took
  643. 288; only the layer check stopped it."""
  644. bound = await self._archive(resolver_env, file_path="archive/reprinted.gcode.3mf", total_layers=125)
  645. await self._archive(resolver_env, file_path="archive/other-plate.gcode.3mf", total_layers=313)
  646. resolver_env["reported_layers"] = 125
  647. assert await self._resolve("job", bound) == 16.0
  648. assert resolver_env["read"][0][0].name == "reprinted.gcode.3mf"
  649. async def test_reads_the_plate_the_job_was_dispatched_with(self, resolver_env):
  650. """A reprint of one plate reuses the archive row without updating its
  651. plate_id, so the dispatched plate wins."""
  652. archive_id = await self._archive(resolver_env, plate_id=1)
  653. await self._resolve("job", archive_id, plate_id=12)
  654. assert resolver_env["read"][0][1] == 12
  655. await self._resolve("job", archive_id)
  656. assert resolver_env["read"][1][1] == 1
  657. async def test_reads_a_relative_file_path_from_the_data_directory(self, resolver_env, tmp_path):
  658. """#3240: archive paths are stored relative to the data directory. The
  659. resolver joined them to a `data_dir` setting that does not exist, so the
  660. lookup raised, was logged at debug level, and the plate never moved."""
  661. archive_id = await self._archive(resolver_env, file_path="archive/1/job/job.gcode.3mf", plate_id=2)
  662. assert await self._resolve("job", archive_id) == 16.0
  663. assert resolver_env["read"] == [(tmp_path / "archive/1/job/job.gcode.3mf", 2)]
  664. async def test_an_absolute_file_path_is_read_as_stored(self, resolver_env):
  665. archive_id = await self._archive(resolver_env, file_path="/srv/bambuddy/archive/job.gcode.3mf")
  666. assert await self._resolve("job", archive_id) == 16.0
  667. assert str(resolver_env["read"][0][0]) == "/srv/bambuddy/archive/job.gcode.3mf"
  668. async def test_matches_a_name_the_printer_echoed_with_underscores(self, resolver_env):
  669. """#3240: the printer reports "Cube v2" as "Cube_v2"."""
  670. archive_id = await self._archive(resolver_env, print_name="Cube v2", filename="Cube v2.gcode.3mf")
  671. assert await self._resolve("Cube_v2", archive_id) == 16.0
  672. async def test_matches_on_the_filename_with_or_without_its_extension(self, resolver_env):
  673. archive_id = await self._archive(resolver_env, print_name=None, filename="Bracket Left.gcode.3mf")
  674. assert await self._resolve("Bracket_Left", archive_id) == 16.0
  675. assert await self._resolve("Bracket_Left.gcode", archive_id) == 16.0
  676. assert await self._resolve("Bracket Left.gcode.3mf", archive_id) == 16.0
  677. async def test_matches_a_file_name_that_ends_in_a_space(self, resolver_env):
  678. """#3241: "Part .gcode.3mf" is echoed as "Part_"."""
  679. archive_id = await self._archive(resolver_env, print_name="Part ", filename="Part .gcode.3mf")
  680. assert await self._resolve("Part_", archive_id) == 16.0
  681. async def test_refuses_a_bound_archive_with_another_name(self, resolver_env):
  682. archive_id = await self._archive(resolver_env)
  683. assert await self._resolve("other", archive_id) is None
  684. async def test_matches_by_equality_not_substring(self, resolver_env):
  685. """ "Cube" must never resolve to "Cube v2" — a different print, quite
  686. possibly a much taller one."""
  687. archive_id = await self._archive(resolver_env, print_name="Cube v2", filename="Cube v2.gcode.3mf")
  688. assert await self._resolve("Cube", archive_id) is None
  689. async def test_a_truncated_echo_does_not_match(self, resolver_env):
  690. """The completion check accepts the printer's "..." truncation; a Z
  691. move must not, since the cut-off name could belong to another print."""
  692. archive_id = await self._archive(resolver_env, print_name="A very long print name indeed")
  693. assert await self._resolve("A_very_long_print...", archive_id) is None
  694. async def test_refuses_another_printers_or_a_failed_or_deleted_archive(self, resolver_env):
  695. for overrides in ({"printer_id": 2}, {"status": "failed"}, {"deleted_at": datetime.now(timezone.utc)}):
  696. archive_id = await self._archive(resolver_env, **overrides)
  697. assert await self._resolve("job", archive_id) is None, overrides
  698. async def test_refuses_when_the_print_has_no_name_to_match_on(self, resolver_env):
  699. archive_id = await self._archive(resolver_env)
  700. assert await self._resolve(None, archive_id) is None
  701. assert resolver_env["read"] == []
  702. async def test_refuses_when_the_layer_counts_disagree(self, resolver_env):
  703. """The corroboration check. The archive's layer count comes from the
  704. 3MF; the printer's comes from MQTT. If two independent sources disagree,
  705. the row is not this print whatever its name says."""
  706. archive_id = await self._archive(resolver_env)
  707. resolver_env["reported_layers"] = 240
  708. assert await self._resolve("job", archive_id) is None
  709. async def test_proceeds_when_a_layer_count_is_simply_unknown(self, resolver_env):
  710. """Absent is not the same as contradictory — a print Bambuddy has no
  711. layer count for still gets its height, because binding and name agree."""
  712. archive_id = await self._archive(resolver_env)
  713. resolver_env["reported_layers"] = 0
  714. assert await self._resolve("job", archive_id) == 16.0
  715. resolver_env["reported_layers"] = 30
  716. unknown_layers = await self._archive(resolver_env, total_layers=None)
  717. assert await self._resolve("job", unknown_layers) == 16.0
  718. async def test_refuses_when_the_archive_has_no_file(self, resolver_env):
  719. archive_id = await self._archive(resolver_env, file_path="")
  720. assert await self._resolve("job", archive_id) is None
  721. async def test_refuses_when_the_3mf_has_no_height(self, resolver_env):
  722. archive_id = await self._archive(resolver_env)
  723. resolver_env["height"] = None
  724. assert await self._resolve("job", archive_id) is None
  725. class TestBoundPrint:
  726. """The binding the plate restore reads (#3240)."""
  727. @pytest.fixture(autouse=True)
  728. def _clean(self):
  729. main_module._active_prints.clear()
  730. main_module._print_plate_ids.clear()
  731. yield
  732. main_module._active_prints.clear()
  733. main_module._print_plate_ids.clear()
  734. def test_finds_the_archive_under_the_keys_on_print_complete_tries(self):
  735. main_module._active_prints[(7, "Cube v2.gcode.3mf")] = 169
  736. main_module._active_prints[(7, "Cube_v2.3mf")] = 169
  737. main_module._print_plate_ids[169] = 12
  738. bound = main_module._bound_print(7, {"filename": "Cube_v2.3mf", "subtask_name": "Cube_v2"})
  739. assert bound == (169, 12)
  740. def test_reads_without_consuming(self):
  741. """on_print_complete still has to find the binding after we looked."""
  742. main_module._active_prints[(7, "job.3mf")] = 5
  743. main_module._print_plate_ids[5] = 2
  744. main_module._bound_print(7, {"filename": "job.3mf", "subtask_name": "job"})
  745. assert main_module._active_prints == {(7, "job.3mf"): 5}
  746. assert main_module._print_plate_ids == {5: 2}
  747. def test_unbound_print_and_other_printers(self):
  748. main_module._active_prints[(8, "job.3mf")] = 5
  749. assert main_module._bound_print(7, {"filename": "job.3mf", "subtask_name": "job"}) == (None, None)
  750. assert main_module._bound_print(7, {}) == (None, None)
  751. def test_no_plate_recorded(self):
  752. main_module._active_prints[(7, "job.3mf")] = 5
  753. assert main_module._bound_print(7, {"filename": "job.3mf", "subtask_name": "job"}) == (5, None)
  754. def test_same_archive_as_on_print_complete_takes(self):
  755. """Keys tried in the same order, so the first one present wins in both."""
  756. main_module._active_prints[(7, "job.gcode.3mf")] = 1
  757. main_module._active_prints[(7, "job.3mf")] = 2
  758. keys = main_module._completion_print_keys(7, "job.3mf", "job")
  759. first = next(main_module._active_prints[k] for k in keys if k in main_module._active_prints)
  760. assert main_module._bound_print(7, {"filename": "job.3mf", "subtask_name": "job"})[0] == first == 2
  761. class TestTimelapsePathPlateRestore:
  762. """#2547: the timelapse path falls through to a live grab whenever the
  763. video hasn't landed yet — the documented usual outcome on P1-series.
  764. `on_finish_photo_moment` returns early for those prints without raising the
  765. plate, so the photo that actually ships in the notification would be of an
  766. already-dropped plate. The consumer therefore does the restore itself, but
  767. only on that path — everywhere else the producer has already done it.
  768. """
  769. def test_notification_budget_outlasts_the_video_poll_plus_a_restore(self):
  770. """The wait has to cover polling for the video AND the restore that
  771. follows when it doesn't arrive. At the old flat 75s the fallback was
  772. cut off mid-settle, so the plate would have moved for a photo nobody
  773. was still waiting for."""
  774. assert (
  775. main_module._FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + main_module._FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  776. > main_module._FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + main_module._PLATE_RESTORE_SETTLE_SECONDS + 15
  777. )
  778. async def test_producer_skips_the_restore_when_a_timelapse_was_recording(self, patched_env, monkeypatch):
  779. """The producer returns before any of the restore code — the consumer
  780. owns it on this path, and doing it in both would move the plate twice."""
  781. moved = []
  782. async def _restore(printer_id, max_z, _logger):
  783. moved.append((printer_id, max_z))
  784. return True
  785. async def _height(_printer_id, _data, _logger, _archive_id, _plate_id=None):
  786. return 16.0
  787. monkeypatch.setattr(main_module, "_restore_plate_for_finish_photo", _restore)
  788. monkeypatch.setattr(main_module, "_max_z_for_current_print", _height)
  789. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state", "timelapse_was_active": True})
  790. assert moved == []
  791. # --- #1655 chamber light for the camera ------------------------------------
  792. class _LightClient:
  793. def __init__(self):
  794. self.state = SimpleNamespace(chamber_light=False)
  795. self.calls: list[bool] = []
  796. self.mode = "off" # the camera_light_mode setting
  797. def set_chamber_light(self, on):
  798. self.calls.append(on)
  799. self.state.chamber_light = on
  800. return True
  801. @pytest.fixture
  802. def light_client(monkeypatch):
  803. from backend.app.services import camera_light as light_svc
  804. client = _LightClient()
  805. monkeypatch.setattr(light_svc, "_get_client", lambda _pid: client)
  806. async def _settings():
  807. return client.mode, 0.0
  808. monkeypatch.setattr(light_svc, "_read_settings", _settings)
  809. monkeypatch.setattr(light_svc, "_settings_cache", None)
  810. monkeypatch.setattr(light_svc, "_holders", {})
  811. monkeypatch.setattr(light_svc, "_lit_at", {})
  812. off_tasks: dict = {}
  813. monkeypatch.setattr(light_svc, "_off_tasks", off_tasks)
  814. yield client
  815. for task in off_tasks.values():
  816. task.cancel()
  817. async def test_finish_photo_live_grab_is_lit_when_the_light_mode_covers_it(patched_env, monkeypatch, light_client):
  818. light_client.mode = "all"
  819. seen = {}
  820. async def _live(**_kwargs):
  821. seen["light"] = light_client.state.chamber_light
  822. return b"\xff\xd8live"
  823. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  824. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  825. assert seen["light"] is True
  826. assert light_client.calls == [True] # off follows after the grace
  827. async def test_finish_photo_live_grab_leaves_the_light_alone_by_default(patched_env, monkeypatch, light_client):
  828. async def _live(**_kwargs):
  829. return b"\xff\xd8live"
  830. monkeypatch.setattr("backend.app.services.camera.capture_camera_frame_bytes", _live)
  831. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  832. assert light_client.calls == []
  833. async def test_finish_photo_from_the_bank_does_not_turn_the_light_on(patched_env, monkeypatch, light_client):
  834. """The banked frame is already taken; lighting the printer for it would
  835. only switch the light on and off for nothing."""
  836. light_client.mode = "all"
  837. print_dispatch_context.mark_pending(patched_env.id)
  838. print_dispatch_context.adopt(patched_env.id)
  839. main_module._inprint_frame_bank[patched_env.id] = b"\xff\xd8banked"
  840. await on_finish_photo_moment(patched_env.id, {"trigger": "finish_state"})
  841. assert main_module._stage22_finish_frames[patched_env.id] == b"\xff\xd8banked"
  842. assert light_client.calls == []
  843. async def test_notification_snapshot_is_lit_for_a_selected_printer(fake_printer, monkeypatch, light_client):
  844. light_client.mode = "selected"
  845. fake_printer.camera_light_auto = True
  846. seen = {}
  847. async def _frame(_pid, _printer, _logger):
  848. seen["light"] = light_client.state.chamber_light
  849. return b"\xff\xd8snap"
  850. monkeypatch.setattr(main_module, "_capture_snapshot_frame", _frame)
  851. assert await main_module._capture_snapshot_for_notification(7, fake_printer, logging.getLogger()) == b"\xff\xd8snap"
  852. assert seen["light"] is True
  853. assert light_client.calls == [True]
  854. def test_every_live_capture_in_main_holds_the_light():
  855. """#1655: the finish photo's last fallback lives in `_background_finish_photo`,
  856. a closure nothing can drive directly (see the rotation guard above). So the
  857. source is checked: every live camera grab in main.py runs inside
  858. `camera_light(...)`, except in `_capture_snapshot_frame`, whose only caller
  859. is the wrapper that holds the light for it.
  860. """
  861. import ast
  862. from pathlib import Path
  863. main_py = Path(__file__).resolve().parents[2] / "app" / "main.py"
  864. tree = ast.parse(main_py.read_text())
  865. parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}
  866. grabs = {"capture_frame", "capture_camera_frame", "capture_camera_frame_bytes", "capture_finish_photo"}
  867. def _held(node) -> bool:
  868. while node in parents:
  869. node = parents[node]
  870. if isinstance(node, ast.AsyncFunctionDef) and node.name == "_capture_snapshot_frame":
  871. return True
  872. if isinstance(node, ast.AsyncWith) and any(
  873. isinstance(item.context_expr, ast.Call)
  874. and getattr(item.context_expr.func, "id", None) == "camera_light"
  875. for item in node.items
  876. ):
  877. return True
  878. return False
  879. calls = [
  880. node
  881. for node in ast.walk(tree)
  882. if isinstance(node, ast.Call) and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) in grabs
  883. ]
  884. assert len(calls) >= 6, "guard found fewer grabs than main.py has; is it parsing the right file?"
  885. unlit = [node.lineno for node in calls if not _held(node)]
  886. assert not unlit, f"main.py:{unlit} grabs a camera frame without camera_light(...)"
  887. wrapper_callers = [
  888. node.lineno
  889. for node in ast.walk(tree)
  890. if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "_capture_snapshot_frame"
  891. ]
  892. assert len(wrapper_callers) == 1, f"_capture_snapshot_frame is called from main.py:{wrapper_callers}"