flashforge-python-api 1.5.0__py3-none-any.whl → 3.0.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.
Files changed (71) hide show
  1. flashforge/__init__.py +337 -233
  2. flashforge/_removed.py +65 -0
  3. flashforge/api/__init__.py +12 -18
  4. flashforge/api/constants/__init__.py +11 -11
  5. flashforge/api/constants/commands.py +18 -15
  6. flashforge/api/constants/endpoints.py +11 -11
  7. flashforge/api/misc/__init__.py +8 -8
  8. flashforge/api/network/__init__.py +11 -11
  9. flashforge/api/network/utils.py +71 -71
  10. flashforge/backends/__init__.py +80 -0
  11. flashforge/backends/connect.py +275 -0
  12. flashforge/backends/creator5_backend.py +191 -0
  13. flashforge/backends/dual_api_backend.py +170 -0
  14. flashforge/backends/dual_api_models.py +145 -0
  15. flashforge/backends/http_core.py +431 -0
  16. flashforge/backends/http_printer_backend.py +254 -0
  17. flashforge/backends/legacy_backend.py +436 -0
  18. flashforge/backends/printer_backend.py +217 -0
  19. flashforge/backends/types.py +125 -0
  20. flashforge/capabilities/__init__.py +98 -0
  21. flashforge/capabilities/models.py +67 -0
  22. flashforge/capabilities/palettes/__init__.py +28 -0
  23. flashforge/capabilities/palettes/ad5x_palette.py +70 -0
  24. flashforge/capabilities/palettes/creator5_palette.py +78 -0
  25. flashforge/capabilities/palettes/palette.py +54 -0
  26. flashforge/{api/controls/creator5_palette.py → capabilities/palettes/palette_snap.py} +226 -258
  27. flashforge/capabilities/printer_capabilities.py +145 -0
  28. flashforge/capabilities/registry.py +125 -0
  29. flashforge/capabilities/resolve_model.py +61 -0
  30. flashforge/discovery/__init__.py +39 -39
  31. flashforge/discovery/discovery.py +730 -763
  32. flashforge/exceptions.py +90 -51
  33. flashforge/models/__init__.py +52 -55
  34. flashforge/models/machine_info.py +540 -543
  35. flashforge/{api/controls/info.py → models/machine_info_parser.py} +35 -242
  36. flashforge/models/responses.py +119 -254
  37. flashforge/status/__init__.py +43 -0
  38. flashforge/status/printer_snapshot.py +396 -0
  39. flashforge/tcp/__init__.py +55 -54
  40. flashforge/tcp/a3_client.py +427 -427
  41. flashforge/tcp/a4_client.py +304 -304
  42. flashforge/tcp/ff_client.py +609 -590
  43. flashforge/tcp/gcode/__init__.py +15 -13
  44. flashforge/tcp/gcode/a3_gcode_controller.py +109 -109
  45. flashforge/tcp/gcode/gcode_controller.py +292 -308
  46. flashforge/tcp/gcode/gcodes.py +81 -99
  47. flashforge/tcp/gcode/legacy_gcode_controller.py +56 -0
  48. flashforge/tcp/parsers/__init__.py +27 -27
  49. flashforge/tcp/parsers/endstop_status.py +248 -248
  50. flashforge/tcp/parsers/location_info.py +83 -83
  51. flashforge/tcp/parsers/print_status.py +180 -180
  52. flashforge/tcp/parsers/printer_info.py +146 -146
  53. flashforge/tcp/parsers/temp_info.py +218 -218
  54. flashforge/tcp/parsers/thumbnail_info.py +274 -274
  55. flashforge/tcp/tcp_client.py +52 -12
  56. flashforge/threemf/__init__.py +40 -0
  57. flashforge/threemf/parser.py +560 -0
  58. flashforge/threemf/warnings.py +58 -0
  59. flashforge_python_api-3.0.0.dist-info/METADATA +184 -0
  60. flashforge_python_api-3.0.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.5.0.dist-info → flashforge_python_api-3.0.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.5.0.dist-info → flashforge_python_api-3.0.0.dist-info}/licenses/LICENSE +21 -21
  63. flashforge/api/controls/__init__.py +0 -17
  64. flashforge/api/controls/control.py +0 -413
  65. flashforge/api/controls/files.py +0 -210
  66. flashforge/api/controls/job_control.py +0 -880
  67. flashforge/api/controls/temp_control.py +0 -309
  68. flashforge/client.py +0 -609
  69. flashforge_python_api-1.5.0.dist-info/METADATA +0 -152
  70. flashforge_python_api-1.5.0.dist-info/RECORD +0 -49
  71. {flashforge_python_api-1.5.0.dist-info → flashforge_python_api-3.0.0.dist-info}/entry_points.txt +0 -0
