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