slice_output_check.py 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Sanity-check a sliced file before Bambuddy is willing to print it.
  2. A Bambu printer's start G-code is where the AMS load (``M620``) and the
  3. preparation-stage announcements (``M1002 gcode_claim_action``) live. Slice
  4. without it and the job still dispatches, still heats the bed and still moves
  5. the toolhead — it simply extrudes nothing, reports no stage, and sits at layer
  6. 0 until someone notices (#2838).
  7. Nothing downstream can tell that apart from a print that has not started yet,
  8. so the only place to catch it is here, on the bytes the slicer just produced.
  9. All 56 instantiable presets in the shipped Bambu bundle carry
  10. ``gcode_claim_action``, which makes its absence a reliable signal rather than
  11. a heuristic.
  12. """
  13. from __future__ import annotations
  14. import io
  15. import json
  16. import logging
  17. import zipfile
  18. logger = logging.getLogger(__name__)
  19. # Present in the start G-code of every instantiable machine preset in the
  20. # bundle. `M620` is equally universal today, but this one is the marker whose
  21. # absence the reporter could see from the printer's side: no claim actions
  22. # means `stg_cur` stays -1 and the UI never names a preparation step.
  23. _START_GCODE_MARKER = "gcode_claim_action"
  24. _PROJECT_SETTINGS = "Metadata/project_settings.config"
  25. # The start block sits after the file header and the embedded thumbnails, well
  26. # inside this. Bounded so a pathological output cannot turn the check into a
  27. # multi-hundred-megabyte read.
  28. _GCODE_SCAN_BYTES = 4 * 1024 * 1024
  29. def _as_text(value: object) -> str:
  30. """Slicer config values arrive as a bare string or a one-element list."""
  31. if isinstance(value, list):
  32. return "".join(str(v) for v in value)
  33. return "" if value is None else str(value)
  34. def start_gcode_is_missing(content: bytes, *, export_3mf: bool) -> bool:
  35. """Whether ``content`` was sliced without the printer's start G-code.
  36. Answers False whenever the question cannot be settled — an unreadable
  37. archive, a missing config, a decode failure. A slice that is merely
  38. unusual must not be blocked by a check that only knows how to recognise
  39. one specific defect; the caller has no better information than we do.
  40. """
  41. if not content:
  42. return False
  43. if not export_3mf:
  44. head = content[:_GCODE_SCAN_BYTES].decode("utf-8", errors="ignore")
  45. return bool(head) and _START_GCODE_MARKER not in head
  46. try:
  47. with zipfile.ZipFile(io.BytesIO(content)) as archive:
  48. raw = archive.read(_PROJECT_SETTINGS)
  49. except (KeyError, OSError, zipfile.BadZipFile) as exc:
  50. logger.debug("Slice output check skipped: cannot read %s (%s)", _PROJECT_SETTINGS, exc)
  51. return False
  52. try:
  53. settings = json.loads(raw)
  54. except (UnicodeDecodeError, json.JSONDecodeError) as exc:
  55. logger.debug("Slice output check skipped: %s is not valid JSON (%s)", _PROJECT_SETTINGS, exc)
  56. return False
  57. if not isinstance(settings, dict) or "machine_start_gcode" not in settings:
  58. logger.debug("Slice output check skipped: no machine_start_gcode in %s", _PROJECT_SETTINGS)
  59. return False
  60. return _START_GCODE_MARKER not in _as_text(settings["machine_start_gcode"])
  61. def missing_start_gcode_message(printer_preset_name: str) -> str:
  62. """The 502 body for a slice that came back without its start G-code.
  63. Names the sidecar because that is where the fix is: Bambuddy sends the
  64. bundled preset by name and the sidecar resolves it, so an older image
  65. resolves it to a generic 577-character stub and no amount of retrying in
  66. Bambuddy will change the result.
  67. """
  68. return (
  69. f"The slicer returned a file with no printer start G-code for '{printer_preset_name}'. "
  70. "Printing it would heat the printer and extrude nothing, so it was not saved. "
  71. "This is fixed by updating the slicer sidecar image: older ones cannot read the "
  72. "companion profile that holds the real start G-code for most Bambu printers. "
  73. "Update the sidecar and slice again."
  74. )