@@ -1,880 +0,0 @@
1
- """
2
- FlashForge Python API - Job Control Module
3
- """
4
-
5
- import base64
6
- import json
7
- import logging
8
- import re
9
- from pathlib import Path
10
- from typing import TYPE_CHECKING, Any
11
-
12
- import aiohttp
13
-
14
- from ...models.responses import (
15
- AD5XLocalJobParams,
16
- AD5XMaterialMapping,
17
- AD5XSingleColorJobParams,
18
- AD5XUploadParams,
19
- Creator5JobParams,
20
- Creator5UploadParams,
21
- )
22
- from ..constants.endpoints import Endpoints
23
- from ..misc.redaction import redact_mapping
24
- from ..network.utils import NetworkUtils, json_from_response
25
-
26
- if TYPE_CHECKING:
27
- from ...client import FlashForgeClient
28
- from .control import Control
29
-
30
- logger = logging.getLogger(__name__)
31
-
32
-
33
- class JobControl:
34
- """
35
- Provides methods for managing print jobs on the FlashForge 3D printer.
36
- This includes pausing, resuming, canceling prints, uploading files for printing,
37
- and starting prints from local files.
38
- """
39
-
40
- def __init__(self, client: "FlashForgeClient"):
41
- """
42
- Creates an instance of the JobControl class.
43
-
44
- Args:
45
- client: The FlashForgeClient instance used for communication with the printer.
46
- """
47
- self.client = client
48
- self._control: Control | None = None
49
-
50
- @property
51
- def control(self) -> "Control":
52
- """Get the control instance."""
53
- if self._control is None:
54
- self._control = self.client.control
55
- return self._control
56
-
57
- async def pause_print_job(self) -> bool:
58
- """
59
- Pauses the current print job.
60
-
61
- Returns:
62
- True if the command is successful, False otherwise.
63
- """
64
- return await self.control.send_job_control_cmd("pause")
65
-
66
- async def resume_print_job(self) -> bool:
67
- """
68
- Resumes a paused print job.
69
-
70
- Returns:
71
- True if the command is successful, False otherwise.
72
- """
73
- return await self.control.send_job_control_cmd("continue")
74
-
75
- async def cancel_print_job(self) -> bool:
76
- """
77
- Cancels the current print job.
78
-
79
- Returns:
80
- True if the command is successful, False otherwise.
81
- """
82
- return await self.control.send_job_control_cmd("cancel")
83
-
84
- def _is_new_firmware_version(self) -> bool:
85
- """
86
- Checks if the printer's firmware version is 3.1.3 or newer.
87
- This is used to determine which API payload format to use for certain commands.
88
-
89
- Returns:
90
- True if the firmware is new (>= 3.1.3), False otherwise or if version cannot be determined.
91
- """
92
- # The 3.1.3 threshold only applies to the 5M family. The AD5X and Creator 5
93
- # series always use the new payload/header format, and their firmware
94
- # versioning isn't comparable to the 5M's 3.x line (e.g. the C5 reports
95
- # 1.9.2, which the numeric check below would wrongly read as "old"), so
96
- # short-circuit to the new format for them.
97
- if self.client.is_ad5x or self.client.is_creator5 or self.client.is_creator5_pro:
98
- return True
99
- try:
100
- current_version = self.client.firmware_ver.split(".")
101
- min_version = [3, 1, 3]
102
-
103
- for i in range(3):
104
- current = int(current_version[i] if i < len(current_version) else "0")
105
- if current > min_version[i]:
106
- return True
107
- if current < min_version[i]:
108
- return False
109
-
110
- return True # Equal versions
111
- except Exception:
112
- return False
113
-
114
- async def clear_platform(self) -> bool:
115
- """
116
- Sends a command to clear the printer's build platform.
117
-
118
- Returns:
119
- True if the command is successful, False otherwise.
120
- """
121
- args = {"action": "setClearPlatform"}
122
-
123
- return await self.control.send_control_command("stateCtrl_cmd", args)
124
-
125
- async def upload_file(
126
- self, file_path: str, start_print: bool, level_before_print: bool
127
- ) -> bool:
128
- """
129
- Uploads a G-code or 3MF file to the printer and optionally starts printing.
130
- It handles different API requirements based on the printer's firmware version.
131
-
132
- Args:
133
- file_path: The local path to the G-code or 3MF file to upload.
134
- start_print: If True, the printer will start printing the file immediately after upload.
135
- level_before_print: If True, the printer will perform bed leveling before starting the print.
136
-
137
- Returns:
138
- True if the file upload (and optional print start) is successful, False otherwise.
139
- """
140
- file_path_obj = Path(file_path)
141
-
142
- if not file_path_obj.exists():
143
- logger.warning("upload_file: file not found at %s", file_path)
144
- return False
145
-
146
- file_size = file_path_obj.stat().st_size
147
- file_name = file_path_obj.name
148
-
149
- logger.debug(
150
- "Starting upload for %s (size=%s, start=%s, level=%s)",
151
- file_name,
152
- file_size,
153
- start_print,
154
- level_before_print,
155
- )
156
-
157
- try:
158
- # Prepare the custom HTTP headers with metadata
159
- custom_headers = {
160
- "serialNumber": self.client.serial_number,
161
- "checkCode": self.client.check_code,
162
- "fileSize": str(file_size),
163
- "printNow": str(start_print).lower(),
164
- "levelingBeforePrint": str(level_before_print).lower(),
165
- "Expect": "100-continue",
166
- }
167
-
168
- # Add additional headers for new firmware
169
- if self._is_new_firmware_version():
170
- logger.debug("Using new firmware headers for upload.")
171
- custom_headers["flowCalibration"] = "false"
172
- custom_headers["useMatlStation"] = "false"
173
- custom_headers["gcodeToolCnt"] = "0"
174
- # Base64 encode "[]" which is "W10="
175
- custom_headers["materialMappings"] = "W10="
176
- else:
177
- logger.debug("Using old firmware headers for upload.")
178
-
179
- logger.debug("Upload request headers: %s", redact_mapping(custom_headers))
180
-
181
- # Create multipart form data
182
- async with aiohttp.ClientSession() as session:
183
- with open(file_path, "rb") as f:
184
- data = aiohttp.FormData()
185
- data.add_field(
186
- "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
187
- )
188
-
189
- async with session.post(
190
- self.client.get_endpoint(Endpoints.UPLOAD_FILE),
191
- data=data,
192
- headers=custom_headers,
193
- ) as response:
194
- logger.debug("Upload response status: %s", response.status)
195
-
196
- if response.status != 200:
197
- logger.warning(
198
- "Upload failed: the printer responded with status %s",
199
- response.status,
200
- )
201
- return False
202
-
203
- result = await json_from_response(response)
204
- logger.debug("Upload response data: %s", result)
205
-
206
- if NetworkUtils.is_ok(result):
207
- logger.debug("Upload successful according to the printer response.")
208
- return True
209
- else:
210
- logger.warning(
211
- "Upload failed: printer response code=%s, message=%s",
212
- result.get("code"),
213
- result.get("message"),
214
- )
215
- return False
216
-
217
- except Exception as e:
218
- logger.warning("upload_file error: %s", e)
219
- return False
220
-
221
- async def print_local_file(self, file_name: str, leveling_before_print: bool) -> bool:
222
- """
223
- Starts printing a file that is already stored locally on the printer.
224
- It handles different API payload formats based on the printer's firmware version.
225
-
226
- Args:
227
- file_name: The name of the file on the printer (e.g., "my_model.gcode") to print.
228
- leveling_before_print: If True, the printer will perform bed leveling before starting the print.
229
-
230
- Returns:
231
- True if the print command is successfully sent and acknowledged, False otherwise.
232
- """
233
- if self._is_new_firmware_version():
234
- # New format for firmware >= 3.1.3
235
- payload = {
236
- "serialNumber": self.client.serial_number,
237
- "checkCode": self.client.check_code,
238
- "fileName": file_name,
239
- "levelingBeforePrint": leveling_before_print,
240
- "flowCalibration": False,
241
- "useMatlStation": False,
242
- "gcodeToolCnt": 0,
243
- "materialMappings": [], # Empty array for materialMappings
244
- }
245
- else:
246
- # Old format for firmware < 3.1.3
247
- payload = {
248
- "serialNumber": self.client.serial_number,
249
- "checkCode": self.client.check_code,
250
- "fileName": file_name,
251
- "levelingBeforePrint": leveling_before_print,
252
- }
253
-
254
- try:
255
- session = await self.client.get_http_session()
256
- async with self.client.command_lock:
257
- async with session.post(
258
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
259
- json=payload,
260
- headers={"Content-Type": "application/json"},
261
- ) as response:
262
- if response.status != 200:
263
- return False
264
-
265
- result = await json_from_response(response)
266
- return NetworkUtils.is_ok(result)
267
-
268
- except Exception as error:
269
- logger.warning("print_local_file error: %s", error)
270
- raise error
271
-
272
- async def upload_file_ad5x(self, params: AD5XUploadParams) -> bool:
273
- """
274
- Uploads a G-code or 3MF file to AD5X printer with material station support.
275
- Handles material mappings, flow calibration, and other AD5X-specific features.
276
- Material mappings are base64-encoded in HTTP headers according to AD5X API requirements.
277
-
278
- Args:
279
- params: AD5X upload parameters including file path, print options, and material mappings
280
-
281
- Returns:
282
- True if the file upload is successful, False otherwise
283
- """
284
- # Validate that this is an AD5X printer
285
- if not self._validate_ad5x_printer():
286
- return False
287
-
288
- # Validate material mappings
289
- if not self._validate_material_mappings(params.material_mappings):
290
- return False
291
-
292
- # Validate file exists
293
- file_path_obj = Path(params.file_path)
294
- if not file_path_obj.exists():
295
- logger.warning("upload_file_ad5x: file not found at %s", params.file_path)
296
- return False
297
-
298
- file_size = file_path_obj.stat().st_size
299
- file_name = file_path_obj.name
300
-
301
- logger.debug(
302
- "Starting AD5X upload for %s (size=%s, start=%s, level=%s, tools=%s)",
303
- file_name,
304
- file_size,
305
- params.start_print,
306
- params.leveling_before_print,
307
- len(params.material_mappings),
308
- )
309
-
310
- try:
311
- # Encode material mappings to base64
312
- material_mappings_base64 = self._encode_material_mappings_to_base64(
313
- params.material_mappings
314
- )
315
-
316
- # Prepare AD5X-specific HTTP headers
317
- custom_headers = {
318
- "serialNumber": self.client.serial_number,
319
- "checkCode": self.client.check_code,
320
- "fileSize": str(file_size),
321
- "printNow": str(params.start_print).lower(),
322
- "levelingBeforePrint": str(params.leveling_before_print).lower(),
323
- "flowCalibration": str(params.flow_calibration).lower(),
324
- "firstLayerInspection": str(params.first_layer_inspection).lower(),
325
- "timeLapseVideo": str(params.time_lapse_video).lower(),
326
- "useMatlStation": "true", # Always true for AD5X uploads with material mappings
327
- "gcodeToolCnt": str(len(params.material_mappings)),
328
- "materialMappings": material_mappings_base64,
329
- "Expect": "100-continue",
330
- }
331
-
332
- logger.debug("AD5X upload request headers: %s", redact_mapping(custom_headers))
333
-
334
- # Create multipart form data
335
- async with aiohttp.ClientSession() as session:
336
- with open(params.file_path, "rb") as f:
337
- data = aiohttp.FormData()
338
- data.add_field(
339
- "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
340
- )
341
-
342
- async with session.post(
343
- self.client.get_endpoint(Endpoints.UPLOAD_FILE),
344
- data=data,
345
- headers=custom_headers,
346
- ) as response:
347
- logger.debug("AD5X upload response status: %s", response.status)
348
-
349
- if response.status != 200:
350
- logger.warning(
351
- "AD5X upload failed: the printer responded with status %s",
352
- response.status,
353
- )
354
- return False
355
-
356
- result = await json_from_response(response)
357
- logger.debug("AD5X upload response data: %s", result)
358
-
359
- if NetworkUtils.is_ok(result):
360
- logger.debug(
361
- "AD5X upload successful according to the printer response."
362
- )
363
- return True
364
- else:
365
- logger.warning(
366
- "AD5X upload failed: printer response code=%s, message=%s",
367
- result.get("code"),
368
- result.get("message"),
369
- )
370
- return False
371
-
372
- except Exception as e:
373
- logger.warning("upload_file_ad5x error: %s", e)
374
- return False
375
-
376
- async def start_ad5x_multi_color_job(self, params: AD5XLocalJobParams) -> bool:
377
- """
378
- Starts a multi-color local print job on AD5X printers with material mappings.
379
- This method automatically configures the material station settings and validates
380
- all parameters before sending the print command.
381
-
382
- Args:
383
- params: Job parameters including file name, leveling option, and material mappings
384
-
385
- Returns:
386
- True if successful, False if validation fails or printer rejects
387
- """
388
- # Validate that this is an AD5X printer
389
- if not self._validate_ad5x_printer():
390
- return False
391
-
392
- # Validate material mappings
393
- if not self._validate_material_mappings(params.material_mappings):
394
- return False
395
-
396
- # Validate file name
397
- if not params.file_name or params.file_name.strip() == "":
398
- logger.warning("AD5X multi-color job: fileName cannot be empty.")
399
- return False
400
-
401
- # Create payload with AD5X-specific parameters
402
- payload = {
403
- "serialNumber": self.client.serial_number,
404
- "checkCode": self.client.check_code,
405
- "fileName": params.file_name,
406
- "levelingBeforePrint": params.leveling_before_print,
407
- "firstLayerInspection": False,
408
- "flowCalibration": False,
409
- "timeLapseVideo": False,
410
- "useMatlStation": True, # Automatically set to true for multi-color jobs
411
- "gcodeToolCnt": len(params.material_mappings), # Set based on material mappings count
412
- "materialMappings": [
413
- {
414
- "toolId": m.tool_id,
415
- "slotId": m.slot_id,
416
- "materialName": m.material_name,
417
- "toolMaterialColor": m.tool_material_color,
418
- "slotMaterialColor": m.slot_material_color,
419
- }
420
- for m in params.material_mappings
421
- ],
422
- }
423
-
424
- try:
425
- session = await self.client.get_http_session()
426
- async with self.client.command_lock:
427
- async with session.post(
428
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
429
- json=payload,
430
- headers={"Content-Type": "application/json"},
431
- ) as response:
432
- if response.status != 200:
433
- return False
434
-
435
- result = await json_from_response(response)
436
- return NetworkUtils.is_ok(result)
437
-
438
- except Exception as error:
439
- logger.warning("AD5X multi-color job error: %s", error)
440
- raise error
441
-
442
- async def start_ad5x_single_color_job(self, params: AD5XSingleColorJobParams) -> bool:
443
- """
444
- Starts a single-color local print job on AD5X printers.
445
- This method automatically configures the printer for single-color printing
446
- without using the material station.
447
-
448
- Args:
449
- params: Job parameters including file name and leveling option
450
-
451
- Returns:
452
- True if successful, False if validation fails or printer rejects
453
- """
454
- # Validate that this is an AD5X printer
455
- if not self._validate_ad5x_printer():
456
- return False
457
-
458
- # Validate file name
459
- if not params.file_name or params.file_name.strip() == "":
460
- logger.warning("AD5X single-color job: fileName cannot be empty.")
461
- return False
462
-
463
- # Create payload with AD5X-specific parameters for single-color printing
464
- payload = {
465
- "serialNumber": self.client.serial_number,
466
- "checkCode": self.client.check_code,
467
- "fileName": params.file_name,
468
- "levelingBeforePrint": params.leveling_before_print,
469
- "firstLayerInspection": False,
470
- "flowCalibration": False,
471
- "timeLapseVideo": False,
472
- "useMatlStation": False, # Set to false for single-color jobs
473
- "gcodeToolCnt": 0, # Set to 0 for single-color jobs
474
- "materialMappings": [], # Empty array for single-color jobs
475
- }
476
-
477
- try:
478
- session = await self.client.get_http_session()
479
- async with self.client.command_lock:
480
- async with session.post(
481
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
482
- json=payload,
483
- headers={"Content-Type": "application/json"},
484
- ) as response:
485
- if response.status != 200:
486
- return False
487
-
488
- result = await json_from_response(response)
489
- return NetworkUtils.is_ok(result)
490
-
491
- except Exception as error:
492
- logger.warning("AD5X single-color job error: %s", error)
493
- raise error
494
-
495
- # --- Creator 5 / Creator 5 Pro ---
496
- # The Creator 5 firmware applies material mappings in two places:
497
- # - POST /printGcode reads `materialMappings` for any file already on the
498
- # printer (see start_creator5_job). This is the recommended path: upload
499
- # with start_print=False, then start with the mappings.
500
- # - POST /uploadGcode also reads a base64 `materialMappings` header, the
501
- # same format as the AD5X, and applies it when `printNow` is true.
502
- # The firmware only logs `useMatlStation` and `gcodeToolCnt` on upload; they
503
- # have no effect. There is NO `firstLayerInspection` header (the field doesn't
504
- # exist on the C5), and the booleans are checked as the string "true"/"false".
505
- #
506
- # Mappings only take effect for a .3mf file. Without mappings, tool N prints
507
- # from the slot with the slicer's filament number (filament 1 -> slot 1),
508
- # whatever is loaded there. Send a mapping for every tool, including a
509
- # single-tool print.
510
-
511
- async def upload_file_creator5(self, params: Creator5UploadParams) -> bool:
512
- """
513
- Uploads a file (.gcode or .3mf) to a Creator 5 / Creator 5 Pro via
514
- ``POST /uploadGcode``, with the C5-specific material-station headers.
515
-
516
- Recommended flow: upload with ``start_print=False``, then call
517
- :meth:`start_creator5_job` with a mapping for every tool. To start in one
518
- request instead, pass ``material_mappings`` with ``start_print=True``: the
519
- firmware reads them from a base64 ``materialMappings`` header, like the
520
- AD5X.
521
-
522
- ``material_mappings`` is sent only when ``start_print`` is true. The
523
- firmware keeps upload mappings in memory until the next print ends, so
524
- mappings on an upload that does not start would apply to a later,
525
- unrelated print.
526
-
527
- ``useMatlStation`` and ``gcodeToolCnt`` are sent for parity with
528
- FlashForge's own clients; the firmware only logs them. Unlike
529
- :meth:`upload_file_ad5x` this sends no ``firstLayerInspection`` header
530
- (the C5 has no such field). Booleans are sent as the string
531
- "true"/"false".
532
-
533
- Args:
534
- params: Creator 5 upload parameters.
535
-
536
- Returns:
537
- True on success, False otherwise.
538
- """
539
- file_path_obj = Path(params.file_path)
540
-
541
- if not file_path_obj.exists():
542
- logger.warning("upload_file_creator5: file not found at %s", params.file_path)
543
- return False
544
-
545
- file_size = file_path_obj.stat().st_size
546
- file_name = file_path_obj.name
547
-
548
- logger.debug(
549
- "Starting Creator 5 upload for %s (size=%s, start=%s, level=%s, "
550
- "matl_station=%s, tools=%s)",
551
- file_name,
552
- file_size,
553
- params.start_print,
554
- params.leveling_before_print,
555
- params.use_matl_station,
556
- params.gcode_tool_cnt,
557
- )
558
-
559
- try:
560
- # C5 upload headers. No firstLayerInspection (absent on the C5);
561
- # booleans sent as "true"/"false" (firmware checks for "true").
562
- custom_headers = {
563
- "serialNumber": self.client.serial_number,
564
- "checkCode": self.client.check_code,
565
- "fileSize": str(file_size),
566
- "printNow": str(params.start_print).lower(),
567
- "levelingBeforePrint": str(params.leveling_before_print).lower(),
568
- "flowCalibration": str(params.flow_calibration).lower(),
569
- "timeLapseVideo": str(params.time_lapse_video).lower(),
570
- "useMatlStation": str(params.use_matl_station).lower(),
571
- "gcodeToolCnt": str(params.gcode_tool_cnt),
572
- "Expect": "100-continue",
573
- }
574
-
575
- mappings = params.material_mappings or []
576
- if mappings:
577
- if not params.start_print:
578
- logger.warning(
579
- "upload_file_creator5: material_mappings ignored because start_print "
580
- "is False; pass them to start_creator5_job instead."
581
- )
582
- else:
583
- if not self._validate_creator5_material_mappings(mappings):
584
- return False
585
- custom_headers["materialMappings"] = self._encode_material_mappings_to_base64(
586
- mappings
587
- )
588
-
589
- logger.debug("Creator 5 upload request headers: %s", redact_mapping(custom_headers))
590
-
591
- # Create multipart form data
592
- async with aiohttp.ClientSession() as session:
593
- with open(params.file_path, "rb") as f:
594
- data = aiohttp.FormData()
595
- data.add_field(
596
- "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
597
- )
598
-
599
- async with session.post(
600
- self.client.get_endpoint(Endpoints.UPLOAD_FILE),
601
- data=data,
602
- headers=custom_headers,
603
- ) as response:
604
- logger.debug("Creator 5 upload response status: %s", response.status)
605
-
606
- if response.status != 200:
607
- logger.warning(
608
- "Creator 5 upload failed: the printer responded with status %s",
609
- response.status,
610
- )
611
- return False
612
-
613
- result = await json_from_response(response)
614
- logger.debug("Creator 5 upload response data: %s", result)
615
-
616
- if NetworkUtils.is_ok(result):
617
- logger.debug(
618
- "Creator 5 upload successful according to the printer response."
619
- )
620
- return True
621
-
622
- logger.warning(
623
- "Creator 5 upload failed: printer response code=%s, message=%s",
624
- result.get("code"),
625
- result.get("message"),
626
- )
627
- return False
628
-
629
- except Exception as e:
630
- logger.warning("upload_file_creator5 error: %s", e)
631
- return False
632
-
633
- async def start_creator5_job(self, params: Creator5JobParams) -> bool:
634
- """
635
- Starts a local print on a Creator 5 / Creator 5 Pro via ``POST /printGcode``.
636
-
637
- This is the Creator 5's print-start material-matching command. The file
638
- must already be on the printer; it can be a file uploaded long before, not
639
- only the last upload. Sends only the fields the Creator 5 firmware reads:
640
- NO ``useMatlStation`` / ``gcodeToolCnt`` and NO ``firstLayerInspection``
641
- (doesn't exist on the C5). ``flowCalibration`` and ``timeLapseVideo`` are
642
- always present (default False).
643
-
644
- Provide a mapping for every tool, including a single-tool print. Without
645
- mappings the firmware prints each tool from the slot with the slicer's
646
- filament number (filament 1 -> slot 1), whatever is loaded there.
647
- Mappings take effect only for a .3mf file.
648
-
649
- Args:
650
- params: File name, leveling flag, and optional flags / material mappings.
651
-
652
- Returns:
653
- True if the printer accepts the print command, False if validation
654
- fails or the printer rejects it.
655
-
656
- Raises:
657
- Exception: On a network failure sending the command.
658
- """
659
- if not self._validate_material_station_printer():
660
- return False
661
-
662
- if not params.file_name or params.file_name.strip() == "":
663
- logger.warning("Creator 5 job: fileName cannot be empty.")
664
- return False
665
-
666
- has_mappings = params.material_mappings is not None and len(params.material_mappings) > 0
667
- if has_mappings and not self._validate_creator5_material_mappings(
668
- params.material_mappings or []
669
- ):
670
- return False
671
-
672
- payload: dict[str, Any] = {
673
- "serialNumber": self.client.serial_number,
674
- "checkCode": self.client.check_code,
675
- "fileName": params.file_name,
676
- "levelingBeforePrint": params.leveling_before_print,
677
- "flowCalibration": params.flow_calibration,
678
- "timeLapseVideo": params.time_lapse_video,
679
- }
680
- if has_mappings:
681
- payload["materialMappings"] = [
682
- {
683
- "toolId": m.tool_id,
684
- "slotId": m.slot_id,
685
- "materialName": m.material_name,
686
- "toolMaterialColor": m.tool_material_color,
687
- "slotMaterialColor": m.slot_material_color,
688
- }
689
- for m in params.material_mappings or []
690
- ]
691
-
692
- try:
693
- session = await self.client.get_http_session()
694
- async with self.client.command_lock:
695
- async with session.post(
696
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
697
- json=payload,
698
- headers={"Content-Type": "application/json"},
699
- ) as response:
700
- if response.status != 200:
701
- return False
702
-
703
- result = await json_from_response(response)
704
- return NetworkUtils.is_ok(result)
705
-
706
- except Exception as error:
707
- logger.warning("Creator 5 job error: %s", error)
708
- raise error
709
-
710
- def _validate_material_station_printer(self) -> bool:
711
- """
712
- Validates that the current printer has a material station and therefore
713
- supports material-mapping uploads/jobs. Covers AD5X and the Creator 5
714
- series, which share the same material-mapping print flow (Creator 5 =
715
- "AD5X + more").
716
-
717
- Returns:
718
- True if the printer supports material mappings, False otherwise.
719
- """
720
- if not self.client.is_ad5x and not self.client.is_creator5:
721
- logger.warning(
722
- "Material-station job: this method requires an AD5X or Creator 5 series printer."
723
- )
724
- return False
725
- return True
726
-
727
- def _validate_creator5_material_mappings(
728
- self, material_mappings: list[AD5XMaterialMapping]
729
- ) -> bool:
730
- """
731
- Validates Creator 5 material mappings. Delegates to the shared validator
732
- with ``allow_empty=True`` (the C5 uses an empty array for the
733
- single-tool print start).
734
-
735
- Args:
736
- material_mappings: Array of Creator 5 mappings to validate.
737
-
738
- Returns:
739
- True if all mappings are valid, False otherwise.
740
- """
741
- return self._validate_mappings(
742
- material_mappings, allow_empty=True, label="Creator 5 material mappings"
743
- )
744
-
745
- def _validate_mappings(
746
- self,
747
- material_mappings: list[AD5XMaterialMapping],
748
- *,
749
- allow_empty: bool,
750
- label: str,
751
- ) -> bool:
752
- """
753
- Shared material-mapping validator used by both the AD5X and Creator 5
754
- flows. Checks toolId 0-3, slotId 1-4, non-empty materialName, and
755
- ``#RRGGBB`` tool/slot colors.
756
-
757
- Args:
758
- material_mappings: Array of mappings to validate.
759
- allow_empty: If True, an empty array is accepted (Creator 5
760
- single-tool start). If False, an empty array is rejected
761
- (AD5X multi-color jobs require at least one mapping).
762
- label: Prefix for the printed validation-error messages.
763
-
764
- Returns:
765
- True if all mappings are valid, False otherwise.
766
- """
767
- if not material_mappings or len(material_mappings) == 0:
768
- if allow_empty:
769
- return True
770
- logger.warning("%s: materialMappings cannot be empty for multi-color jobs.", label)
771
- return False
772
-
773
- if len(material_mappings) > 4:
774
- logger.warning("%s: a maximum of 4 material mappings is allowed.", label)
775
- return False
776
-
777
- hex_color_regex = re.compile(r"^#[0-9A-Fa-f]{6}$")
778
-
779
- for i, mapping in enumerate(material_mappings):
780
- if mapping.tool_id < 0 or mapping.tool_id > 3:
781
- logger.warning(
782
- "%s: toolId must be between 0-3, got %s at index %s",
783
- label,
784
- mapping.tool_id,
785
- i,
786
- )
787
- return False
788
-
789
- if mapping.slot_id < 1 or mapping.slot_id > 4:
790
- logger.warning(
791
- "%s: slotId must be between 1-4, got %s at index %s",
792
- label,
793
- mapping.slot_id,
794
- i,
795
- )
796
- return False
797
-
798
- if not mapping.material_name or mapping.material_name.strip() == "":
799
- logger.warning("%s: materialName cannot be empty at index %s", label, i)
800
- return False
801
-
802
- if not hex_color_regex.match(mapping.tool_material_color):
803
- logger.warning(
804
- "%s: toolMaterialColor must be in #RRGGBB format, got %s at index %s",
805
- label,
806
- mapping.tool_material_color,
807
- i,
808
- )
809
- return False
810
-
811
- if not hex_color_regex.match(mapping.slot_material_color):
812
- logger.warning(
813
- "%s: slotMaterialColor must be in #RRGGBB format, got %s at index %s",
814
- label,
815
- mapping.slot_material_color,
816
- i,
817
- )
818
- return False
819
-
820
- return True
821
-
822
- def _validate_ad5x_printer(self) -> bool:
823
- """
824
- Validates that the current printer is an AD5X model.
825
-
826
- Returns:
827
- True if the printer is AD5X, false otherwise
828
- """
829
- if not self.client.is_ad5x:
830
- logger.warning("AD5X job: this method can only be used with AD5X printers.")
831
- return False
832
- return True
833
-
834
- def _encode_material_mappings_to_base64(
835
- self, material_mappings: list[AD5XMaterialMapping]
836
- ) -> str:
837
- """
838
- Encodes material mappings array to base64 string for HTTP headers.
839
- Converts AD5XMaterialMapping array to JSON and then to base64 encoding.
840
-
841
- Args:
842
- material_mappings: Array of material mappings to encode
843
-
844
- Returns:
845
- Base64-encoded JSON string
846
- """
847
- try:
848
- json_array = [
849
- {
850
- "toolId": m.tool_id,
851
- "slotId": m.slot_id,
852
- "materialName": m.material_name,
853
- "toolMaterialColor": m.tool_material_color,
854
- "slotMaterialColor": m.slot_material_color,
855
- }
856
- for m in material_mappings
857
- ]
858
- json_string = json.dumps(json_array)
859
- return base64.b64encode(json_string.encode("utf-8")).decode("utf-8")
860
- except Exception as error:
861
- logger.warning("Failed to encode the material mappings to base64: %s", error)
862
- raise Exception(
863
- "Failed to encode material mappings for upload"
864
- ) from error # noqa: B904
865
-
866
- def _validate_material_mappings(self, material_mappings: list[AD5XMaterialMapping]) -> bool:
867
- """
868
- Validates material mappings for AD5X multi-color jobs. Delegates to the
869
- shared validator with ``allow_empty=False`` (AD5X multi-color jobs
870
- require at least one mapping).
871
-
872
- Args:
873
- material_mappings: Array of material mappings to validate
874
-
875
- Returns:
876
- True if all mappings are valid, false otherwise
877
- """
878
- return self._validate_mappings(
879
- material_mappings, allow_empty=False, label="Material mappings validation"
880
- )