flashforge-python-api 1.5.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 CHANGED
@@ -127,8 +127,21 @@ from .tcp import (
127
127
  FlashForgeTcpClient as TcpClient,
128
128
  )
129
129
 
130
+ # Sliced 3MF parsing (tools and materials before upload)
131
+ from .threemf import (
132
+ PrinterFamily,
133
+ ThreeMFError,
134
+ ThreeMFFilament,
135
+ ThreeMFFile,
136
+ ThreeMFFormatError,
137
+ ThreeMFMultiplePlatesError,
138
+ ThreeMFNotSlicedError,
139
+ ThreeMFWarning,
140
+ parse_3mf,
141
+ )
142
+
130
143
  FiveMClient = FlashForgeClient
131
- __version__ = "1.5.0"
144
+ __version__ = "1.6.0"
132
145
  __author__ = "FlashForge Python API Contributors"
133
146
  __email__ = "notghosttypes@gmail.com"
134
147
  __description__ = "Python library for controlling FlashForge 3D printers"
@@ -164,6 +177,16 @@ __all__ = [
164
177
  "AD5XUploadParams",
165
178
  "GCodeListResponse",
166
179
  "ThumbnailResponse",
180
+ # Sliced 3MF parsing
181
+ "parse_3mf",
182
+ "PrinterFamily",
183
+ "ThreeMFError",
184
+ "ThreeMFFilament",
185
+ "ThreeMFFile",
186
+ "ThreeMFFormatError",
187
+ "ThreeMFMultiplePlatesError",
188
+ "ThreeMFNotSlicedError",
189
+ "ThreeMFWarning",
167
190
  # Control classes for advanced usage
168
191
  "Control",
169
192
  "JobControl",
@@ -2,6 +2,7 @@
2
2
  FlashForge Python API - Job Control Module
3
3
  """
4
4
 
5
+ import asyncio
5
6
  import base64
6
7
  import json
7
8
  import logging
@@ -29,6 +30,26 @@ if TYPE_CHECKING:
29
30
 
30
31
  logger = logging.getLogger(__name__)
31
32
 
33
+ # Uploads can be hundreds of megabytes over printer Wi-Fi, so the aiohttp default
34
+ # (a 5-minute cap on the whole request) is too short. There is no total cap; the
35
+ # connect and response-read limits still catch a printer that stops answering.
36
+ UPLOAD_TIMEOUT = aiohttp.ClientTimeout(total=None, sock_connect=30, sock_read=300)
37
+
38
+
39
+ async def _local_file_size(file_path: str) -> int | None:
40
+ """
41
+ Return the size of a local file, or None if it is not a regular file.
42
+
43
+ Runs in a worker thread: blocking file I/O on the event loop stalls every
44
+ other task, and Home Assistant reports it as an error.
45
+ """
46
+
47
+ def _size() -> int | None:
48
+ path = Path(file_path)
49
+ return path.stat().st_size if path.is_file() else None
50
+
51
+ return await asyncio.to_thread(_size)
52
+
32
53
 
33
54
  class JobControl:
34
55
  """
@@ -137,14 +158,12 @@ class JobControl:
137
158
  Returns:
138
159
  True if the file upload (and optional print start) is successful, False otherwise.
139
160
  """
140
- file_path_obj = Path(file_path)
141
-
142
- if not file_path_obj.exists():
161
+ file_size = await _local_file_size(file_path)
162
+ if file_size is None:
143
163
  logger.warning("upload_file: file not found at %s", file_path)
144
164
  return False
145
165
 
146
- file_size = file_path_obj.stat().st_size
147
- file_name = file_path_obj.name
166
+ file_name = Path(file_path).name
148
167
 
149
168
  logger.debug(
150
169
  "Starting upload for %s (size=%s, start=%s, level=%s)",
@@ -179,8 +198,8 @@ class JobControl:
179
198
  logger.debug("Upload request headers: %s", redact_mapping(custom_headers))
180
199
 
181
200
  # Create multipart form data
182
- async with aiohttp.ClientSession() as session:
183
- with open(file_path, "rb") as f:
201
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
202
+ with await asyncio.to_thread(open, file_path, "rb") as f:
184
203
  data = aiohttp.FormData()
185
204
  data.add_field(
186
205
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -290,13 +309,12 @@ class JobControl:
290
309
  return False
291
310
 
292
311
  # Validate file exists
293
- file_path_obj = Path(params.file_path)
294
- if not file_path_obj.exists():
312
+ file_size = await _local_file_size(params.file_path)
313
+ if file_size is None:
295
314
  logger.warning("upload_file_ad5x: file not found at %s", params.file_path)
296
315
  return False
297
316
 
298
- file_size = file_path_obj.stat().st_size
299
- file_name = file_path_obj.name
317
+ file_name = Path(params.file_path).name
300
318
 
301
319
  logger.debug(
302
320
  "Starting AD5X upload for %s (size=%s, start=%s, level=%s, tools=%s)",
@@ -332,8 +350,8 @@ class JobControl:
332
350
  logger.debug("AD5X upload request headers: %s", redact_mapping(custom_headers))
333
351
 
334
352
  # Create multipart form data
335
- async with aiohttp.ClientSession() as session:
336
- with open(params.file_path, "rb") as f:
353
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
354
+ with await asyncio.to_thread(open, params.file_path, "rb") as f:
337
355
  data = aiohttp.FormData()
338
356
  data.add_field(
339
357
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -536,14 +554,12 @@ class JobControl:
536
554
  Returns:
537
555
  True on success, False otherwise.
538
556
  """
539
- file_path_obj = Path(params.file_path)
540
-
541
- if not file_path_obj.exists():
557
+ file_size = await _local_file_size(params.file_path)
558
+ if file_size is None:
542
559
  logger.warning("upload_file_creator5: file not found at %s", params.file_path)
543
560
  return False
544
561
 
545
- file_size = file_path_obj.stat().st_size
546
- file_name = file_path_obj.name
562
+ file_name = Path(params.file_path).name
547
563
 
548
564
  logger.debug(
549
565
  "Starting Creator 5 upload for %s (size=%s, start=%s, level=%s, "
@@ -589,8 +605,8 @@ class JobControl:
589
605
  logger.debug("Creator 5 upload request headers: %s", redact_mapping(custom_headers))
590
606
 
591
607
  # Create multipart form data
592
- async with aiohttp.ClientSession() as session:
593
- with open(params.file_path, "rb") as f:
608
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
609
+ with await asyncio.to_thread(open, params.file_path, "rb") as f:
594
610
  data = aiohttp.FormData()
595
611
  data.add_field(
596
612
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -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
@@ -0,0 +1,58 @@
1
+ """
2
+ FlashForge Python API - Slicer warning translations
3
+
4
+ Slicers in the OrcaSlicer family (OrcaSlicer, Orca-FlashForge, Flash Studio)
5
+ write slice warnings into ``Metadata/slice_info.config`` as raw i18n keys such
6
+ as ``bed_temperature_too_high_than_filament``, not as display text. This module
7
+ turns those keys into readable sentences. An unknown key falls back to a
8
+ prettified form, so a new warning still reads acceptably.
9
+
10
+ The keys come from OrcaSlicer's ``GCodeProcessor.hpp``, and the wording follows
11
+ ``Plater::get_slice_warning_string()``, so the messages match what the slicer
12
+ itself shows. The table matches ``slicer-meta``'s ``warning-translations.ts``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ _KNOWN_WARNINGS: dict[str, str] = {
18
+ "bed_temperature_too_high_than_filament": (
19
+ "The current hot bed temperature is relatively high. The nozzle may be clogged "
20
+ "when printing this filament in a closed enclosure. Please open the front door "
21
+ "and/or remove the upper glass."
22
+ ),
23
+ "the_actual_nozzle_hrc_smaller_than_the_required_nozzle_hrc": (
24
+ "The nozzle hardness required by the filament is higher than the default nozzle "
25
+ "hardness of the printer. Please replace the hardened nozzle or filament, "
26
+ "otherwise, the nozzle will be attrited or damaged."
27
+ ),
28
+ "not_support_traditional_timelapse": (
29
+ "Enabling traditional timelapse photography may cause surface imperfections. "
30
+ "It is recommended to change to smooth mode."
31
+ ),
32
+ "not_generate_timelapse": "Timelapse will not be generated for this print.",
33
+ "smooth_timelapse_without_prime_tower": (
34
+ "Smooth mode for timelapse is enabled, but the prime tower is off, which may "
35
+ "cause print defects. Please enable the prime tower, re-slice and print again."
36
+ ),
37
+ "activate_long_retraction_when_cut": "Long retraction when cut is enabled for this print.",
38
+ }
39
+
40
+
41
+ def translate_warning(key: str) -> str:
42
+ """
43
+ Translate a raw slicer warning key into readable text.
44
+
45
+ Args:
46
+ key: The warning key as the slicer wrote it.
47
+
48
+ Returns:
49
+ The curated message for a known key, a prettified form of an unknown
50
+ snake_case key, or an empty string for an empty key.
51
+ """
52
+ if not key:
53
+ return ""
54
+ known = _KNOWN_WARNINGS.get(key)
55
+ if known is not None:
56
+ return known
57
+ words = key.replace("_", " ").strip()
58
+ return words[:1].upper() + words[1:] if words else ""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flashforge-python-api
3
- Version: 1.5.0
3
+ Version: 1.6.0
4
4
  Summary: A comprehensive Python library for controlling FlashForge 3D printers
5
5
  Project-URL: Homepage, https://github.com/GhostTypes/ff-5mp-api-py
6
6
  Project-URL: Documentation, https://github.com/GhostTypes/ff-5mp-api-py#readme
@@ -143,6 +143,39 @@ asyncio.run(main())
143
143
  - temperature and motion control, including per-nozzle and chamber temperature control (Creator 5)
144
144
  - LED, camera, and filtration control where supported
145
145
  - AD5X and Creator 5 / Creator 5 Pro material-station, slot configuration, and material mapping
146
+ - sliced 3MF parsing: read the tools, materials, colors, estimates, and thumbnail of a `.3mf` before upload
147
+
148
+ ## Parse a Sliced 3MF
149
+
150
+ A sliced 3MF tells you which filaments (tools) a print uses. The Creator 5 series does not report this for stored files, so read the 3MF before you upload it. Then build one material mapping per filament.
151
+
152
+ ```python
153
+ import asyncio
154
+ from flashforge import AD5XMaterialMapping, parse_3mf
155
+
156
+
157
+ async def build_mappings(path: str) -> list[AD5XMaterialMapping]:
158
+ # parse_3mf is synchronous file I/O, so run it in a worker thread.
159
+ info = await asyncio.to_thread(parse_3mf, path)
160
+ print(f"{info.file_name}: {info.tool_count} tool(s), sliced for {info.printer_family}")
161
+
162
+ mappings = []
163
+ for filament in info.filaments:
164
+ mappings.append(
165
+ AD5XMaterialMapping(
166
+ tool_id=filament.tool_id, # 0-based: filament 1 is tool 0
167
+ slot_id=filament.tool_id + 1, # choose the station slot to print from
168
+ material_name=filament.material_name,
169
+ tool_material_color=filament.color or "#FFFFFF",
170
+ slot_material_color=filament.color or "#FFFFFF",
171
+ )
172
+ )
173
+ return mappings
174
+ ```
175
+
176
+ In a real app, pick `slot_id` and `slot_material_color` from the slots the printer reports. Pass the mappings to `upload_file_creator5` / `start_creator5_job` (Creator 5 series) or `upload_file_ad5x` (AD5X).
177
+
178
+ `parse_3mf` accepts one sliced plate only. A project file with no sliced G-code raises `ThreeMFNotSlicedError`. A file with more than one sliced plate raises `ThreeMFMultiplePlatesError`. All 3MF errors subclass `ThreeMFError`.
146
179
 
147
180
  ## Documentation
148
181
 
@@ -1,4 +1,4 @@
1
- flashforge/__init__.py,sha256=dDzpUX4K063NRYBvhj1QkfFxxQpb1aSMMkSEFQTzxhI,5472
1
+ flashforge/__init__.py,sha256=HojGIgobrlO5Qr9mzrHhFeuVq5a1otJPDMBa9AFuKBM,5984
2
2
  flashforge/client.py,sha256=5DxKJyicq5LX8xfZUtIB0Q-_sh8kIFNzMMV_3Dos5fk,22519
3
3
  flashforge/exceptions.py,sha256=LQli1pAH2X8fm3jsRD4caz0Mn-nyBjNpaJh_En7YJw0,1737
4
4
  flashforge/api/__init__.py,sha256=vQz-DkG6LTH39bI4fyiUc0D9jQzemLh45pORLptSOlg,335
@@ -10,7 +10,7 @@ flashforge/api/controls/control.py,sha256=mK-k3SX53wrq3-aPmMaAbAnqcOaJgvuNSR-sm1
10
10
  flashforge/api/controls/creator5_palette.py,sha256=1I6QfAYlCJcpqPzrySsXfn2EST04QYHZKVxCRnxu4AQ,8795
11
11
  flashforge/api/controls/files.py,sha256=tOqPgf9SBIvJBgno1GMAROdoDHF_ZJOmbEac1ikq_HI,8769
12
12
  flashforge/api/controls/info.py,sha256=E-VepEeTyquh50ssckpMGIkH9cagNZGUzn_Zb-bPplY,24846
13
- flashforge/api/controls/job_control.py,sha256=e_8A1-avghNGQ3OBzTbScDnUCUOJobdiulFCyXtyb8w,35294
13
+ flashforge/api/controls/job_control.py,sha256=-6UafeTpjYOs5gIVAHbQyTUROErJs4XW8lpI6HsLJgM,36119
14
14
  flashforge/api/controls/temp_control.py,sha256=_qrKCfjKJsPE4dj6bXZeJRH2FjLKx2T2V3pyG2oLrgI,12991
15
15
  flashforge/api/filament/__init__.py,sha256=isT2dl0hzUS0xMTXMm4Tip0GTG1gCsm8LKWa9xPu4Y8,104
16
16
  flashforge/api/filament/filament.py,sha256=TtcC2G2nD9Sq4cOrCZzFLZ6Q0Ve-zfrfuEF9uQ8M3eE,1214
@@ -42,8 +42,11 @@ flashforge/tcp/parsers/print_status.py,sha256=C-KzukhK0TR86AP3t3XrMH4dief6pa3I-y
42
42
  flashforge/tcp/parsers/printer_info.py,sha256=CHPs6nJfEByXyG3co7Nb8_ygggxkYuc7A9O9bpQEqXE,5441
43
43
  flashforge/tcp/parsers/temp_info.py,sha256=9wRGUM9cKvDiZD3SIxBx_qVLZbeXoYsoY3-R3vN3H4g,7938
44
44
  flashforge/tcp/parsers/thumbnail_info.py,sha256=1U1S_gcIZ2lDpEA4622ywUew6TVw0BnzjlBAiihQwzk,10478
45
- flashforge_python_api-1.5.0.dist-info/METADATA,sha256=hpoGseNvotHfDNDJXpItMUbp9Ehr75sj-wgOgO2jfDU,4970
46
- flashforge_python_api-1.5.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
47
- flashforge_python_api-1.5.0.dist-info/entry_points.txt,sha256=AkOxlsLvQ7cvMLxn7tlzfKp_DCH2hXhbVceHIXxawpU,66
48
- flashforge_python_api-1.5.0.dist-info/licenses/LICENSE,sha256=-cTA-hrmvlb3pqlQrBZQXUnKayhUjsLJMPb7TD91frM,1067
49
- flashforge_python_api-1.5.0.dist-info/RECORD,,
45
+ flashforge/threemf/__init__.py,sha256=xjoHiyl-RFvzMCGeZ00K197d01ZO7-j2o15Xy0ns96Y,900
46
+ flashforge/threemf/parser.py,sha256=mr-FJ2_Zs__VcBwPZvQXUPtBEuKUB-2fcMMaKOQYYOE,20987
47
+ flashforge/threemf/warnings.py,sha256=-8o7VhdaXqaOpx4ZH-A5kYybWJZepqRxmScVV3d-UzA,2472
48
+ flashforge_python_api-1.6.0.dist-info/METADATA,sha256=22juPUjzsx7czIfPWSgH13A846vO1Mf09_IMtibg7cw,6619
49
+ flashforge_python_api-1.6.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
50
+ flashforge_python_api-1.6.0.dist-info/entry_points.txt,sha256=AkOxlsLvQ7cvMLxn7tlzfKp_DCH2hXhbVceHIXxawpU,66
51
+ flashforge_python_api-1.6.0.dist-info/licenses/LICENSE,sha256=-cTA-hrmvlb3pqlQrBZQXUnKayhUjsLJMPb7TD91frM,1067
52
+ flashforge_python_api-1.6.0.dist-info/RECORD,,