flashforge-python-api 1.4.0__py3-none-any.whl → 1.6.0__py3-none-any.whl
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.
- flashforge/__init__.py +24 -1
- flashforge/api/constants/commands.py +1 -1
- flashforge/api/controls/control.py +11 -14
- flashforge/api/controls/creator5_palette.py +3 -3
- flashforge/api/controls/files.py +3 -4
- flashforge/api/controls/info.py +2 -2
- flashforge/api/controls/job_control.py +132 -77
- flashforge/api/controls/temp_control.py +4 -4
- flashforge/client.py +49 -30
- flashforge/exceptions.py +1 -1
- flashforge/models/machine_info.py +2 -2
- flashforge/models/responses.py +17 -10
- flashforge/threemf/__init__.py +40 -0
- flashforge/threemf/parser.py +560 -0
- flashforge/threemf/warnings.py +58 -0
- {flashforge_python_api-1.4.0.dist-info → flashforge_python_api-1.6.0.dist-info}/METADATA +35 -2
- {flashforge_python_api-1.4.0.dist-info → flashforge_python_api-1.6.0.dist-info}/RECORD +20 -17
- {flashforge_python_api-1.4.0.dist-info → flashforge_python_api-1.6.0.dist-info}/WHEEL +1 -1
- {flashforge_python_api-1.4.0.dist-info → flashforge_python_api-1.6.0.dist-info}/entry_points.txt +0 -0
- {flashforge_python_api-1.4.0.dist-info → flashforge_python_api-1.6.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -20,7 +20,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
|
|
20
20
|
# blast radius: pydantic fails a model as a unit, and `Info.get_detail_response`
|
|
21
21
|
# turns any failure into "no data", which Home Assistant shows as an offline
|
|
22
22
|
# printer. So a `ge=0` on a field nobody reads could take the whole integration
|
|
23
|
-
# down. That is exactly what happened in
|
|
23
|
+
# down. That is exactly what happened in ff-5mp-hass#18, where a Creator 5 reporting
|
|
24
24
|
# `chamberTemp: -108` made every entity unavailable and the config flow report
|
|
25
25
|
# `cannot_connect`.
|
|
26
26
|
#
|
|
@@ -369,7 +369,7 @@ class FFPrinterDetail(BaseModel):
|
|
|
369
369
|
z_axis_compensation: float | None = Field(default=None, alias="zAxisCompensation")
|
|
370
370
|
|
|
371
371
|
# Firmware reports absent temperature hardware with a negative sentinel
|
|
372
|
-
# (-108 on a chamber-less Creator 5,
|
|
372
|
+
# (-108 on a chamber-less Creator 5, ff-5mp-hass#18) rather than by omitting the
|
|
373
373
|
# field. Map those to None here so "no sensor" reads as "not reported"
|
|
374
374
|
# everywhere downstream, instead of as a -108 C reading or a hard failure.
|
|
375
375
|
@field_validator(
|
flashforge/models/responses.py
CHANGED
|
@@ -175,12 +175,12 @@ class AD5XUploadParams(BaseModel):
|
|
|
175
175
|
class Creator5JobParams(BaseModel):
|
|
176
176
|
"""Parameters for starting a Creator 5 / Creator 5 Pro local print job.
|
|
177
177
|
|
|
178
|
-
|
|
179
|
-
(
|
|
180
|
-
``
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
178
|
+
The body carries NO ``useMatlStation`` / ``gcodeToolCnt`` /
|
|
179
|
+
``firstLayerInspection`` (the latter doesn't exist on the C5).
|
|
180
|
+
``flowCalibration`` and ``timeLapseVideo`` are always present (default False).
|
|
181
|
+
Map every tool, including a single-tool print: without mappings the firmware
|
|
182
|
+
prints each tool from the slot with the slicer's filament number (filament 1
|
|
183
|
+
-> slot 1). Mappings take effect only for a .3mf file.
|
|
184
184
|
"""
|
|
185
185
|
|
|
186
186
|
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
@@ -196,16 +196,18 @@ class Creator5JobParams(BaseModel):
|
|
|
196
196
|
material_mappings: list[AD5XMaterialMapping] | None = Field(
|
|
197
197
|
default=None,
|
|
198
198
|
max_length=4,
|
|
199
|
-
description="
|
|
199
|
+
description="Per-tool material mappings (1-4 items); recommended for every print",
|
|
200
200
|
)
|
|
201
201
|
|
|
202
202
|
|
|
203
203
|
class Creator5UploadParams(BaseModel):
|
|
204
204
|
"""Parameters for uploading a file to a Creator 5 / Creator 5 Pro.
|
|
205
205
|
|
|
206
|
-
Mirrors the AD5X upload but omits ``firstLayerInspection`` (absent on the
|
|
207
|
-
|
|
208
|
-
|
|
206
|
+
Mirrors the AD5X upload but omits ``firstLayerInspection`` (absent on the
|
|
207
|
+
C5). ``material_mappings`` is sent as the base64 ``materialMappings`` header
|
|
208
|
+
only when ``start_print`` is true. The firmware only logs ``use_matl_station``
|
|
209
|
+
and ``gcode_tool_cnt``. The C5 firmware checks the booleans as the string
|
|
210
|
+
"true"/"false".
|
|
209
211
|
"""
|
|
210
212
|
|
|
211
213
|
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
@@ -223,6 +225,11 @@ class Creator5UploadParams(BaseModel):
|
|
|
223
225
|
gcode_tool_cnt: int = Field(
|
|
224
226
|
ge=1, le=4, description="Number of tools in the G-code (1-4 for the C5)"
|
|
225
227
|
)
|
|
228
|
+
material_mappings: list[AD5XMaterialMapping] | None = Field(
|
|
229
|
+
default=None,
|
|
230
|
+
max_length=4,
|
|
231
|
+
description="Optional per-tool material mappings, sent only when start_print is true",
|
|
232
|
+
)
|
|
226
233
|
|
|
227
234
|
|
|
228
235
|
class GCodeListResponse(GenericResponse):
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FlashForge Python API - 3MF support
|
|
3
|
+
|
|
4
|
+
Parse a sliced ``.3mf`` before upload to learn which tools and materials the
|
|
5
|
+
print uses. See :func:`parse_3mf`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .parser import (
|
|
9
|
+
MAX_GCODE_HEADER_BYTES,
|
|
10
|
+
MAX_SLICE_INFO_BYTES,
|
|
11
|
+
MAX_THUMBNAIL_BYTES,
|
|
12
|
+
PrinterFamily,
|
|
13
|
+
ThreeMFError,
|
|
14
|
+
ThreeMFFilament,
|
|
15
|
+
ThreeMFFile,
|
|
16
|
+
ThreeMFFormatError,
|
|
17
|
+
ThreeMFMultiplePlatesError,
|
|
18
|
+
ThreeMFNotSlicedError,
|
|
19
|
+
ThreeMFWarning,
|
|
20
|
+
parse_3mf,
|
|
21
|
+
printer_family_from_model_id,
|
|
22
|
+
)
|
|
23
|
+
from .warnings import translate_warning
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"MAX_GCODE_HEADER_BYTES",
|
|
27
|
+
"MAX_SLICE_INFO_BYTES",
|
|
28
|
+
"MAX_THUMBNAIL_BYTES",
|
|
29
|
+
"PrinterFamily",
|
|
30
|
+
"ThreeMFError",
|
|
31
|
+
"ThreeMFFilament",
|
|
32
|
+
"ThreeMFFile",
|
|
33
|
+
"ThreeMFFormatError",
|
|
34
|
+
"ThreeMFMultiplePlatesError",
|
|
35
|
+
"ThreeMFNotSlicedError",
|
|
36
|
+
"ThreeMFWarning",
|
|
37
|
+
"parse_3mf",
|
|
38
|
+
"printer_family_from_model_id",
|
|
39
|
+
"translate_warning",
|
|
40
|
+
]
|
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FlashForge Python API - Sliced 3MF parser
|
|
3
|
+
|
|
4
|
+
Reads what a client needs to know about a sliced ``.3mf`` before it sends the
|
|
5
|
+
file to a printer: which filaments (tools) the print uses, with their material
|
|
6
|
+
and color, plus the plate thumbnail, time and weight estimates, the printer model
|
|
7
|
+
the file was sliced for, and any slicer warnings.
|
|
8
|
+
|
|
9
|
+
This is the information a client needs to build material mappings. The Creator 5
|
|
10
|
+
series does not report a stored file's tools, so for that family, parsing the
|
|
11
|
+
3MF before upload is the only way to map tools to Material Station slots
|
|
12
|
+
correctly.
|
|
13
|
+
|
|
14
|
+
Tested with output from Orca-FlashForge, OrcaSlicer, Flash Studio and Snapmaker
|
|
15
|
+
Orca. The fields
|
|
16
|
+
match ``ThreeMfParser`` in the TypeScript ``slicer-meta`` package.
|
|
17
|
+
|
|
18
|
+
The parser reads only small, bounded parts of the archive: the slice metadata,
|
|
19
|
+
the plate image and the start of the plate G-code. It never decompresses the
|
|
20
|
+
whole G-code, so a large or hostile archive costs a bounded amount of memory.
|
|
21
|
+
Parsing is synchronous file I/O. In an asyncio program, run it in an executor
|
|
22
|
+
(for example ``await asyncio.to_thread(parse_3mf, path)``).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
import zipfile
|
|
30
|
+
import zlib
|
|
31
|
+
from enum import StrEnum
|
|
32
|
+
from typing import IO, TypeVar
|
|
33
|
+
from xml.etree import ElementTree
|
|
34
|
+
|
|
35
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
36
|
+
|
|
37
|
+
from ..exceptions import FlashForgeError
|
|
38
|
+
from .warnings import translate_warning
|
|
39
|
+
|
|
40
|
+
# Size limits for the parts of the archive the parser reads. A real
|
|
41
|
+
# slice_info.config is 1-2 KB and a plate image well under 100 KB, so these
|
|
42
|
+
# bounds only ever stop a malformed or hostile archive.
|
|
43
|
+
MAX_SLICE_INFO_BYTES = 4 * 1024 * 1024
|
|
44
|
+
MAX_THUMBNAIL_BYTES = 8 * 1024 * 1024
|
|
45
|
+
# How much of the plate G-code to scan for the header comments. The header and
|
|
46
|
+
# the summary block sit at the start of the file; embedded thumbnails can push
|
|
47
|
+
# the summary back by a few hundred KB, so the scan stops at the first
|
|
48
|
+
# executable line or at this bound, whichever comes first.
|
|
49
|
+
MAX_GCODE_HEADER_BYTES = 1024 * 1024
|
|
50
|
+
|
|
51
|
+
_T = TypeVar("_T")
|
|
52
|
+
|
|
53
|
+
_SLICE_INFO = "Metadata/slice_info.config"
|
|
54
|
+
_PLATE_GCODE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
|
|
55
|
+
_HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
|
56
|
+
_HEX8 = re.compile(r"^#[0-9A-Fa-f]{8}$")
|
|
57
|
+
_HEX3 = re.compile(r"^#[0-9A-Fa-f]{3}$")
|
|
58
|
+
_GENERATED_BY = re.compile(r"^;\s*generated by\s+(.+?)\s+(\d\S*)(?:\s+on\s|\s*$)", re.IGNORECASE)
|
|
59
|
+
_DURATION = re.compile(r"(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ThreeMFError(FlashForgeError):
|
|
63
|
+
"""Base class for errors raised while reading a 3MF file."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ThreeMFFormatError(ThreeMFError):
|
|
67
|
+
"""The file is not a readable 3MF archive, or its slice metadata is malformed."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ThreeMFNotSlicedError(ThreeMFError):
|
|
71
|
+
"""
|
|
72
|
+
The archive holds no sliced plate G-code.
|
|
73
|
+
|
|
74
|
+
A project 3MF saved from the slicer has models but no G-code, so a printer
|
|
75
|
+
cannot print it. Export the sliced plate from the slicer instead.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ThreeMFMultiplePlatesError(ThreeMFError):
|
|
80
|
+
"""
|
|
81
|
+
The archive holds more than one sliced plate.
|
|
82
|
+
|
|
83
|
+
Which plate a printer prints from such a file is not known, so a client
|
|
84
|
+
cannot tell which tools and materials the print uses. Export a single plate
|
|
85
|
+
from the slicer instead.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, plate_count: int) -> None:
|
|
89
|
+
"""
|
|
90
|
+
Args:
|
|
91
|
+
plate_count: The number of sliced plates in the archive.
|
|
92
|
+
"""
|
|
93
|
+
super().__init__(
|
|
94
|
+
f"This 3MF holds {plate_count} sliced plates. Export a single plate from the "
|
|
95
|
+
"slicer and try again."
|
|
96
|
+
)
|
|
97
|
+
self.plate_count = plate_count
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class PrinterFamily(StrEnum):
|
|
101
|
+
"""The printer model a 3MF was sliced for, as far as this library can tell."""
|
|
102
|
+
|
|
103
|
+
ADVENTURER_5M = "adventurer_5m"
|
|
104
|
+
ADVENTURER_5M_PRO = "adventurer_5m_pro"
|
|
105
|
+
AD5X = "ad5x"
|
|
106
|
+
CREATOR_5 = "creator_5"
|
|
107
|
+
CREATOR_5_PRO = "creator_5_pro"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def printer_family_from_model_id(model_id: str | None) -> PrinterFamily | None:
|
|
111
|
+
"""
|
|
112
|
+
Map a slicer printer-model id to a printer family.
|
|
113
|
+
|
|
114
|
+
Slicers write ids such as ``Flashforge-Adventurer-5M-Pro``, ``Flashforge-AD5X``
|
|
115
|
+
and ``Flashforge-Creator-5-Pro``. The comparison ignores case, spaces, hyphens
|
|
116
|
+
and underscores, so ``Flashforge Adventurer 5M Pro`` matches too.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
model_id: The id from the file, or ``None``.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
The matching family, or ``None`` for an unknown or missing id.
|
|
123
|
+
"""
|
|
124
|
+
if not model_id:
|
|
125
|
+
return None
|
|
126
|
+
folded = re.sub(r"[\s_\-]+", "", model_id).lower()
|
|
127
|
+
if "ad5x" in folded:
|
|
128
|
+
return PrinterFamily.AD5X
|
|
129
|
+
if "creator5pro" in folded:
|
|
130
|
+
return PrinterFamily.CREATOR_5_PRO
|
|
131
|
+
if "creator5" in folded:
|
|
132
|
+
return PrinterFamily.CREATOR_5
|
|
133
|
+
if "5mpro" in folded:
|
|
134
|
+
return PrinterFamily.ADVENTURER_5M_PRO
|
|
135
|
+
if "adventurer5m" in folded or folded.endswith("ad5m"):
|
|
136
|
+
return PrinterFamily.ADVENTURER_5M
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class ThreeMFFilament(BaseModel):
|
|
141
|
+
"""One filament (tool) that the sliced plate uses."""
|
|
142
|
+
|
|
143
|
+
model_config = ConfigDict(frozen=True)
|
|
144
|
+
|
|
145
|
+
filament_id: int = Field(description="The slicer's filament number (1-based)")
|
|
146
|
+
tool_id: int = Field(
|
|
147
|
+
description=(
|
|
148
|
+
"The tool id a material mapping uses for this filament (0-based: filament 1 "
|
|
149
|
+
"is tool 0)"
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
material_name: str = Field(default="", description="Material type, e.g. 'PLA'")
|
|
153
|
+
color: str = Field(
|
|
154
|
+
default="", description="Filament color as #RRGGBB, or '' if the file has none"
|
|
155
|
+
)
|
|
156
|
+
used_m: float | None = Field(default=None, description="Filament length used, in meters")
|
|
157
|
+
used_g: float | None = Field(default=None, description="Filament weight used, in grams")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class ThreeMFWarning(BaseModel):
|
|
161
|
+
"""A warning the slicer recorded for the plate."""
|
|
162
|
+
|
|
163
|
+
model_config = ConfigDict(frozen=True)
|
|
164
|
+
|
|
165
|
+
key: str = Field(description="Raw warning key, e.g. 'bed_temperature_too_high_than_filament'")
|
|
166
|
+
message: str = Field(description="Readable text for the key")
|
|
167
|
+
level: int = Field(default=0, description="Severity level as the slicer wrote it")
|
|
168
|
+
error_code: str = Field(default="", description="The slicer's error code, if any")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class ThreeMFFile(BaseModel):
|
|
172
|
+
"""What a sliced 3MF says about its print."""
|
|
173
|
+
|
|
174
|
+
model_config = ConfigDict(frozen=True)
|
|
175
|
+
|
|
176
|
+
file_name: str = Field(description="The file's base name")
|
|
177
|
+
plate_index: int = Field(description="The index of the sliced plate (1-based)")
|
|
178
|
+
printer_model_id: str | None = Field(
|
|
179
|
+
default=None, description="The printer model id the file was sliced for"
|
|
180
|
+
)
|
|
181
|
+
slicer_name: str | None = Field(default=None, description="e.g. 'Orca-Flashforge'")
|
|
182
|
+
slicer_version: str | None = Field(default=None, description="e.g. '1.4.2'")
|
|
183
|
+
estimated_time_s: int | None = Field(
|
|
184
|
+
default=None, description="The slicer's print time estimate, in seconds"
|
|
185
|
+
)
|
|
186
|
+
total_weight_g: float | None = Field(
|
|
187
|
+
default=None, description="Total filament weight, in grams"
|
|
188
|
+
)
|
|
189
|
+
first_layer_time_s: float | None = Field(
|
|
190
|
+
default=None, description="The slicer's first-layer time estimate, in seconds"
|
|
191
|
+
)
|
|
192
|
+
layer_count: int | None = Field(default=None, description="Total layer count")
|
|
193
|
+
support_used: bool = Field(default=False, description="Whether the plate uses supports")
|
|
194
|
+
nozzle_diameters: list[float] = Field(
|
|
195
|
+
default_factory=list, description="Nozzle diameter per extruder, in mm"
|
|
196
|
+
)
|
|
197
|
+
object_names: list[str] = Field(
|
|
198
|
+
default_factory=list, description="Names of the objects on the plate"
|
|
199
|
+
)
|
|
200
|
+
filaments: list[ThreeMFFilament] = Field(
|
|
201
|
+
default_factory=list, description="The filaments the plate uses, by filament id"
|
|
202
|
+
)
|
|
203
|
+
warnings: list[ThreeMFWarning] = Field(
|
|
204
|
+
default_factory=list, description="Warnings the slicer recorded"
|
|
205
|
+
)
|
|
206
|
+
thumbnail_png: bytes | None = Field(
|
|
207
|
+
default=None, repr=False, description="The plate preview image (PNG bytes)"
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def tool_count(self) -> int:
|
|
212
|
+
"""The number of filaments (tools) the plate uses."""
|
|
213
|
+
return len(self.filaments)
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def printer_family(self) -> PrinterFamily | None:
|
|
217
|
+
"""The printer family the file was sliced for, if the id is known."""
|
|
218
|
+
return printer_family_from_model_id(self.printer_model_id)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def parse_3mf(
|
|
222
|
+
source: str | os.PathLike[str] | IO[bytes],
|
|
223
|
+
*,
|
|
224
|
+
file_name: str | None = None,
|
|
225
|
+
) -> ThreeMFFile:
|
|
226
|
+
"""
|
|
227
|
+
Parse a sliced 3MF file.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
source: A path to the file, or a binary file object open for reading.
|
|
231
|
+
file_name: The name to report in :attr:`ThreeMFFile.file_name`. Defaults
|
|
232
|
+
to the base name of ``source`` when it is a path.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
The parsed metadata.
|
|
236
|
+
|
|
237
|
+
Raises:
|
|
238
|
+
FileNotFoundError: If ``source`` is a path that does not exist.
|
|
239
|
+
ThreeMFFormatError: If the file is not a valid ZIP archive, has a corrupt
|
|
240
|
+
entry, or its slice metadata is malformed or too large.
|
|
241
|
+
ThreeMFNotSlicedError: If the archive holds no sliced plate G-code.
|
|
242
|
+
ThreeMFMultiplePlatesError: If the archive holds more than one sliced plate.
|
|
243
|
+
"""
|
|
244
|
+
if file_name is None:
|
|
245
|
+
file_name = (
|
|
246
|
+
os.path.basename(os.fspath(source))
|
|
247
|
+
if isinstance(source, (str, os.PathLike))
|
|
248
|
+
else "unknown.3mf"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
try:
|
|
252
|
+
archive = zipfile.ZipFile(source)
|
|
253
|
+
except FileNotFoundError:
|
|
254
|
+
raise
|
|
255
|
+
except (zipfile.BadZipFile, OSError, ValueError) as err:
|
|
256
|
+
raise ThreeMFFormatError(f"'{file_name}' is not a readable 3MF archive: {err}") from err
|
|
257
|
+
|
|
258
|
+
with archive:
|
|
259
|
+
try:
|
|
260
|
+
return _parse_archive(archive, file_name)
|
|
261
|
+
except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError) as err:
|
|
262
|
+
# A corrupt entry (bad CRC, truncated or unsupported compression).
|
|
263
|
+
raise ThreeMFFormatError(f"'{file_name}' has a corrupt entry: {err}") from err
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _parse_archive(archive: zipfile.ZipFile, file_name: str) -> ThreeMFFile:
|
|
267
|
+
plates: dict[int, str] = {}
|
|
268
|
+
for name in archive.namelist():
|
|
269
|
+
match = _PLATE_GCODE.match(name)
|
|
270
|
+
if match:
|
|
271
|
+
plates[int(match.group(1))] = name
|
|
272
|
+
|
|
273
|
+
if not plates:
|
|
274
|
+
raise ThreeMFNotSlicedError(
|
|
275
|
+
f"'{file_name}' holds no sliced G-code. Slice the plate and export the sliced "
|
|
276
|
+
"file from the slicer."
|
|
277
|
+
)
|
|
278
|
+
if len(plates) > 1:
|
|
279
|
+
raise ThreeMFMultiplePlatesError(len(plates))
|
|
280
|
+
|
|
281
|
+
plate_index, gcode_name = next(iter(plates.items()))
|
|
282
|
+
|
|
283
|
+
fields: dict[str, object] = {"file_name": file_name, "plate_index": plate_index}
|
|
284
|
+
filaments: list[ThreeMFFilament] = []
|
|
285
|
+
|
|
286
|
+
if _SLICE_INFO in archive.namelist():
|
|
287
|
+
raw = _read_bounded(archive, _SLICE_INFO, MAX_SLICE_INFO_BYTES)
|
|
288
|
+
if raw is None:
|
|
289
|
+
raise ThreeMFFormatError(f"'{file_name}' has an oversized slice_info.config.")
|
|
290
|
+
filaments = _parse_slice_info(raw, plate_index, fields, file_name)
|
|
291
|
+
|
|
292
|
+
header = _scan_gcode_header(archive, gcode_name)
|
|
293
|
+
_apply_gcode_header(header, fields)
|
|
294
|
+
if not filaments:
|
|
295
|
+
filaments = _filaments_from_header(header)
|
|
296
|
+
fields["filaments"] = filaments
|
|
297
|
+
|
|
298
|
+
thumbnail_name = f"Metadata/plate_{plate_index}.png"
|
|
299
|
+
if thumbnail_name in archive.namelist():
|
|
300
|
+
fields["thumbnail_png"] = _read_bounded(archive, thumbnail_name, MAX_THUMBNAIL_BYTES)
|
|
301
|
+
|
|
302
|
+
return ThreeMFFile.model_validate(fields)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _read_bounded(archive: zipfile.ZipFile, name: str, limit: int) -> bytes | None:
|
|
306
|
+
"""Read one entry, or return None when it is larger than ``limit``."""
|
|
307
|
+
if archive.getinfo(name).file_size > limit:
|
|
308
|
+
return None
|
|
309
|
+
with archive.open(name) as handle:
|
|
310
|
+
data = handle.read(limit + 1)
|
|
311
|
+
# file_size comes from the archive and can lie, so check what was read too.
|
|
312
|
+
return None if len(data) > limit else data
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# --------------------------------------------------------------------------- #
|
|
316
|
+
# slice_info.config
|
|
317
|
+
# --------------------------------------------------------------------------- #
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _parse_slice_info(
|
|
321
|
+
raw: bytes, plate_index: int, fields: dict[str, object], file_name: str
|
|
322
|
+
) -> list[ThreeMFFilament]:
|
|
323
|
+
try:
|
|
324
|
+
root = ElementTree.fromstring(raw)
|
|
325
|
+
except ElementTree.ParseError as err:
|
|
326
|
+
raise ThreeMFFormatError(f"'{file_name}' has a malformed slice_info.config: {err}") from err
|
|
327
|
+
|
|
328
|
+
plates = root.findall("plate")
|
|
329
|
+
if not plates:
|
|
330
|
+
return []
|
|
331
|
+
|
|
332
|
+
plate = plates[0]
|
|
333
|
+
for candidate in plates:
|
|
334
|
+
if _plate_metadata(candidate).get("index") == str(plate_index):
|
|
335
|
+
plate = candidate
|
|
336
|
+
break
|
|
337
|
+
|
|
338
|
+
meta = _plate_metadata(plate)
|
|
339
|
+
if meta.get("printer_model_id"):
|
|
340
|
+
fields["printer_model_id"] = meta["printer_model_id"]
|
|
341
|
+
prediction = _to_float(meta.get("prediction"))
|
|
342
|
+
if prediction is not None:
|
|
343
|
+
fields["estimated_time_s"] = int(round(prediction))
|
|
344
|
+
weight = _to_float(meta.get("weight"))
|
|
345
|
+
if weight is not None:
|
|
346
|
+
fields["total_weight_g"] = weight
|
|
347
|
+
first_layer = _to_float(meta.get("first_layer_time"))
|
|
348
|
+
if first_layer is not None:
|
|
349
|
+
fields["first_layer_time_s"] = first_layer
|
|
350
|
+
fields["support_used"] = meta.get("support_used", "").lower() in ("true", "1")
|
|
351
|
+
fields["nozzle_diameters"] = [
|
|
352
|
+
value
|
|
353
|
+
for value in (
|
|
354
|
+
_to_float(part) for part in re.split(r"[,\s]+", meta.get("nozzle_diameters", ""))
|
|
355
|
+
)
|
|
356
|
+
if value is not None
|
|
357
|
+
]
|
|
358
|
+
fields["object_names"] = [
|
|
359
|
+
obj.get("name", "") for obj in plate.findall("object") if obj.get("name")
|
|
360
|
+
]
|
|
361
|
+
fields["warnings"] = [
|
|
362
|
+
ThreeMFWarning(
|
|
363
|
+
key=warning.get("msg", ""),
|
|
364
|
+
message=translate_warning(warning.get("msg", "")),
|
|
365
|
+
level=_to_int(warning.get("level")) or 0,
|
|
366
|
+
error_code=warning.get("error_code", "") or "",
|
|
367
|
+
)
|
|
368
|
+
for warning in plate.findall("warning")
|
|
369
|
+
]
|
|
370
|
+
|
|
371
|
+
filaments: list[ThreeMFFilament] = []
|
|
372
|
+
for element in plate.findall("filament"):
|
|
373
|
+
filament_id = _to_int(element.get("id"))
|
|
374
|
+
if filament_id is None or filament_id < 1:
|
|
375
|
+
continue
|
|
376
|
+
filaments.append(
|
|
377
|
+
ThreeMFFilament(
|
|
378
|
+
filament_id=filament_id,
|
|
379
|
+
tool_id=filament_id - 1,
|
|
380
|
+
material_name=(element.get("type") or "").strip(),
|
|
381
|
+
color=_normalize_color(element.get("color")),
|
|
382
|
+
used_m=_to_float(element.get("used_m")),
|
|
383
|
+
used_g=_to_float(element.get("used_g")),
|
|
384
|
+
)
|
|
385
|
+
)
|
|
386
|
+
filaments.sort(key=lambda item: item.filament_id)
|
|
387
|
+
return filaments
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _plate_metadata(plate: ElementTree.Element) -> dict[str, str]:
|
|
391
|
+
return {
|
|
392
|
+
item.get("key", ""): item.get("value", "") or ""
|
|
393
|
+
for item in plate.findall("metadata")
|
|
394
|
+
if item.get("key")
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
# --------------------------------------------------------------------------- #
|
|
399
|
+
# Plate G-code header
|
|
400
|
+
# --------------------------------------------------------------------------- #
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _scan_gcode_header(archive: zipfile.ZipFile, name: str) -> dict[str, str]:
|
|
404
|
+
"""
|
|
405
|
+
Collect ``; key = value`` and ``; key: value`` comments from the G-code start.
|
|
406
|
+
|
|
407
|
+
Stops at the first executable line block, at the end of the config block,
|
|
408
|
+
or after :data:`MAX_GCODE_HEADER_BYTES`. The first occurrence of a key wins.
|
|
409
|
+
"""
|
|
410
|
+
header: dict[str, str] = {}
|
|
411
|
+
consumed = 0
|
|
412
|
+
with archive.open(name) as handle:
|
|
413
|
+
for raw_line in handle:
|
|
414
|
+
consumed += len(raw_line)
|
|
415
|
+
if consumed > MAX_GCODE_HEADER_BYTES:
|
|
416
|
+
break
|
|
417
|
+
line = raw_line.decode("utf-8", errors="replace").strip()
|
|
418
|
+
if not line.startswith(";"):
|
|
419
|
+
continue
|
|
420
|
+
if "EXECUTABLE_BLOCK_START" in line or "CONFIG_BLOCK_END" in line:
|
|
421
|
+
break
|
|
422
|
+
generated = _GENERATED_BY.match(line)
|
|
423
|
+
if generated and "generated_by" not in header:
|
|
424
|
+
header["generated_by_name"] = generated.group(1).strip()
|
|
425
|
+
header["generated_by_version"] = generated.group(2).strip()
|
|
426
|
+
header["generated_by"] = line
|
|
427
|
+
continue
|
|
428
|
+
body = line.lstrip(";").strip()
|
|
429
|
+
for separator in (" = ", ": "):
|
|
430
|
+
if separator in body:
|
|
431
|
+
key, value = body.split(separator, 1)
|
|
432
|
+
header.setdefault(key.strip().lower(), value.strip())
|
|
433
|
+
break
|
|
434
|
+
return header
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _apply_gcode_header(header: dict[str, str], fields: dict[str, object]) -> None:
|
|
438
|
+
if header.get("generated_by_name"):
|
|
439
|
+
fields["slicer_name"] = header["generated_by_name"]
|
|
440
|
+
fields["slicer_version"] = header["generated_by_version"]
|
|
441
|
+
|
|
442
|
+
if "estimated_time_s" not in fields:
|
|
443
|
+
eta = next(
|
|
444
|
+
(
|
|
445
|
+
value
|
|
446
|
+
for key, value in header.items()
|
|
447
|
+
if key.startswith("estimated printing time") and "first layer" not in key
|
|
448
|
+
),
|
|
449
|
+
None,
|
|
450
|
+
)
|
|
451
|
+
if eta is None:
|
|
452
|
+
# Orca-FlashForge before 1.3.0:
|
|
453
|
+
# "; model printing time: 43m 42s; total estimated time: 43m 42s"
|
|
454
|
+
legacy = header.get("model printing time", "")
|
|
455
|
+
if "total estimated time:" in legacy:
|
|
456
|
+
eta = legacy.split("total estimated time:", 1)[1]
|
|
457
|
+
seconds = _parse_duration(eta)
|
|
458
|
+
if seconds is not None:
|
|
459
|
+
fields["estimated_time_s"] = seconds
|
|
460
|
+
|
|
461
|
+
layers = _to_int(header.get("total layer number")) or _to_int(header.get("total layers count"))
|
|
462
|
+
if layers is not None:
|
|
463
|
+
fields["layer_count"] = layers
|
|
464
|
+
|
|
465
|
+
if "total_weight_g" not in fields:
|
|
466
|
+
weight = _to_float(header.get("total filament used [g]"))
|
|
467
|
+
if weight is not None:
|
|
468
|
+
fields["total_weight_g"] = weight
|
|
469
|
+
|
|
470
|
+
if "printer_model_id" not in fields and header.get("printer_model"):
|
|
471
|
+
fields["printer_model_id"] = header["printer_model"]
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _filaments_from_header(header: dict[str, str]) -> list[ThreeMFFilament]:
|
|
475
|
+
"""
|
|
476
|
+
Fall back to the G-code header when slice_info.config lists no filaments.
|
|
477
|
+
|
|
478
|
+
Uses the ``; filament: 1,2`` id list when present, otherwise every filament
|
|
479
|
+
with a non-zero weight in ``; filament used [g]``.
|
|
480
|
+
"""
|
|
481
|
+
grams = [_to_float(part) for part in _split_list(header.get("filament used [g]"))]
|
|
482
|
+
meters_mm = [_to_float(part) for part in _split_list(header.get("filament used [mm]"))]
|
|
483
|
+
types = _split_list(header.get("filament_type"), separator=";")
|
|
484
|
+
colors = _split_list(header.get("filament_colour"), separator=";")
|
|
485
|
+
|
|
486
|
+
ids = [
|
|
487
|
+
value for value in (_to_int(part) for part in _split_list(header.get("filament"))) if value
|
|
488
|
+
]
|
|
489
|
+
if not ids:
|
|
490
|
+
ids = [index + 1 for index, value in enumerate(grams) if value]
|
|
491
|
+
if not ids and len(types) == 1:
|
|
492
|
+
ids = [1]
|
|
493
|
+
|
|
494
|
+
filaments: list[ThreeMFFilament] = []
|
|
495
|
+
for filament_id in sorted(set(ids)):
|
|
496
|
+
index = filament_id - 1
|
|
497
|
+
length_mm = _pick(meters_mm, index)
|
|
498
|
+
filaments.append(
|
|
499
|
+
ThreeMFFilament(
|
|
500
|
+
filament_id=filament_id,
|
|
501
|
+
tool_id=index,
|
|
502
|
+
material_name=(_pick(types, index) or "").strip(),
|
|
503
|
+
color=_normalize_color(_pick(colors, index)),
|
|
504
|
+
used_m=round(length_mm / 1000, 2) if length_mm is not None else None,
|
|
505
|
+
used_g=_pick(grams, index),
|
|
506
|
+
)
|
|
507
|
+
)
|
|
508
|
+
return filaments
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
# --------------------------------------------------------------------------- #
|
|
512
|
+
# Value helpers
|
|
513
|
+
# --------------------------------------------------------------------------- #
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _pick(values: list[_T], index: int) -> _T | None:
|
|
517
|
+
return values[index] if 0 <= index < len(values) else None
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _split_list(value: str | None, separator: str = ",") -> list[str]:
|
|
521
|
+
if not value:
|
|
522
|
+
return []
|
|
523
|
+
return [part.strip().strip('"') for part in value.split(separator)]
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _to_float(value: str | None) -> float | None:
|
|
527
|
+
if value is None:
|
|
528
|
+
return None
|
|
529
|
+
try:
|
|
530
|
+
return float(str(value).strip())
|
|
531
|
+
except ValueError:
|
|
532
|
+
return None
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _to_int(value: str | None) -> int | None:
|
|
536
|
+
number = _to_float(value)
|
|
537
|
+
return int(number) if number is not None else None
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _normalize_color(value: str | None) -> str:
|
|
541
|
+
"""Return ``#RRGGBB`` (upper case) for a usable color, or ``''``."""
|
|
542
|
+
color = (value or "").strip()
|
|
543
|
+
if color and not color.startswith("#"):
|
|
544
|
+
color = f"#{color}"
|
|
545
|
+
if _HEX8.match(color):
|
|
546
|
+
color = color[:7]
|
|
547
|
+
elif _HEX3.match(color):
|
|
548
|
+
color = "#" + "".join(ch * 2 for ch in color[1:])
|
|
549
|
+
return color.upper() if _HEX6.match(color) else ""
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _parse_duration(value: str | None) -> int | None:
|
|
553
|
+
"""Convert ``1d 2h 5m 30s`` style text to seconds."""
|
|
554
|
+
if not value:
|
|
555
|
+
return None
|
|
556
|
+
match = next((m for m in _DURATION.finditer(value) if any(m.groups())), None)
|
|
557
|
+
if match is None:
|
|
558
|
+
return None
|
|
559
|
+
days, hours, minutes, seconds = (int(group) if group else 0 for group in match.groups())
|
|
560
|
+
return ((days * 24 + hours) * 60 + minutes) * 60 + seconds
|