bambu-autoeject 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bambu-autoeject contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: bambu-autoeject
3
+ Version: 0.1.0
4
+ Summary: Chain prints on a Bambu Lab A1 and push each finished part off the bed, no extra hardware
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/bullsrobo-boop/bambu-autoeject
7
+ Project-URL: Issues, https://github.com/bullsrobo-boop/bambu-autoeject/issues
8
+ Keywords: 3d-printing,bambu-lab,a1,gcode,print-farm,auto-eject
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Manufacturing
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Printing
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # bambu-autoeject
21
+
22
+ [![test](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml/badge.svg)](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml)
23
+
24
+ Print a queue of parts on a **Bambu Lab A1** without standing next to it. No extra hardware, no firmware changes.
25
+
26
+ The tool joins several sliced plates into one job. After each print the printer:
27
+
28
+ 1. turns off the bed and nozzle and waits for the bed to cool (12 minutes by default, fan on);
29
+ 2. lowers the nozzle to 1 mm behind the parts and pushes them forward, in lanes 6 mm apart, until they fall off the front of the bed;
30
+ 3. re-homes and starts the next print.
31
+
32
+ > **Status: alpha, not yet tested on a real printer.** The G-code is generated and covered by tests, but the eject moves have not been run on hardware. Do the dry run first and stay next to the printer for the first real runs. Test reports are the most useful contribution right now: [open a printer test report](https://github.com/bullsrobo-boop/bambu-autoeject/issues/new?template=printer-test.yml).
33
+
34
+ ## Supported printers
35
+
36
+ | Printer | Status |
37
+ | --- | --- |
38
+ | Bambu Lab A1 | main target, values from the stock profile |
39
+ | Bambu Lab A1 mini | experimental, values from the stock profile, `--clean-front` not available |
40
+ | P1, X1, H2D | not supported (closed front or no bed slinger) |
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install bambu-autoeject
46
+ ```
47
+
48
+ Python 3.9 or newer, no other dependencies. Without installing you can also run `python3 autoeject.py ...` from a clone of this repository.
49
+
50
+ ## Usage
51
+
52
+ ### Join several plates
53
+
54
+ 1. Slice each model in Bambu Studio and export it with **File > Export > Export plate sliced file** (`.gcode.3mf`, one plate per file).
55
+ 2. Run:
56
+
57
+ ```bash
58
+ bambu-autoeject queue.gcode.3mf bracket.gcode.3mf:3 keychain.gcode.3mf:2
59
+ ```
60
+
61
+ `:3` means three copies in a row. Open `queue.gcode.3mf` in Bambu Studio and send it to the printer like any sliced file.
62
+
63
+ ### From inside Bambu Studio (experimental)
64
+
65
+ Bambu Studio can run a post-processing script on every slice. In the process settings (Advanced mode), **Others > Post-processing Scripts**, add:
66
+
67
+ ```
68
+ bambu-autoeject --in-place --copies 3;
69
+ ```
70
+
71
+ Bambu Studio adds the G-code path at the end. Every slice is then printed 3 times with an eject after each. Use the full path to `bambu-autoeject` if Bambu Studio cannot find it (`which bambu-autoeject` on macOS and Linux, `where bambu-autoeject` on Windows). This mode has only been tested on exported files so far, not on jobs sent from Bambu Studio over the network.
72
+
73
+ ### Options
74
+
75
+ | Option | Default | What it does |
76
+ | --- | --- | --- |
77
+ | `--cool-min N` | 12 | minutes of cooling before the push |
78
+ | `--push-z MM` | 1.0 | nozzle height while pushing (not below 0.5) |
79
+ | `--lane MM` | 6 | spacing between push lanes (use 4 for very narrow parts) |
80
+ | `--behind MM` | 8 | how far behind the parts the nozzle comes down |
81
+ | `--keep-last` | off | leave the last print on the bed |
82
+ | `--dry-run` | off | do all the moves above the part, never touching it |
83
+ | `--clean-front` | off | A1 only: also push off the front calibration line (nozzle at 0.3 mm, may scratch) |
84
+ | `--copies N` | 1 | with `--in-place`: repeat the plate N times |
85
+
86
+ Full list: `bambu-autoeject --help`.
87
+
88
+ ## Safety
89
+
90
+ - The nozzle never goes below the `--push-z` height (1 mm by default) unless you use `--clean-front`.
91
+ - Motor current is lowered during the push, so a stuck part makes the motor skip instead of forcing it. The printer re-homes afterwards.
92
+ - The start G-code draws a calibration line on the front edge. The nozzle cannot reach it safely, so the first line stays on the bed and later prints skip drawing it again.
93
+ - Plates sliced for different printers cannot be mixed in one job.
94
+
95
+ ## What works and what does not
96
+
97
+ - Best on the **textured PEI plate** with PLA or PETG: parts release by themselves once the bed is cold.
98
+ - Very small parts (base under about 15 x 15 mm) or large flat bases may not release.
99
+ - Tall, thin parts can tip over: print them lying down or with a brim.
100
+ - Leave 8 mm free between the parts and the back edge of the bed.
101
+ - Put a box or a ramp in front of the printer to catch the parts.
102
+
103
+ ## First test
104
+
105
+ `examples/a1/` contains a 20 mm cube sliced for the A1 (textured PEI plate, Bambu PLA Basic):
106
+
107
+ 1. `1_dry_run.gcode.3mf`: prints the cube, waits 12 minutes, then does all the eject moves **above** it. Check that the path looks right.
108
+ 2. `2_eject_one_cube.gcode.3mf`: same cube, this time pushed off. Keep a hand near the stop button.
109
+ 3. `3_two_cubes.gcode.3mf`: two cubes in a row with an eject after each, the full loop.
110
+
111
+ `examples/a1-mini/` has the dry run and the two-cube job for the A1 mini.
112
+
113
+ If the printer does not wait the 12 minutes in step 1, the firmware is ignoring `M400 S60`; please report it.
114
+
115
+ ## How it works
116
+
117
+ Bambu Studio writes the whole job as plain G-code inside the `.gcode.3mf` archive. The tool reads the first layer to find where the parts are, inserts an eject block before the end sequence turns off the motors, removes the duplicate header and calibration line from the following jobs and writes the joined G-code back into a copy of the first archive, so thumbnails and settings stay intact.
118
+
119
+ ## Contributing
120
+
121
+ See [CONTRIBUTING.md](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/CONTRIBUTING.md). Run the tests with `python3 -m unittest`.
122
+
123
+ ## License
124
+
125
+ MIT, see [LICENSE](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/LICENSE). Use at your own risk: this changes how your printer moves.
@@ -0,0 +1,106 @@
1
+ # bambu-autoeject
2
+
3
+ [![test](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml/badge.svg)](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml)
4
+
5
+ Print a queue of parts on a **Bambu Lab A1** without standing next to it. No extra hardware, no firmware changes.
6
+
7
+ The tool joins several sliced plates into one job. After each print the printer:
8
+
9
+ 1. turns off the bed and nozzle and waits for the bed to cool (12 minutes by default, fan on);
10
+ 2. lowers the nozzle to 1 mm behind the parts and pushes them forward, in lanes 6 mm apart, until they fall off the front of the bed;
11
+ 3. re-homes and starts the next print.
12
+
13
+ > **Status: alpha, not yet tested on a real printer.** The G-code is generated and covered by tests, but the eject moves have not been run on hardware. Do the dry run first and stay next to the printer for the first real runs. Test reports are the most useful contribution right now: [open a printer test report](https://github.com/bullsrobo-boop/bambu-autoeject/issues/new?template=printer-test.yml).
14
+
15
+ ## Supported printers
16
+
17
+ | Printer | Status |
18
+ | --- | --- |
19
+ | Bambu Lab A1 | main target, values from the stock profile |
20
+ | Bambu Lab A1 mini | experimental, values from the stock profile, `--clean-front` not available |
21
+ | P1, X1, H2D | not supported (closed front or no bed slinger) |
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install bambu-autoeject
27
+ ```
28
+
29
+ Python 3.9 or newer, no other dependencies. Without installing you can also run `python3 autoeject.py ...` from a clone of this repository.
30
+
31
+ ## Usage
32
+
33
+ ### Join several plates
34
+
35
+ 1. Slice each model in Bambu Studio and export it with **File > Export > Export plate sliced file** (`.gcode.3mf`, one plate per file).
36
+ 2. Run:
37
+
38
+ ```bash
39
+ bambu-autoeject queue.gcode.3mf bracket.gcode.3mf:3 keychain.gcode.3mf:2
40
+ ```
41
+
42
+ `:3` means three copies in a row. Open `queue.gcode.3mf` in Bambu Studio and send it to the printer like any sliced file.
43
+
44
+ ### From inside Bambu Studio (experimental)
45
+
46
+ Bambu Studio can run a post-processing script on every slice. In the process settings (Advanced mode), **Others > Post-processing Scripts**, add:
47
+
48
+ ```
49
+ bambu-autoeject --in-place --copies 3;
50
+ ```
51
+
52
+ Bambu Studio adds the G-code path at the end. Every slice is then printed 3 times with an eject after each. Use the full path to `bambu-autoeject` if Bambu Studio cannot find it (`which bambu-autoeject` on macOS and Linux, `where bambu-autoeject` on Windows). This mode has only been tested on exported files so far, not on jobs sent from Bambu Studio over the network.
53
+
54
+ ### Options
55
+
56
+ | Option | Default | What it does |
57
+ | --- | --- | --- |
58
+ | `--cool-min N` | 12 | minutes of cooling before the push |
59
+ | `--push-z MM` | 1.0 | nozzle height while pushing (not below 0.5) |
60
+ | `--lane MM` | 6 | spacing between push lanes (use 4 for very narrow parts) |
61
+ | `--behind MM` | 8 | how far behind the parts the nozzle comes down |
62
+ | `--keep-last` | off | leave the last print on the bed |
63
+ | `--dry-run` | off | do all the moves above the part, never touching it |
64
+ | `--clean-front` | off | A1 only: also push off the front calibration line (nozzle at 0.3 mm, may scratch) |
65
+ | `--copies N` | 1 | with `--in-place`: repeat the plate N times |
66
+
67
+ Full list: `bambu-autoeject --help`.
68
+
69
+ ## Safety
70
+
71
+ - The nozzle never goes below the `--push-z` height (1 mm by default) unless you use `--clean-front`.
72
+ - Motor current is lowered during the push, so a stuck part makes the motor skip instead of forcing it. The printer re-homes afterwards.
73
+ - The start G-code draws a calibration line on the front edge. The nozzle cannot reach it safely, so the first line stays on the bed and later prints skip drawing it again.
74
+ - Plates sliced for different printers cannot be mixed in one job.
75
+
76
+ ## What works and what does not
77
+
78
+ - Best on the **textured PEI plate** with PLA or PETG: parts release by themselves once the bed is cold.
79
+ - Very small parts (base under about 15 x 15 mm) or large flat bases may not release.
80
+ - Tall, thin parts can tip over: print them lying down or with a brim.
81
+ - Leave 8 mm free between the parts and the back edge of the bed.
82
+ - Put a box or a ramp in front of the printer to catch the parts.
83
+
84
+ ## First test
85
+
86
+ `examples/a1/` contains a 20 mm cube sliced for the A1 (textured PEI plate, Bambu PLA Basic):
87
+
88
+ 1. `1_dry_run.gcode.3mf`: prints the cube, waits 12 minutes, then does all the eject moves **above** it. Check that the path looks right.
89
+ 2. `2_eject_one_cube.gcode.3mf`: same cube, this time pushed off. Keep a hand near the stop button.
90
+ 3. `3_two_cubes.gcode.3mf`: two cubes in a row with an eject after each, the full loop.
91
+
92
+ `examples/a1-mini/` has the dry run and the two-cube job for the A1 mini.
93
+
94
+ If the printer does not wait the 12 minutes in step 1, the firmware is ignoring `M400 S60`; please report it.
95
+
96
+ ## How it works
97
+
98
+ Bambu Studio writes the whole job as plain G-code inside the `.gcode.3mf` archive. The tool reads the first layer to find where the parts are, inserts an eject block before the end sequence turns off the motors, removes the duplicate header and calibration line from the following jobs and writes the joined G-code back into a copy of the first archive, so thumbnails and settings stay intact.
99
+
100
+ ## Contributing
101
+
102
+ See [CONTRIBUTING.md](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/CONTRIBUTING.md). Run the tests with `python3 -m unittest`.
103
+
104
+ ## License
105
+
106
+ MIT, see [LICENSE](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/LICENSE). Use at your own risk: this changes how your printer moves.
@@ -0,0 +1,3 @@
1
+ """Chain prints on a Bambu Lab A1 and push each part off the bed."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,89 @@
1
+ """Command line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .core import AutoEjectError, Options, join_files, process_in_place
10
+
11
+ USAGE_EXAMPLES = """\
12
+ examples:
13
+ bambu-autoeject queue.gcode.3mf bracket.gcode.3mf:3 keychain.gcode.3mf:2
14
+ bambu-autoeject test.gcode.3mf cube.gcode.3mf --dry-run
15
+ bambu-autoeject --in-place --copies 3 plate.gcode (Bambu Studio post-processing)
16
+ """
17
+
18
+
19
+ def build_parser() -> argparse.ArgumentParser:
20
+ ap = argparse.ArgumentParser(
21
+ prog="bambu-autoeject",
22
+ description="Chain prints on a Bambu Lab A1 and push each finished part off the bed.",
23
+ epilog=USAGE_EXAMPLES,
24
+ formatter_class=argparse.RawDescriptionHelpFormatter,
25
+ )
26
+ ap.add_argument("files", nargs="+", metavar="FILE",
27
+ help="OUTPUT.gcode.3mf INPUT.gcode.3mf[:count] ..., or one .gcode file with --in-place")
28
+ ap.add_argument("--in-place", action="store_true",
29
+ help="rewrite a single plain .gcode file (for the slicer's post-processing scripts)")
30
+ ap.add_argument("--copies", type=int, default=1, help="with --in-place: print the plate N times (1)")
31
+ ap.add_argument("--cool-min", type=int, default=12, help="minutes of cooling before ejecting (12)")
32
+ ap.add_argument("--cool-temp", type=int, default=28, help="target temperature for --wait-bed (28)")
33
+ ap.add_argument("--wait-bed", action="store_true", help="also add M190 (may hang if the room is warm)")
34
+ ap.add_argument("--push-z", type=float, default=1.0, help="nozzle height while pushing, mm (1.0)")
35
+ ap.add_argument("--push-speed", type=int, default=25, help="push speed, mm/s (25)")
36
+ ap.add_argument("--lane", type=float, default=6.0, help="spacing between push lanes, mm (6)")
37
+ ap.add_argument("--behind", type=float, default=8.0, help="how far behind the parts the nozzle drops, mm (8)")
38
+ ap.add_argument("--clean-front", action="store_true",
39
+ help="A1 only: also push off the front calibration lines (nozzle very low, may scratch)")
40
+ ap.add_argument("--front-z", type=float, default=0.3, help="nozzle height for --clean-front, mm (0.3)")
41
+ ap.add_argument("--keep-cali-line", action="store_true",
42
+ help="keep the front calibration line on prints after the first")
43
+ ap.add_argument("--keep-last", action="store_true", help="leave the last print on the bed")
44
+ ap.add_argument("--dry-run", action="store_true", help="do the moves above the parts without touching them")
45
+ ap.add_argument("--force", action="store_true", help="accept other printers as if they were an A1 (at your own risk)")
46
+ ap.add_argument("--version", action="version", version="%(prog)s " + __version__)
47
+ return ap
48
+
49
+
50
+ def check_options(args) -> Options:
51
+ if args.push_z < 0.5 and not args.dry_run:
52
+ raise AutoEjectError("--push-z below 0.5 mm risks the plate")
53
+ if args.lane <= 0 or args.behind <= 0 or args.push_speed <= 0 or args.cool_min < 0:
54
+ raise AutoEjectError("--lane, --behind and --push-speed must be positive, --cool-min not negative")
55
+ return Options(
56
+ cool_min=args.cool_min, cool_temp=args.cool_temp, wait_bed=args.wait_bed,
57
+ push_z=args.push_z, push_speed=args.push_speed, lane=args.lane, behind=args.behind,
58
+ clean_front=args.clean_front, front_z=args.front_z, keep_cali_line=args.keep_cali_line,
59
+ keep_last=args.keep_last, dry_run=args.dry_run, force=args.force,
60
+ )
61
+
62
+
63
+ def main(argv=None) -> int:
64
+ args = build_parser().parse_args(argv)
65
+ try:
66
+ opts = check_options(args)
67
+ if args.in_place:
68
+ if len(args.files) != 1:
69
+ raise AutoEjectError("--in-place takes exactly one .gcode file")
70
+ count, printer = process_in_place(args.files[0], args.copies, opts, log=print)
71
+ target = args.files[0]
72
+ else:
73
+ if len(args.files) < 2:
74
+ raise AutoEjectError("give the output file and at least one input file")
75
+ if args.copies != 1:
76
+ raise AutoEjectError("--copies is for --in-place; use file.gcode.3mf:N instead")
77
+ count, printer = join_files(args.files[0], args.files[1:], opts, log=print)
78
+ target = args.files[0]
79
+ except (AutoEjectError, OSError, ValueError) as e:
80
+ print("bambu-autoeject: error: %s" % e, file=sys.stderr)
81
+ sys.exit(1)
82
+ note = " (support for this printer is experimental)" if printer.experimental else ""
83
+ print("wrote %s: %d prints, %s%s" % (target, count,
84
+ "NO contact (dry-run)" if args.dry_run else "with eject", note))
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,326 @@
1
+ """G-code handling: find the parts, build the eject block, join the jobs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import zipfile
9
+ from typing import List, NamedTuple, Optional, Tuple
10
+
11
+
12
+ class AutoEjectError(Exception):
13
+ """Input the script cannot handle safely."""
14
+
15
+
16
+ class Printer(NamedTuple):
17
+ model: str
18
+ model_id: str
19
+ bed: Tuple[float, float]
20
+ max_z: float
21
+ currents: str # default motor currents from the stock start G-code
22
+ eject_currents: str # lower currents while pushing
23
+ park: Tuple[float, float]
24
+ front_line_x: Optional[Tuple[float, float]] # calibration line, None if --clean-front is not supported
25
+ experimental: bool
26
+
27
+
28
+ PRINTERS = {
29
+ "Bambu Lab A1": Printer(
30
+ model="Bambu Lab A1",
31
+ model_id="N2S",
32
+ bed=(256.0, 256.0),
33
+ max_z=256.0,
34
+ currents="M17 X0.65 Y1.2 Z0.6",
35
+ eject_currents="M17 X0.5 Y0.7",
36
+ park=(-48.0, 180.0),
37
+ front_line_x=(104.0, 160.0),
38
+ experimental=False,
39
+ ),
40
+ "Bambu Lab A1 mini": Printer(
41
+ model="Bambu Lab A1 mini",
42
+ model_id="N1",
43
+ bed=(180.0, 180.0),
44
+ max_z=180.0,
45
+ currents="M17 X0.7 Y0.9 Z0.5",
46
+ eject_currents="M17 X0.55 Y0.5",
47
+ park=(-13.0, 180.0),
48
+ front_line_x=None,
49
+ experimental=True,
50
+ ),
51
+ }
52
+
53
+ Y_FRONT = -0.5 # front edge, same as the A1 start G-code
54
+ FRONT_LINE_FROM_Y = 8.0
55
+ CALI_START = ";===== extrude cali test"
56
+ CALI_END = ";========turn off light"
57
+ EXEC_START = "; EXECUTABLE_BLOCK_START"
58
+
59
+
60
+ class Options(NamedTuple):
61
+ cool_min: int = 12
62
+ cool_temp: int = 28
63
+ wait_bed: bool = False
64
+ push_z: float = 1.0
65
+ push_speed: int = 25
66
+ lane: float = 6.0
67
+ behind: float = 8.0
68
+ clean_front: bool = False
69
+ front_z: float = 0.3
70
+ keep_cali_line: bool = False
71
+ keep_last: bool = False
72
+ dry_run: bool = False
73
+ force: bool = False
74
+
75
+
76
+ def config_value(gcode: str, key: str) -> Optional[str]:
77
+ m = re.search(r"^; %s = (.*)$" % re.escape(key), gcode, re.M)
78
+ return m.group(1).strip() if m else None
79
+
80
+
81
+ def detect_printer(gcode: str, force: bool = False) -> Printer:
82
+ model = config_value(gcode, "printer_model")
83
+ if model in PRINTERS:
84
+ return PRINTERS[model]
85
+ if force:
86
+ return PRINTERS["Bambu Lab A1"]
87
+ raise AutoEjectError("sliced for '%s'; supported: %s (use --force at your own risk)"
88
+ % (model, ", ".join(PRINTERS)))
89
+
90
+
91
+ def first_layer_bbox(gcode: str) -> Tuple[float, float, float, float]:
92
+ """Area printed on the first layer: (xmin, ymin, xmax, ymax)."""
93
+ start = gcode.find("; MACHINE_START_GCODE_END")
94
+ if start < 0:
95
+ raise AutoEjectError("not a Bambu Studio G-code (no MACHINE_START_GCODE_END)")
96
+ layers = [m.start() for m in re.finditer(r"^; CHANGE_LAYER", gcode[start:], re.M)]
97
+ if len(layers) < 2:
98
+ raise AutoEjectError("cannot find layers in the G-code")
99
+ body = gcode[start + layers[0]: start + layers[1]]
100
+ x = y = None
101
+ xs, ys = [], []
102
+ for line in body.splitlines():
103
+ if not line.startswith(("G1 ", "G0 ", "G2 ", "G3 ")):
104
+ continue
105
+ mx = re.search(r"X(-?[\d.]+)", line)
106
+ my = re.search(r"Y(-?[\d.]+)", line)
107
+ me = re.search(r"E(-?[\d.]+)", line)
108
+ if mx:
109
+ x = float(mx.group(1))
110
+ if my:
111
+ y = float(my.group(1))
112
+ if me and float(me.group(1)) > 0 and x is not None and y is not None:
113
+ xs.append(x)
114
+ ys.append(y)
115
+ if not xs:
116
+ raise AutoEjectError("first layer has no extrusion")
117
+ return min(xs), min(ys), max(xs), max(ys)
118
+
119
+
120
+ def max_height(gcode: str) -> float:
121
+ m = re.search(r"^; max_z_height: ([\d.]+)", gcode, re.M)
122
+ return float(m.group(1)) if m else 100.0
123
+
124
+
125
+ def eject_block(printer: Printer, bbox, height: float, opts: Options) -> str:
126
+ xmin, ymin, xmax, ymax = bbox
127
+ bed_x, bed_y = printer.bed
128
+ z_safe = min(height + 8.0, printer.max_z - 6.0)
129
+ z_push = z_safe if opts.dry_run else opts.push_z
130
+ y_back = min(ymax + opts.behind, bed_y)
131
+
132
+ # push lanes across the full width, closer together than the narrowest part
133
+ lanes = []
134
+ x = max(xmin + 1.0, 0.0)
135
+ while x < xmax - 1.0:
136
+ lanes.append(round(x, 2))
137
+ x += opts.lane
138
+ lanes.append(round(min(max(xmax - 1.0, xmin + 1.0), bed_x), 2))
139
+
140
+ out = [
141
+ "; ===== AUTO-EJECT START (bambu-autoeject) =====",
142
+ "M400",
143
+ "M140 S0 ; bed off",
144
+ "M104 S0 ; nozzle off",
145
+ "G90",
146
+ "G1 Z%.2f F600 ; above the parts" % z_safe,
147
+ "G1 X%d Y%d F6000" % (bed_x / 2, bed_y / 2),
148
+ "M106 S255 ; fan helps cooling",
149
+ ]
150
+ if opts.wait_bed:
151
+ out.append("M190 S%d ; wait for cold bed (if firmware supports it)" % opts.cool_temp)
152
+ # fixed pause: waiting on bed temperature is not reliable on Bambu firmware
153
+ for i in range(opts.cool_min):
154
+ out.append("M400 S60 ; cooling %d/%d min" % (i + 1, opts.cool_min))
155
+ out += [
156
+ "M106 S0",
157
+ printer.eject_currents + " ; lower current: if the part is stuck the motor skips instead of breaking something",
158
+ ]
159
+ for x in lanes:
160
+ out += [
161
+ "G1 Z%.2f F1200" % z_safe,
162
+ "G1 X%.2f Y%.2f F6000" % (x, y_back),
163
+ "G1 Z%.2f F600" % z_push,
164
+ "G1 Y%.2f F%d ; push to the front" % (Y_FRONT, opts.push_speed * 60),
165
+ ]
166
+ if opts.clean_front:
167
+ # calibration lines drawn by the start G-code on the front edge
168
+ z_front = z_safe if opts.dry_run else opts.front_z
169
+ out.append("G1 Z%.2f F1200" % z_safe)
170
+ x, x_end = printer.front_line_x
171
+ while x <= x_end:
172
+ out += [
173
+ "G1 Z3 F1200",
174
+ "G1 X%.1f Y%.1f F6000" % (x, FRONT_LINE_FROM_Y),
175
+ "G1 Z%.2f F600" % z_front,
176
+ "G1 Y%.2f F1500 ; calibration line off the bed" % Y_FRONT,
177
+ ]
178
+ x += 4.0
179
+ out += [
180
+ "G1 Z%.2f F1200" % z_safe,
181
+ printer.currents + " ; normal currents",
182
+ "G28 X ; re-home XY like the Bambu start, in case steps were skipped",
183
+ "G1 X%.1f Y%.1f F6000" % printer.park,
184
+ "M400",
185
+ "; ===== AUTO-EJECT END =====",
186
+ ]
187
+ return "\n".join(out) + "\n"
188
+
189
+
190
+ def insert_eject(gcode: str, block: str) -> str:
191
+ """Insert the eject block before the motors are disabled in the Bambu end G-code."""
192
+ idx = gcode.rfind("\nM18 X Y Z")
193
+ if idx < 0:
194
+ raise AutoEjectError("cannot find the end sequence (M18 X Y Z) in the G-code")
195
+ return gcode[: idx + 1] + block + gcode[idx + 1:]
196
+
197
+
198
+ def strip_cali_line(gcode: str) -> str:
199
+ """Remove the front calibration line from every print after the first.
200
+
201
+ The start G-code always draws it in the same place at 0.3 mm. The nozzle cannot go
202
+ that low there without risking the plate (the front edge is not probed by bed
203
+ leveling), so the first line stays and later ones are skipped.
204
+ """
205
+ base = max(gcode.find(EXEC_START), 0)
206
+ start = gcode.find(CALI_START, base)
207
+ end = gcode.find(CALI_END, start)
208
+ if start < 0 or end < 0:
209
+ raise AutoEjectError("cannot find the calibration line in the start G-code (Bambu profile changed?)")
210
+ return gcode[:start] + "; calibration line removed by bambu-autoeject (already on the bed)\n" + gcode[end:]
211
+
212
+
213
+ def strip_header(gcode: str) -> str:
214
+ """For jobs after the first keep only the executable part."""
215
+ i = gcode.find(EXEC_START)
216
+ return gcode[i:] if i >= 0 else gcode
217
+
218
+
219
+ def parse_jobs(specs: List[str]) -> List[str]:
220
+ """'part.gcode.3mf:3' -> three entries."""
221
+ jobs = []
222
+ for spec in specs:
223
+ path, _, count = spec.rpartition(":")
224
+ if not path or not count.isdigit():
225
+ path, count = spec, "1"
226
+ if int(count) < 1:
227
+ raise AutoEjectError("%s: count must be at least 1" % spec)
228
+ jobs += [path] * int(count)
229
+ return jobs
230
+
231
+
232
+ def build_job(plates: List[Tuple[str, str]], opts: Options, log=None) -> Tuple[str, Printer]:
233
+ """Join (label, gcode) plates into one G-code with an eject after each."""
234
+ if not plates:
235
+ raise AutoEjectError("nothing to print")
236
+ if opts.dry_run and len(plates) > 1:
237
+ raise AutoEjectError("--dry-run leaves the part on the bed, so it only works with a single print")
238
+ printer = None
239
+ parts = []
240
+ total_layers = 0
241
+ for n, (label, gcode) in enumerate(plates):
242
+ this = detect_printer(gcode, opts.force)
243
+ if printer is None:
244
+ printer = this
245
+ elif this != printer:
246
+ raise AutoEjectError("%s: sliced for %s, the first plate is for %s" % (label, this.model, printer.model))
247
+ if opts.clean_front and printer.front_line_x is None:
248
+ raise AutoEjectError("--clean-front is not supported on the %s" % printer.model)
249
+ bbox = first_layer_bbox(gcode)
250
+ height = max_height(gcode)
251
+ if bbox[3] + opts.behind > printer.bed[1] + 0.01:
252
+ raise AutoEjectError("%s: part is too far back (y max %.0f); move it forward on the plate."
253
+ % (label, bbox[3]))
254
+ last = n == len(plates) - 1
255
+ if not (last and opts.keep_last):
256
+ gcode = insert_eject(gcode, eject_block(printer, bbox, height, opts))
257
+ if n:
258
+ gcode = strip_header(gcode)
259
+ if not opts.keep_cali_line:
260
+ gcode = strip_cali_line(gcode)
261
+ parts.append("; ===== JOB %d/%d: %s =====\n" % (n + 1, len(plates), label) + gcode)
262
+ m = re.search(r"^; total layer number: (\d+)", gcode, re.M)
263
+ total_layers += int(m.group(1)) if m else 0
264
+ if log:
265
+ log("job %d: %s, parts at X %.0f-%.0f, Y %.0f-%.0f, height %.0f mm"
266
+ % (n + 1, label, bbox[0], bbox[2], bbox[1], bbox[3], height))
267
+
268
+ combined = "\n".join(parts)
269
+ combined = re.sub(r"^; total layer number: \d+", "; total layer number: %d" % total_layers,
270
+ combined, count=1, flags=re.M)
271
+ return combined, printer
272
+
273
+
274
+ def read_plate(path: str) -> Tuple[str, str]:
275
+ """Return (G-code name inside the .gcode.3mf archive, G-code text)."""
276
+ with zipfile.ZipFile(path) as z:
277
+ names = [n for n in z.namelist() if re.fullmatch(r"Metadata/plate_\d+\.gcode", n)]
278
+ if not names:
279
+ raise AutoEjectError("%s: no G-code inside. Use 'Export plate sliced file', not the project." % path)
280
+ if len(names) > 1:
281
+ raise AutoEjectError("%s: has %d plates; export one plate per file." % (path, len(names)))
282
+ return names[0], z.read(names[0]).decode("utf-8")
283
+
284
+
285
+ def write_3mf(template: str, output: str, gcode: str, printer: Printer) -> None:
286
+ """Copy the template archive (thumbnails, settings) and replace only the G-code."""
287
+ gname, _ = read_plate(template)
288
+ data = gcode.encode("utf-8")
289
+ md5 = hashlib.md5(data).hexdigest().upper()
290
+ with zipfile.ZipFile(template) as src, zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as dst:
291
+ for item in src.infolist():
292
+ if item.filename == gname:
293
+ dst.writestr(item, data)
294
+ elif item.filename == gname + ".md5":
295
+ dst.writestr(item, md5)
296
+ elif item.filename == "Metadata/slice_info.config":
297
+ cfg = src.read(item).decode("utf-8")
298
+ cfg = cfg.replace('key="printer_model_id" value=""',
299
+ 'key="printer_model_id" value="%s"' % printer.model_id)
300
+ dst.writestr(item, cfg)
301
+ else:
302
+ dst.writestr(item, src.read(item))
303
+
304
+
305
+ def join_files(output: str, specs: List[str], opts: Options, log=None) -> Tuple[int, Printer]:
306
+ """CLI mode: several .gcode.3mf files in, one .gcode.3mf out."""
307
+ jobs = parse_jobs(specs)
308
+ plates = [(os.path.basename(p), read_plate(p)[1]) for p in jobs]
309
+ gcode, printer = build_job(plates, opts, log)
310
+ write_3mf(jobs[0], output, gcode, printer)
311
+ return len(jobs), printer
312
+
313
+
314
+ def process_in_place(path: str, copies: int, opts: Options, log=None) -> Tuple[int, Printer]:
315
+ """Post-processing mode: rewrite a plain .gcode file, optionally repeating it."""
316
+ if copies < 1:
317
+ raise AutoEjectError("--copies must be at least 1")
318
+ with open(path, encoding="utf-8") as f:
319
+ gcode = f.read()
320
+ if "AUTO-EJECT START" in gcode:
321
+ raise AutoEjectError("%s: already processed by bambu-autoeject" % path)
322
+ label = os.path.basename(path)
323
+ out, printer = build_job([(label, gcode)] * copies, opts, log)
324
+ with open(path, "w", encoding="utf-8") as f:
325
+ f.write(out)
326
+ return copies, printer
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: bambu-autoeject
3
+ Version: 0.1.0
4
+ Summary: Chain prints on a Bambu Lab A1 and push each finished part off the bed, no extra hardware
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/bullsrobo-boop/bambu-autoeject
7
+ Project-URL: Issues, https://github.com/bullsrobo-boop/bambu-autoeject/issues
8
+ Keywords: 3d-printing,bambu-lab,a1,gcode,print-farm,auto-eject
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Manufacturing
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Printing
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # bambu-autoeject
21
+
22
+ [![test](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml/badge.svg)](https://github.com/bullsrobo-boop/bambu-autoeject/actions/workflows/test.yml)
23
+
24
+ Print a queue of parts on a **Bambu Lab A1** without standing next to it. No extra hardware, no firmware changes.
25
+
26
+ The tool joins several sliced plates into one job. After each print the printer:
27
+
28
+ 1. turns off the bed and nozzle and waits for the bed to cool (12 minutes by default, fan on);
29
+ 2. lowers the nozzle to 1 mm behind the parts and pushes them forward, in lanes 6 mm apart, until they fall off the front of the bed;
30
+ 3. re-homes and starts the next print.
31
+
32
+ > **Status: alpha, not yet tested on a real printer.** The G-code is generated and covered by tests, but the eject moves have not been run on hardware. Do the dry run first and stay next to the printer for the first real runs. Test reports are the most useful contribution right now: [open a printer test report](https://github.com/bullsrobo-boop/bambu-autoeject/issues/new?template=printer-test.yml).
33
+
34
+ ## Supported printers
35
+
36
+ | Printer | Status |
37
+ | --- | --- |
38
+ | Bambu Lab A1 | main target, values from the stock profile |
39
+ | Bambu Lab A1 mini | experimental, values from the stock profile, `--clean-front` not available |
40
+ | P1, X1, H2D | not supported (closed front or no bed slinger) |
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install bambu-autoeject
46
+ ```
47
+
48
+ Python 3.9 or newer, no other dependencies. Without installing you can also run `python3 autoeject.py ...` from a clone of this repository.
49
+
50
+ ## Usage
51
+
52
+ ### Join several plates
53
+
54
+ 1. Slice each model in Bambu Studio and export it with **File > Export > Export plate sliced file** (`.gcode.3mf`, one plate per file).
55
+ 2. Run:
56
+
57
+ ```bash
58
+ bambu-autoeject queue.gcode.3mf bracket.gcode.3mf:3 keychain.gcode.3mf:2
59
+ ```
60
+
61
+ `:3` means three copies in a row. Open `queue.gcode.3mf` in Bambu Studio and send it to the printer like any sliced file.
62
+
63
+ ### From inside Bambu Studio (experimental)
64
+
65
+ Bambu Studio can run a post-processing script on every slice. In the process settings (Advanced mode), **Others > Post-processing Scripts**, add:
66
+
67
+ ```
68
+ bambu-autoeject --in-place --copies 3;
69
+ ```
70
+
71
+ Bambu Studio adds the G-code path at the end. Every slice is then printed 3 times with an eject after each. Use the full path to `bambu-autoeject` if Bambu Studio cannot find it (`which bambu-autoeject` on macOS and Linux, `where bambu-autoeject` on Windows). This mode has only been tested on exported files so far, not on jobs sent from Bambu Studio over the network.
72
+
73
+ ### Options
74
+
75
+ | Option | Default | What it does |
76
+ | --- | --- | --- |
77
+ | `--cool-min N` | 12 | minutes of cooling before the push |
78
+ | `--push-z MM` | 1.0 | nozzle height while pushing (not below 0.5) |
79
+ | `--lane MM` | 6 | spacing between push lanes (use 4 for very narrow parts) |
80
+ | `--behind MM` | 8 | how far behind the parts the nozzle comes down |
81
+ | `--keep-last` | off | leave the last print on the bed |
82
+ | `--dry-run` | off | do all the moves above the part, never touching it |
83
+ | `--clean-front` | off | A1 only: also push off the front calibration line (nozzle at 0.3 mm, may scratch) |
84
+ | `--copies N` | 1 | with `--in-place`: repeat the plate N times |
85
+
86
+ Full list: `bambu-autoeject --help`.
87
+
88
+ ## Safety
89
+
90
+ - The nozzle never goes below the `--push-z` height (1 mm by default) unless you use `--clean-front`.
91
+ - Motor current is lowered during the push, so a stuck part makes the motor skip instead of forcing it. The printer re-homes afterwards.
92
+ - The start G-code draws a calibration line on the front edge. The nozzle cannot reach it safely, so the first line stays on the bed and later prints skip drawing it again.
93
+ - Plates sliced for different printers cannot be mixed in one job.
94
+
95
+ ## What works and what does not
96
+
97
+ - Best on the **textured PEI plate** with PLA or PETG: parts release by themselves once the bed is cold.
98
+ - Very small parts (base under about 15 x 15 mm) or large flat bases may not release.
99
+ - Tall, thin parts can tip over: print them lying down or with a brim.
100
+ - Leave 8 mm free between the parts and the back edge of the bed.
101
+ - Put a box or a ramp in front of the printer to catch the parts.
102
+
103
+ ## First test
104
+
105
+ `examples/a1/` contains a 20 mm cube sliced for the A1 (textured PEI plate, Bambu PLA Basic):
106
+
107
+ 1. `1_dry_run.gcode.3mf`: prints the cube, waits 12 minutes, then does all the eject moves **above** it. Check that the path looks right.
108
+ 2. `2_eject_one_cube.gcode.3mf`: same cube, this time pushed off. Keep a hand near the stop button.
109
+ 3. `3_two_cubes.gcode.3mf`: two cubes in a row with an eject after each, the full loop.
110
+
111
+ `examples/a1-mini/` has the dry run and the two-cube job for the A1 mini.
112
+
113
+ If the printer does not wait the 12 minutes in step 1, the firmware is ignoring `M400 S60`; please report it.
114
+
115
+ ## How it works
116
+
117
+ Bambu Studio writes the whole job as plain G-code inside the `.gcode.3mf` archive. The tool reads the first layer to find where the parts are, inserts an eject block before the end sequence turns off the motors, removes the duplicate header and calibration line from the following jobs and writes the joined G-code back into a copy of the first archive, so thumbnails and settings stay intact.
118
+
119
+ ## Contributing
120
+
121
+ See [CONTRIBUTING.md](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/CONTRIBUTING.md). Run the tests with `python3 -m unittest`.
122
+
123
+ ## License
124
+
125
+ MIT, see [LICENSE](https://github.com/bullsrobo-boop/bambu-autoeject/blob/main/LICENSE). Use at your own risk: this changes how your printer moves.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ bambu_autoeject/__init__.py
5
+ bambu_autoeject/__main__.py
6
+ bambu_autoeject/cli.py
7
+ bambu_autoeject/core.py
8
+ bambu_autoeject.egg-info/PKG-INFO
9
+ bambu_autoeject.egg-info/SOURCES.txt
10
+ bambu_autoeject.egg-info/dependency_links.txt
11
+ bambu_autoeject.egg-info/entry_points.txt
12
+ bambu_autoeject.egg-info/top_level.txt
13
+ tests/test_autoeject.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bambu-autoeject = bambu_autoeject.cli:main
@@ -0,0 +1 @@
1
+ bambu_autoeject
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bambu-autoeject"
7
+ dynamic = ["version"]
8
+ description = "Chain prints on a Bambu Lab A1 and push each finished part off the bed, no extra hardware"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ keywords = ["3d-printing", "bambu-lab", "a1", "gcode", "print-farm", "auto-eject"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Manufacturing",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Printing",
21
+ ]
22
+
23
+ [project.scripts]
24
+ bambu-autoeject = "bambu_autoeject.cli:main"
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/bullsrobo-boop/bambu-autoeject"
28
+ Issues = "https://github.com/bullsrobo-boop/bambu-autoeject/issues"
29
+
30
+ [tool.setuptools]
31
+ packages = ["bambu_autoeject"]
32
+
33
+ [tool.setuptools.dynamic]
34
+ version = { attr = "bambu_autoeject.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,140 @@
1
+ import os
2
+ import re
3
+ import shutil
4
+ import tempfile
5
+ import unittest
6
+ import zipfile
7
+
8
+ from bambu_autoeject.cli import main
9
+ from bambu_autoeject.core import (AutoEjectError, Options, PRINTERS, build_job, first_layer_bbox,
10
+ join_files, parse_jobs, process_in_place, read_plate)
11
+
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+ EXAMPLES = os.path.join(HERE, "..", "examples")
14
+ A1_CUBE = os.path.join(EXAMPLES, "a1", "cube20.gcode.3mf")
15
+ MINI_CUBE = os.path.join(EXAMPLES, "a1-mini", "cube20.gcode.3mf")
16
+
17
+
18
+ def gcode_of(path):
19
+ return read_plate(path)[1]
20
+
21
+
22
+ def eject_blocks(gcode):
23
+ return re.findall(r"AUTO-EJECT START.*?AUTO-EJECT END", gcode, re.S)
24
+
25
+
26
+ def z_moves(text):
27
+ return [float(z) for z in re.findall(r"^G1 Z([\d.]+)", text, re.M)]
28
+
29
+
30
+ class ParseJobs(unittest.TestCase):
31
+ def test_counts(self):
32
+ self.assertEqual(parse_jobs(["a.gcode.3mf:3", "b.gcode.3mf"]),
33
+ ["a.gcode.3mf"] * 3 + ["b.gcode.3mf"])
34
+
35
+ def test_windows_path_without_count(self):
36
+ self.assertEqual(parse_jobs([r"C:\prints\a.gcode.3mf"]), [r"C:\prints\a.gcode.3mf"])
37
+
38
+ def test_zero_count_rejected(self):
39
+ with self.assertRaises(AutoEjectError):
40
+ parse_jobs(["a.gcode.3mf:0"])
41
+
42
+
43
+ class Geometry(unittest.TestCase):
44
+ def test_cube_bbox_a1(self):
45
+ xmin, ymin, xmax, ymax = first_layer_bbox(gcode_of(A1_CUBE))
46
+ self.assertAlmostEqual(xmax - xmin, 20, delta=1)
47
+ self.assertAlmostEqual(ymax - ymin, 20, delta=1)
48
+
49
+
50
+ class EjectSafety(unittest.TestCase):
51
+ def check(self, cube, printer):
52
+ gcode = gcode_of(cube)
53
+ out, found = build_job([("cube", gcode)] * 2, Options())
54
+ self.assertEqual(found, PRINTERS[printer])
55
+ blocks = eject_blocks(out)
56
+ self.assertEqual(len(blocks), 2)
57
+ for block in blocks:
58
+ self.assertGreaterEqual(min(z_moves(block)), 1.0)
59
+ ys = [float(y) for y in re.findall(r"Y(-?[\d.]+)", block)]
60
+ self.assertLessEqual(max(ys), PRINTERS[printer].bed[1])
61
+ # the second job must not draw the calibration line again
62
+ second = out.split("JOB 2/2")[1]
63
+ self.assertNotIn(";===== extrude cali test", second)
64
+ self.assertIn("calibration line removed", second)
65
+
66
+ def test_a1(self):
67
+ self.check(A1_CUBE, "Bambu Lab A1")
68
+
69
+ def test_a1_mini(self):
70
+ self.check(MINI_CUBE, "Bambu Lab A1 mini")
71
+
72
+ def test_dry_run_stays_above_part(self):
73
+ out, _ = build_job([("cube", gcode_of(A1_CUBE))], Options(dry_run=True))
74
+ self.assertGreater(min(z_moves(eject_blocks(out)[0])), 20)
75
+
76
+ def test_keep_last(self):
77
+ out, _ = build_job([("cube", gcode_of(A1_CUBE))] * 2, Options(keep_last=True))
78
+ self.assertEqual(len(eject_blocks(out)), 1)
79
+
80
+ def test_clean_front_not_on_mini(self):
81
+ with self.assertRaises(AutoEjectError):
82
+ build_job([("cube", gcode_of(MINI_CUBE))], Options(clean_front=True))
83
+
84
+ def test_mixed_printers_rejected(self):
85
+ with self.assertRaises(AutoEjectError):
86
+ build_job([("a", gcode_of(A1_CUBE)), ("b", gcode_of(MINI_CUBE))], Options())
87
+
88
+ def test_unknown_printer_rejected(self):
89
+ gcode = gcode_of(A1_CUBE).replace("; printer_model = Bambu Lab A1", "; printer_model = Bambu Lab X1C")
90
+ with self.assertRaises(AutoEjectError):
91
+ build_job([("x", gcode)], Options())
92
+
93
+
94
+ class Files(unittest.TestCase):
95
+ def setUp(self):
96
+ self.tmp = tempfile.mkdtemp()
97
+
98
+ def tearDown(self):
99
+ shutil.rmtree(self.tmp)
100
+
101
+ def test_examples_are_up_to_date(self):
102
+ cases = [("1_dry_run", ["cube20.gcode.3mf"], Options(dry_run=True)),
103
+ ("2_eject_one_cube", ["cube20.gcode.3mf"], Options()),
104
+ ("3_two_cubes", ["cube20.gcode.3mf:2"], Options())]
105
+ folder = os.path.join(EXAMPLES, "a1")
106
+ for name, specs, opts in cases:
107
+ out = os.path.join(self.tmp, name + ".gcode.3mf")
108
+ cwd = os.getcwd()
109
+ os.chdir(folder)
110
+ try:
111
+ join_files(out, specs, opts)
112
+ finally:
113
+ os.chdir(cwd)
114
+ self.assertEqual(gcode_of(out), gcode_of(os.path.join(folder, name + ".gcode.3mf")), name)
115
+
116
+ def test_output_archive(self):
117
+ out = os.path.join(self.tmp, "q.gcode.3mf")
118
+ join_files(out, [MINI_CUBE + ":2"], Options())
119
+ with zipfile.ZipFile(out) as z:
120
+ self.assertIn('value="N1"', z.read("Metadata/slice_info.config").decode())
121
+ self.assertIn("Metadata/plate_1.png", z.namelist())
122
+
123
+ def test_in_place(self):
124
+ path = os.path.join(self.tmp, "plate.gcode")
125
+ with open(path, "w") as f:
126
+ f.write(gcode_of(A1_CUBE))
127
+ process_in_place(path, 3, Options())
128
+ with open(path) as f:
129
+ self.assertEqual(len(eject_blocks(f.read())), 3)
130
+ with self.assertRaises(AutoEjectError):
131
+ process_in_place(path, 1, Options())
132
+
133
+ def test_cli_error_exit(self):
134
+ with self.assertRaises(SystemExit) as ctx:
135
+ main([os.path.join(self.tmp, "o.gcode.3mf"), A1_CUBE, "--push-z", "0.1"])
136
+ self.assertEqual(ctx.exception.code, 1)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ unittest.main()