flashforge-python-api 1.6.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 (70) hide show
  1. flashforge/__init__.py +337 -256
  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 -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.0.0.dist-info}/METADATA +46 -47
  60. flashforge_python_api-3.0.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.0.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.6.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 -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.0.0.dist-info}/entry_points.txt +0 -0
@@ -1,590 +1,609 @@
1
- """
2
- High-level client for FlashForge 3D printers via TCP/IP.
3
-
4
- This module provides a comprehensive interface for interacting with FlashForge printers,
5
- building upon the basic TCP communication provided by FlashForgeTcpClient.
6
- """
7
-
8
- import asyncio
9
- import logging
10
-
11
- from .gcode import GCodeController, GCodes
12
- from .parsers import EndstopStatus, LocationInfo, PrinterInfo, PrintStatus, TempInfo, ThumbnailInfo
13
- from .tcp_client import FlashForgeTcpClient, FlashForgeTcpClientOptions
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
-
18
- class FlashForgeClient(FlashForgeTcpClient):
19
- """
20
- High-level client for interacting with FlashForge 3D printers via TCP/IP.
21
-
22
- This class implements specific G-code commands and workflows for printer control,
23
- such as initialization, LED control, job management, homing, temperature settings,
24
- filament operations, and retrieving various printer statuses.
25
-
26
- It uses a "legacy" API approach primarily based on sending G-code/M-code commands
27
- and parsing text-based responses.
28
- """
29
-
30
- def __init__(self, hostname: str, options: FlashForgeTcpClientOptions | None = None) -> None:
31
- """
32
- Create an instance of FlashForgeClient.
33
-
34
- Args:
35
- hostname: The IP address or hostname of the FlashForge printer
36
- """
37
- super().__init__(hostname, options)
38
- self._control = GCodeController(self)
39
- self._is_5m_pro = False
40
- """Flag indicating if the connected printer is a 5M Pro model, which may have specific features."""
41
-
42
- def get_ip(self) -> str:
43
- """
44
- Get the IP address or hostname of the connected printer.
45
-
46
- Returns:
47
- The printer's hostname or IP address
48
- """
49
- return self.hostname
50
-
51
- def gcode(self) -> GCodeController:
52
- """
53
- Get the GCodeController instance associated with this client.
54
-
55
- Provides access to specific G-code command methods.
56
-
57
- Returns:
58
- The GCodeController instance
59
- """
60
- return self._control
61
-
62
- async def init_control(self) -> bool:
63
- """
64
- Initialize the control connection with the printer.
65
-
66
- This typically involves sending a login command, retrieving printer info,
67
- and starting a keep-alive mechanism. Retries on failure.
68
-
69
- Returns:
70
- True if control is successfully initialized, False otherwise
71
- """
72
- logger.info("(Legacy API) InitControl()")
73
- tries = 0
74
- while tries <= 3:
75
- result = await self.send_raw_cmd(GCodes.CMD_LOGIN)
76
- if result and "Control failed." not in result and "ok" in result:
77
- await asyncio.sleep(0.1)
78
- info = await self.get_printer_info()
79
- if not info:
80
- logger.info("(Legacy API) Failed to get printer info, aborting.")
81
- return False
82
-
83
- logger.info(f"(Legacy API) connected to: {info.type_name}")
84
- logger.info(f"(Legacy API) Firmware version: {info.firmware_version}")
85
-
86
- if "5M" in info.type_name and "Pro" in info.type_name:
87
- self._is_5m_pro = True
88
-
89
- await self.start_keep_alive()
90
- return True
91
-
92
- tries += 1
93
- # Ensures no errors from previous connections that were improperly closed
94
- await self.send_raw_cmd(GCodes.CMD_LOGOUT)
95
- await asyncio.sleep(0.5 * tries)
96
-
97
- return False
98
-
99
- async def led_on(self) -> bool:
100
- """
101
- Turn the printer's LED lights on.
102
-
103
- Returns:
104
- True if the command is successful, False otherwise
105
- """
106
- return await self._control.led_on()
107
-
108
- async def led_off(self) -> bool:
109
- """
110
- Turn the printer's LED lights off.
111
-
112
- Returns:
113
- True if the command is successful, False otherwise
114
- """
115
- return await self._control.led_off()
116
-
117
- async def pause_job(self) -> bool:
118
- """
119
- Pause the current print job.
120
-
121
- Returns:
122
- True if the command is successful, False otherwise
123
- """
124
- return await self._control.pause_job()
125
-
126
- async def resume_job(self) -> bool:
127
- """
128
- Resume a paused print job.
129
-
130
- Returns:
131
- True if the command is successful, False otherwise
132
- """
133
- return await self._control.resume_job()
134
-
135
- async def stop_job(self) -> bool:
136
- """
137
- Stop the current print job.
138
-
139
- Returns:
140
- True if the command is successful, False otherwise
141
- """
142
- return await self._control.stop_job()
143
-
144
- async def start_job(self, name: str) -> bool:
145
- """
146
- Start a print job from a file stored on the printer.
147
-
148
- Args:
149
- name: The name of the file to print (typically without path)
150
-
151
- Returns:
152
- True if the command is successful, False otherwise
153
- """
154
- return await self._control.start_job(name)
155
-
156
- async def home_axes(self) -> bool:
157
- """
158
- Home all axes (X, Y, Z) of the printer.
159
-
160
- Returns:
161
- True if the command is successful, False otherwise
162
- """
163
- return await self._control.home()
164
-
165
- async def rapid_home(self) -> bool:
166
- """
167
- Perform a rapid homing of all axes.
168
-
169
- Returns:
170
- True if the command is successful, False otherwise
171
- """
172
- return await self._control.rapid_home()
173
-
174
- async def turn_runout_sensor_on(self) -> bool:
175
- """
176
- Turn on the filament runout sensor.
177
-
178
- This functionality is only available on specific printer models (e.g., 5M Pro).
179
-
180
- Returns:
181
- True if the command is successful and applicable, False otherwise
182
- """
183
- if self._is_5m_pro:
184
- return await self.send_cmd_ok(GCodes.CMD_RUNOUT_SENSOR_ON)
185
-
186
- logger.info("Filament runout sensor not equipped on this printer.")
187
- return False
188
-
189
- async def turn_runout_sensor_off(self) -> bool:
190
- """
191
- Turn off the filament runout sensor.
192
-
193
- This functionality is only available on specific printer models (e.g., 5M Pro).
194
-
195
- Returns:
196
- True if the command is successful and applicable, False otherwise
197
- """
198
- if self._is_5m_pro:
199
- return await self.send_cmd_ok(GCodes.CMD_RUNOUT_SENSOR_OFF)
200
-
201
- logger.info("Filament runout sensor not equipped on this printer.")
202
- return False
203
-
204
- async def set_extruder_temp(self, temp: int, wait_for: bool = False) -> bool:
205
- """
206
- Set the target temperature for the extruder.
207
-
208
- Args:
209
- temp: The target temperature in Celsius
210
- wait_for: If True, the method will wait until the target temperature is reached
211
-
212
- Returns:
213
- True if the command is successful, False otherwise
214
- """
215
- return await self._control.set_extruder_temp(temp, wait_for)
216
-
217
- async def cancel_extruder_temp(self) -> bool:
218
- """
219
- Cancel extruder heating and set its target temperature to 0.
220
-
221
- Returns:
222
- True if the command is successful, False otherwise
223
- """
224
- return await self._control.cancel_extruder_temp()
225
-
226
- async def set_bed_temp(self, temp: int, wait_for: bool = False) -> bool:
227
- """
228
- Set the target temperature for the print bed.
229
-
230
- Args:
231
- temp: The target temperature in Celsius
232
- wait_for: If True, the method will wait until the target temperature is reached
233
-
234
- Returns:
235
- True if the command is successful, False otherwise
236
- """
237
- return await self._control.set_bed_temp(temp, wait_for)
238
-
239
- async def cancel_bed_temp(self, wait_for_cool: bool = False) -> bool:
240
- """
241
- Cancel print bed heating and set its target temperature to 0.
242
-
243
- Args:
244
- wait_for_cool: If True, waits for the bed to cool down after canceling
245
-
246
- Returns:
247
- True if the command is successful, False otherwise
248
- """
249
- return await self._control.cancel_bed_temp(wait_for_cool)
250
-
251
- async def extrude(self, length: float, feedrate: int = 450) -> bool:
252
- """
253
- Command the extruder to extrude a specific length of filament.
254
-
255
- Uses G1 E[length] F[feedrate] command.
256
-
257
- Args:
258
- length: The length of filament to extrude in millimeters
259
- feedrate: The feedrate for extrusion in mm/min (default: 450)
260
-
261
- Returns:
262
- True if the command is successful, False otherwise
263
- """
264
- return await self.send_cmd_ok(f"~G1 E{length} F{feedrate}")
265
-
266
- async def move_extruder(self, x: float, y: float, feedrate: int) -> bool:
267
- """
268
- Move the extruder to a specified X, Y position.
269
-
270
- Uses G1 X[x] Y[y] F[feedrate] command.
271
-
272
- Args:
273
- x: The target X coordinate
274
- y: The target Y coordinate
275
- feedrate: The feedrate for the movement in mm/min
276
-
277
- Returns:
278
- True if the command is successful, False otherwise
279
- """
280
- return await self.send_cmd_ok(f"~G1 X{x} Y{y} F{feedrate}")
281
-
282
- async def move(self, x: float, y: float, z: float, feedrate: int) -> bool:
283
- """
284
- Move the extruder to a specified X, Y, Z position.
285
-
286
- Uses G1 X[x] Y[y] Z[z] F[feedrate] command.
287
-
288
- Args:
289
- x: The target X coordinate
290
- y: The target Y coordinate
291
- z: The target Z coordinate
292
- feedrate: The feedrate for the movement in mm/min
293
-
294
- Returns:
295
- True if the command is successful, False otherwise
296
- """
297
- return await self.send_cmd_ok(f"~G1 X{x} Y{y} Z{z} F{feedrate}")
298
-
299
- async def send_cmd_ok(self, cmd: str) -> bool:
300
- """
301
- Send a G-code/M-code command to the printer and check for an "ok" response.
302
-
303
- Expects the printer's reply to include "Received." and "ok" to be considered successful.
304
-
305
- Args:
306
- cmd: The command string to send (e.g., "~M115")
307
-
308
- Returns:
309
- True if the command is acknowledged with "ok", False otherwise or on error
310
- """
311
- try:
312
- reply = await self.send_command_async(cmd)
313
- if reply and "Received." in reply and "ok" in reply:
314
- return True
315
- except Exception as ex:
316
- logger.error(f"SendCmdOk exception sending cmd: {cmd} : {ex}")
317
- return False
318
- return False
319
-
320
- async def send_raw_cmd(self, cmd: str) -> str:
321
- """
322
- Send a raw command string to the printer and return the raw response.
323
-
324
- Handles a special case for "M661" (list files), which is processed differently.
325
-
326
- Args:
327
- cmd: The raw command string to send
328
-
329
- Returns:
330
- The printer's raw string response, or an empty string on failure.
331
- For "M661", it returns a newline-separated list of files.
332
- """
333
- if "M661" not in cmd:
334
- result = await self.send_command_async(cmd)
335
- return result or ""
336
-
337
- file_list = await self.get_file_list_async()
338
- return "\n".join(file_list)
339
-
340
- async def get_printer_info(self) -> PrinterInfo | None:
341
- """
342
- Retrieve general printer information (model, firmware, etc.).
343
-
344
- Sends CMD_INFO_STATUS and parses the response into a PrinterInfo object.
345
-
346
- Returns:
347
- A PrinterInfo object, or None if retrieval fails
348
- """
349
- response = await self.send_command_async(GCodes.CMD_INFO_STATUS)
350
- if response:
351
- return PrinterInfo().from_replay(response)
352
- return None
353
-
354
- async def get_temp_info(self) -> TempInfo | None:
355
- """
356
- Retrieve current temperature information (extruder, bed).
357
-
358
- Sends CMD_TEMP and parses the response into a TempInfo object.
359
-
360
- Returns:
361
- A TempInfo object, or None if retrieval fails
362
- """
363
- response = await self.send_command_async(GCodes.CMD_TEMP)
364
- if response:
365
- return TempInfo().from_replay(response)
366
- return None
367
-
368
- async def get_location_info(self) -> LocationInfo | None:
369
- """
370
- Retrieve the current XYZ coordinates of the print head.
371
-
372
- Sends CMD_INFO_XYZAB and parses the response into a LocationInfo object.
373
-
374
- Returns:
375
- A LocationInfo object, or None if retrieval fails
376
- """
377
- response = await self.send_command_async(GCodes.CMD_INFO_XYZAB)
378
- if response:
379
- return LocationInfo().from_replay(response)
380
- return None
381
-
382
- async def _get_nozzle_temp(self) -> float:
383
- """
384
- Retrieve the current temperature of the nozzle (extruder).
385
-
386
- Returns:
387
- The current nozzle temperature in Celsius, or 0 if unavailable
388
- """
389
- temps = await self.get_temp_info()
390
- if temps:
391
- extruder_temp = temps.get_extruder_temp()
392
- if extruder_temp:
393
- return extruder_temp.get_current()
394
- return 0.0
395
-
396
- async def get_endstop_status(self) -> EndstopStatus | None:
397
- """
398
- Retrieve the current endstop status and machine state information.
399
-
400
- Sends M119 command and parses the response into an EndstopStatus object.
401
- This includes endstop states, machine status, move mode, LED status, and current file.
402
-
403
- Returns:
404
- An EndstopStatus object, or None if retrieval fails
405
- """
406
- response = await self.send_command_async(GCodes.CMD_ENDSTOP_INFO)
407
- if response:
408
- return EndstopStatus().from_replay(response)
409
- return None
410
-
411
- async def get_print_status(self) -> PrintStatus | None:
412
- """
413
- Retrieve the current print status and progress information.
414
-
415
- Sends M27 command and parses the response into a PrintStatus object.
416
- This includes SD card byte progress and layer progress.
417
-
418
- Returns:
419
- A PrintStatus object, or None if retrieval fails
420
- """
421
- response = await self.send_command_async("~M27") # Print progress
422
- if response:
423
- return PrintStatus().from_replay(response)
424
- return None
425
-
426
- async def get_thumbnail(self, file_name: str) -> ThumbnailInfo | None:
427
- """
428
- Retrieve the thumbnail image for a specific file.
429
-
430
- Sends M662 command and parses the response to extract PNG thumbnail data.
431
-
432
- Args:
433
- file_name: The name of the file to get the thumbnail for
434
-
435
- Returns:
436
- A ThumbnailInfo object containing the PNG image data, or None if retrieval fails
437
- """
438
- # M662 command to get thumbnail
439
- cmd = f"~M662 {file_name}"
440
- response = await self.send_command_async(cmd)
441
- if response:
442
- return ThumbnailInfo().from_replay(response, file_name)
443
- return None
444
-
445
- async def check_machine_state(self) -> str:
446
- """
447
- Get a simplified machine state string for quick status checking.
448
-
449
- Returns:
450
- A string indicating the machine state ("printing", "ready", "paused", "complete", "unknown")
451
- """
452
- endstop_status = await self.get_endstop_status()
453
- if not endstop_status:
454
- return "unknown"
455
-
456
- if endstop_status.is_printing():
457
- return "printing"
458
- elif endstop_status.is_print_complete():
459
- return "complete"
460
- elif endstop_status.is_paused():
461
- return "paused"
462
- elif endstop_status.is_ready():
463
- return "ready"
464
- else:
465
- return "unknown"
466
-
467
- async def get_current_print_file(self) -> str | None:
468
- """
469
- Get the name of the currently loaded/printing file.
470
-
471
- Returns:
472
- The filename of the current print job, or None if no file is loaded
473
- """
474
- endstop_status = await self.get_endstop_status()
475
- if endstop_status:
476
- return endstop_status.current_file
477
- return None
478
-
479
- async def is_printer_ready(self) -> bool:
480
- """
481
- Check if the printer is ready for new commands.
482
-
483
- Returns:
484
- True if the printer is in a ready state, False otherwise
485
- """
486
- endstop_status = await self.get_endstop_status()
487
- if endstop_status:
488
- return endstop_status.is_ready()
489
- return False
490
-
491
- async def get_print_progress(self) -> tuple[int, int, int]:
492
- """
493
- Get comprehensive print progress information.
494
-
495
- Returns:
496
- A tuple of (layer_percent, sd_percent, current_layer) where:
497
- - layer_percent: Progress based on layers (0-100)
498
- - sd_percent: Progress based on SD card bytes (0-100)
499
- - current_layer: Current layer number
500
- Returns (0, 0, 0) if progress information is unavailable
501
- """
502
- print_status = await self.get_print_status()
503
- if not print_status:
504
- return (0, 0, 0)
505
-
506
- layer_percent = print_status.get_print_percent()
507
- sd_percent = print_status.get_sd_percent()
508
-
509
- # Handle NaN values
510
- if layer_percent != layer_percent: # NaN check
511
- layer_percent = 0
512
- if sd_percent != sd_percent: # NaN check
513
- sd_percent = 0
514
-
515
- try:
516
- current_layer = int(print_status.layer_current) if print_status.layer_current else 0
517
- except ValueError:
518
- current_layer = 0
519
-
520
- return (int(layer_percent), int(sd_percent), current_layer)
521
-
522
- async def wait_for_part_cool(
523
- self, target_temp: float = 50.0, timeout_seconds: int = 1800
524
- ) -> bool:
525
- """
526
- Wait for printer components (extruder and bed) to cool down to a safe temperature.
527
-
528
- This method cancels heating for both extruder and bed, then waits for them to cool down.
529
-
530
- Args:
531
- target_temp: The target temperature to wait for (default: 50°C)
532
- timeout_seconds: Maximum time to wait in seconds (default: 30 minutes)
533
-
534
- Returns:
535
- True if components cooled to target temperature, False if timeout or error
536
- """
537
- logger.info(f"Starting cooling process - waiting for parts to cool to {target_temp}°C")
538
-
539
- # Cancel heating for both extruder and bed
540
- extruder_cancel_ok = await self.cancel_extruder_temp()
541
- bed_cancel_ok = await self.cancel_bed_temp()
542
-
543
- if not (extruder_cancel_ok and bed_cancel_ok):
544
- logger.error("Failed to cancel heating - cannot wait for cooling")
545
- return False
546
-
547
- start_time = asyncio.get_event_loop().time()
548
- timeout_time = start_time + timeout_seconds
549
-
550
- extruder_cooled = False
551
- bed_cooled = False
552
-
553
- while asyncio.get_event_loop().time() < timeout_time:
554
- # Check current temperatures
555
- temp_info = await self.get_temp_info()
556
- if not temp_info:
557
- logger.warning("Could not get temperature info during cooling")
558
- await asyncio.sleep(10)
559
- continue
560
-
561
- # Check extruder temperature
562
- if not extruder_cooled:
563
- extruder_temp = temp_info.get_extruder_temp()
564
- if extruder_temp:
565
- current_extruder_temp = extruder_temp.get_current()
566
- if current_extruder_temp <= target_temp:
567
- extruder_cooled = True
568
- logger.info(f"Extruder cooled to {current_extruder_temp}°C")
569
-
570
- # Check bed temperature
571
- if not bed_cooled:
572
- bed_temp = temp_info.get_bed_temp()
573
- if bed_temp:
574
- current_bed_temp = bed_temp.get_current()
575
- if current_bed_temp <= target_temp:
576
- bed_cooled = True
577
- logger.info(f"Bed cooled to {current_bed_temp}°C")
578
-
579
- # Check if both have cooled
580
- if extruder_cooled and bed_cooled:
581
- logger.info("All components have cooled to target temperature")
582
- return True
583
-
584
- # Wait before next check
585
- await asyncio.sleep(10) # Check every 10 seconds
586
-
587
- # Timeout reached
588
- logger.warning(f"Timeout after {timeout_seconds} seconds waiting for cooling")
589
- logger.warning(f"Extruder cooled: {extruder_cooled}, Bed cooled: {bed_cooled}")
590
- return False
1
+ """
2
+ High-level client for FlashForge 3D printers via TCP/IP.
3
+
4
+ This module provides a comprehensive interface for interacting with FlashForge printers,
5
+ building upon the basic TCP communication provided by FlashForgeTcpClient.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+
11
+ from ..api.filament.filament import Filament
12
+ from .gcode import GCodeController, GCodes
13
+ from .parsers import EndstopStatus, LocationInfo, PrinterInfo, PrintStatus, TempInfo, ThumbnailInfo
14
+ from .tcp_client import FlashForgeTcpClient, FlashForgeTcpClientOptions
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class FlashForgeClient(FlashForgeTcpClient):
20
+ """
21
+ High-level client for interacting with FlashForge 3D printers via TCP/IP.
22
+
23
+ This class implements specific G-code commands and workflows for printer control,
24
+ such as initialization, LED control, job management, homing, temperature settings,
25
+ filament operations, and retrieving various printer statuses.
26
+
27
+ It uses a "legacy" API approach primarily based on sending G-code/M-code commands
28
+ and parsing text-based responses.
29
+ """
30
+
31
+ def __init__(self, hostname: str, options: FlashForgeTcpClientOptions | None = None) -> None:
32
+ """
33
+ Create an instance of FlashForgeClient.
34
+
35
+ Args:
36
+ hostname: The IP address or hostname of the FlashForge printer
37
+ """
38
+ super().__init__(hostname, options)
39
+ self._control = GCodeController(self)
40
+ self._is_5m_pro = False
41
+ """Flag indicating if the connected printer is a 5M Pro model, which may have specific features."""
42
+
43
+ def get_ip(self) -> str:
44
+ """
45
+ Get the IP address or hostname of the connected printer.
46
+
47
+ Returns:
48
+ The printer's hostname or IP address
49
+ """
50
+ return self.hostname
51
+
52
+ def gcode(self) -> GCodeController:
53
+ """
54
+ Get the GCodeController instance associated with this client.
55
+
56
+ Provides access to specific G-code command methods.
57
+
58
+ Returns:
59
+ The GCodeController instance
60
+ """
61
+ return self._control
62
+
63
+ async def init_control(self) -> bool:
64
+ """
65
+ Initialize the control connection with the printer.
66
+
67
+ This typically involves sending a login command, retrieving printer info,
68
+ and starting a keep-alive mechanism. Retries on failure.
69
+
70
+ Returns:
71
+ True if control is successfully initialized, False otherwise
72
+ """
73
+ logger.info("(Legacy API) InitControl()")
74
+ tries = 0
75
+ while tries <= 3:
76
+ result = await self.send_raw_cmd(GCodes.CMD_LOGIN)
77
+ if result and "Control failed." not in result and "ok" in result:
78
+ await asyncio.sleep(0.1)
79
+ info = await self.get_printer_info()
80
+ if not info:
81
+ logger.info("(Legacy API) Failed to get printer info, aborting.")
82
+ return False
83
+
84
+ logger.info(f"(Legacy API) connected to: {info.type_name}")
85
+ logger.info(f"(Legacy API) Firmware version: {info.firmware_version}")
86
+
87
+ if "5M" in info.type_name and "Pro" in info.type_name:
88
+ self._is_5m_pro = True
89
+
90
+ await self.start_keep_alive()
91
+ return True
92
+
93
+ tries += 1
94
+ # Ensures no errors from previous connections that were improperly closed
95
+ await self.send_raw_cmd(GCodes.CMD_LOGOUT)
96
+ await asyncio.sleep(0.5 * tries)
97
+
98
+ return False
99
+
100
+ async def led_on(self) -> bool:
101
+ """
102
+ Turn the printer's LED lights on.
103
+
104
+ Returns:
105
+ True if the command is successful, False otherwise
106
+ """
107
+ return await self._control.led_on()
108
+
109
+ async def led_off(self) -> bool:
110
+ """
111
+ Turn the printer's LED lights off.
112
+
113
+ Returns:
114
+ True if the command is successful, False otherwise
115
+ """
116
+ return await self._control.led_off()
117
+
118
+ async def pause_job(self) -> bool:
119
+ """
120
+ Pause the current print job.
121
+
122
+ Returns:
123
+ True if the command is successful, False otherwise
124
+ """
125
+ return await self._control.pause_job()
126
+
127
+ async def resume_job(self) -> bool:
128
+ """
129
+ Resume a paused print job.
130
+
131
+ Returns:
132
+ True if the command is successful, False otherwise
133
+ """
134
+ return await self._control.resume_job()
135
+
136
+ async def stop_job(self) -> bool:
137
+ """
138
+ Stop the current print job.
139
+
140
+ Returns:
141
+ True if the command is successful, False otherwise
142
+ """
143
+ return await self._control.stop_job()
144
+
145
+ async def start_job(self, name: str) -> bool:
146
+ """
147
+ Start a print job from a file stored on the printer.
148
+
149
+ Args:
150
+ name: The name of the file to print (typically without path)
151
+
152
+ Returns:
153
+ True if the command is successful, False otherwise
154
+ """
155
+ return await self._control.start_job(name)
156
+
157
+ async def home_axes(self) -> bool:
158
+ """
159
+ Home all axes (X, Y, Z) of the printer.
160
+
161
+ Returns:
162
+ True if the command is successful, False otherwise
163
+ """
164
+ return await self._control.home()
165
+
166
+ async def rapid_home(self) -> bool:
167
+ """
168
+ Perform a rapid homing of all axes.
169
+
170
+ Returns:
171
+ True if the command is successful, False otherwise
172
+ """
173
+ return await self._control.rapid_home()
174
+
175
+ async def set_extruder_temp(self, temp: int) -> bool:
176
+ """
177
+ Set the target temperature for the extruder.
178
+
179
+ Args:
180
+ temp: The target temperature in Celsius
181
+
182
+ Returns:
183
+ True if the command is successful, False otherwise
184
+ """
185
+ return await self._control.set_extruder_temp(temp)
186
+
187
+ async def cancel_extruder_temp(self) -> bool:
188
+ """
189
+ Cancel extruder heating and set its target temperature to 0.
190
+
191
+ Returns:
192
+ True if the command is successful, False otherwise
193
+ """
194
+ return await self._control.cancel_extruder_temp()
195
+
196
+ async def set_bed_temp(self, temp: int) -> bool:
197
+ """
198
+ Set the target temperature for the print bed.
199
+
200
+ Args:
201
+ temp: The target temperature in Celsius
202
+
203
+ Returns:
204
+ True if the command is successful, False otherwise
205
+ """
206
+ return await self._control.set_bed_temp(temp)
207
+
208
+ async def cancel_bed_temp(self, wait_for_cool: bool = False) -> bool:
209
+ """
210
+ Cancel print bed heating and set its target temperature to 0.
211
+
212
+ Args:
213
+ wait_for_cool: If True, waits for the bed to cool down after canceling
214
+
215
+ Returns:
216
+ True if the command is successful, False otherwise
217
+ """
218
+ return await self._control.cancel_bed_temp(wait_for_cool)
219
+
220
+ async def extrude(self, length: float, feedrate: int = 450) -> bool:
221
+ """
222
+ Command the extruder to extrude a specific length of filament.
223
+
224
+ Uses G1 E[length] F[feedrate] command.
225
+
226
+ Args:
227
+ length: The length of filament to extrude in millimeters
228
+ feedrate: The feedrate for extrusion in mm/min (default: 450)
229
+
230
+ Returns:
231
+ True if the command is successful, False otherwise
232
+ """
233
+ return await self.send_cmd_ok(f"~G1 E{length} F{feedrate}")
234
+
235
+ async def move_extruder(self, x: float, y: float, feedrate: int) -> bool:
236
+ """
237
+ Move the extruder to a specified X, Y position.
238
+
239
+ Uses G1 X[x] Y[y] F[feedrate] command.
240
+
241
+ Args:
242
+ x: The target X coordinate
243
+ y: The target Y coordinate
244
+ feedrate: The feedrate for the movement in mm/min
245
+
246
+ Returns:
247
+ True if the command is successful, False otherwise
248
+ """
249
+ return await self.send_cmd_ok(f"~G1 X{x} Y{y} F{feedrate}")
250
+
251
+ async def move(self, x: float, y: float, z: float, feedrate: int) -> bool:
252
+ """
253
+ Move the extruder to a specified X, Y, Z position.
254
+
255
+ Uses G1 X[x] Y[y] Z[z] F[feedrate] command.
256
+
257
+ Args:
258
+ x: The target X coordinate
259
+ y: The target Y coordinate
260
+ z: The target Z coordinate
261
+ feedrate: The feedrate for the movement in mm/min
262
+
263
+ Returns:
264
+ True if the command is successful, False otherwise
265
+ """
266
+ return await self.send_cmd_ok(f"~G1 X{x} Y{y} Z{z} F{feedrate}")
267
+
268
+ async def send_cmd_ok(self, cmd: str) -> bool:
269
+ """
270
+ Send a G-code/M-code command to the printer and check for an "ok" response.
271
+
272
+ Expects the printer's reply to include "Received." and "ok" to be considered successful.
273
+
274
+ Args:
275
+ cmd: The command string to send (e.g., "~M115")
276
+
277
+ Returns:
278
+ True if the command is acknowledged with "ok", False otherwise or on error
279
+ """
280
+ try:
281
+ reply = await self.send_command_async(cmd)
282
+ if reply and "Received." in reply and "ok" in reply:
283
+ return True
284
+ except Exception as ex:
285
+ logger.error(f"SendCmdOk exception sending cmd: {cmd} : {ex}")
286
+ return False
287
+ return False
288
+
289
+ async def send_raw_cmd(self, cmd: str) -> str:
290
+ """
291
+ Send a raw command string to the printer and return the raw response.
292
+
293
+ Handles a special case for "M661" (list files), which is processed differently.
294
+
295
+ Args:
296
+ cmd: The raw command string to send
297
+
298
+ Returns:
299
+ The printer's raw string response, or an empty string on failure.
300
+ For "M661", it returns a newline-separated list of files.
301
+ """
302
+ if "M661" not in cmd:
303
+ result = await self.send_command_async(cmd)
304
+ return result or ""
305
+
306
+ file_list = await self.get_file_list_async()
307
+ return "\n".join(file_list)
308
+
309
+ async def get_printer_info(self) -> PrinterInfo | None:
310
+ """
311
+ Retrieve general printer information (model, firmware, etc.).
312
+
313
+ Sends CMD_INFO_STATUS and parses the response into a PrinterInfo object.
314
+
315
+ Returns:
316
+ A PrinterInfo object, or None if retrieval fails
317
+ """
318
+ response = await self.send_command_async(GCodes.CMD_INFO_STATUS)
319
+ if response:
320
+ return PrinterInfo().from_replay(response)
321
+ return None
322
+
323
+ async def get_temp_info(self) -> TempInfo | None:
324
+ """
325
+ Retrieve current temperature information (extruder, bed).
326
+
327
+ Sends CMD_TEMP and parses the response into a TempInfo object.
328
+
329
+ Returns:
330
+ A TempInfo object, or None if retrieval fails
331
+ """
332
+ response = await self.send_command_async(GCodes.CMD_TEMP)
333
+ if response:
334
+ return TempInfo().from_replay(response)
335
+ return None
336
+
337
+ async def get_location_info(self) -> LocationInfo | None:
338
+ """
339
+ Retrieve the current XYZ coordinates of the print head.
340
+
341
+ Sends CMD_INFO_XYZAB and parses the response into a LocationInfo object.
342
+
343
+ Returns:
344
+ A LocationInfo object, or None if retrieval fails
345
+ """
346
+ response = await self.send_command_async(GCodes.CMD_INFO_XYZAB)
347
+ if response:
348
+ return LocationInfo().from_replay(response)
349
+ return None
350
+
351
+ async def _get_nozzle_temp(self) -> float:
352
+ """
353
+ Retrieve the current temperature of the nozzle (extruder).
354
+
355
+ Returns:
356
+ The current nozzle temperature in Celsius, or 0 if unavailable
357
+ """
358
+ temps = await self.get_temp_info()
359
+ if temps:
360
+ extruder_temp = temps.get_extruder_temp()
361
+ if extruder_temp:
362
+ return extruder_temp.get_current()
363
+ return 0.0
364
+
365
+ async def prepare_filament_load(self, filament: Filament) -> bool:
366
+ """
367
+ Prepares the printer for a filament load: turns the nozzle off, homes, moves the head
368
+ to the front, heats to the filament's load temperature and purges the old filament.
369
+
370
+ The printer does not support M109 ("set and wait"), so the wait for the nozzle
371
+ temperature happens here (M105 polling, 5 minute limit).
372
+
373
+ Returns:
374
+ True when every step succeeds.
375
+ """
376
+ if not await self.cancel_extruder_temp():
377
+ return False
378
+ if not await self.send_cmd_ok("~G90"):
379
+ return False
380
+ if not await self.home_axes():
381
+ return False
382
+ if not await self.move_extruder(0, 0, 9000):
383
+ return False
384
+ if not await self.set_extruder_temp(int(filament.load_temp)):
385
+ return False
386
+ if not await self._wait_for_nozzle_temp(filament.load_temp):
387
+ return False
388
+ return await self.extrude(300)
389
+
390
+ async def _wait_for_nozzle_temp(self, target: float, timeout_s: float = 300.0) -> bool:
391
+ """Polls M105 until the nozzle is within 2 degrees below the target or higher."""
392
+ loop = asyncio.get_running_loop()
393
+ deadline = loop.time() + timeout_s
394
+ while loop.time() < deadline:
395
+ if await self._get_nozzle_temp() >= target - 2:
396
+ return True
397
+ await asyncio.sleep(1.0)
398
+ logger.warning("Nozzle did not reach %s C within %ss.", target, timeout_s)
399
+ return False
400
+
401
+ async def load_filament(self) -> bool:
402
+ """Loads filament by extruding 250 mm. Needs a nozzle at 210 C or more."""
403
+ if await self._get_nozzle_temp() >= 210:
404
+ return await self.extrude(250)
405
+ logger.warning("load_filament: the nozzle is not hot enough.")
406
+ return False
407
+
408
+ async def finish_filament_load(self) -> bool:
409
+ """Finishes a filament load: turns the nozzle off, waits 5 s and homes the axes."""
410
+ if not await self.cancel_extruder_temp():
411
+ return False
412
+ await asyncio.sleep(5)
413
+ return await self.home_axes()
414
+
415
+ async def get_endstop_status(self) -> EndstopStatus | None:
416
+ """
417
+ Retrieve the current endstop status and machine state information.
418
+
419
+ Sends M119 command and parses the response into an EndstopStatus object.
420
+ This includes endstop states, machine status, move mode, LED status, and current file.
421
+
422
+ Returns:
423
+ An EndstopStatus object, or None if retrieval fails
424
+ """
425
+ response = await self.send_command_async(GCodes.CMD_ENDSTOP_INFO)
426
+ if response:
427
+ return EndstopStatus().from_replay(response)
428
+ return None
429
+
430
+ async def get_print_status(self) -> PrintStatus | None:
431
+ """
432
+ Retrieve the current print status and progress information.
433
+
434
+ Sends M27 command and parses the response into a PrintStatus object.
435
+ This includes SD card byte progress and layer progress.
436
+
437
+ Returns:
438
+ A PrintStatus object, or None if retrieval fails
439
+ """
440
+ response = await self.send_command_async("~M27") # Print progress
441
+ if response:
442
+ return PrintStatus().from_replay(response)
443
+ return None
444
+
445
+ async def get_thumbnail(self, file_name: str) -> ThumbnailInfo | None:
446
+ """
447
+ Retrieve the thumbnail image for a specific file.
448
+
449
+ Sends M662 command and parses the response to extract PNG thumbnail data.
450
+
451
+ Args:
452
+ file_name: The name of the file to get the thumbnail for
453
+
454
+ Returns:
455
+ A ThumbnailInfo object containing the PNG image data, or None if retrieval fails
456
+ """
457
+ # M662 command to get thumbnail
458
+ cmd = f"~M662 {file_name}"
459
+ response = await self.send_command_async(cmd)
460
+ if response:
461
+ return ThumbnailInfo().from_replay(response, file_name)
462
+ return None
463
+
464
+ async def check_machine_state(self) -> str:
465
+ """
466
+ Get a simplified machine state string for quick status checking.
467
+
468
+ Returns:
469
+ A string indicating the machine state ("printing", "ready", "paused", "complete", "unknown")
470
+ """
471
+ endstop_status = await self.get_endstop_status()
472
+ if not endstop_status:
473
+ return "unknown"
474
+
475
+ if endstop_status.is_printing():
476
+ return "printing"
477
+ elif endstop_status.is_print_complete():
478
+ return "complete"
479
+ elif endstop_status.is_paused():
480
+ return "paused"
481
+ elif endstop_status.is_ready():
482
+ return "ready"
483
+ else:
484
+ return "unknown"
485
+
486
+ async def get_current_print_file(self) -> str | None:
487
+ """
488
+ Get the name of the currently loaded/printing file.
489
+
490
+ Returns:
491
+ The filename of the current print job, or None if no file is loaded
492
+ """
493
+ endstop_status = await self.get_endstop_status()
494
+ if endstop_status:
495
+ return endstop_status.current_file
496
+ return None
497
+
498
+ async def is_printer_ready(self) -> bool:
499
+ """
500
+ Check if the printer is ready for new commands.
501
+
502
+ Returns:
503
+ True if the printer is in a ready state, False otherwise
504
+ """
505
+ endstop_status = await self.get_endstop_status()
506
+ if endstop_status:
507
+ return endstop_status.is_ready()
508
+ return False
509
+
510
+ async def get_print_progress(self) -> tuple[int, int, int]:
511
+ """
512
+ Get comprehensive print progress information.
513
+
514
+ Returns:
515
+ A tuple of (layer_percent, sd_percent, current_layer) where:
516
+ - layer_percent: Progress based on layers (0-100)
517
+ - sd_percent: Progress based on SD card bytes (0-100)
518
+ - current_layer: Current layer number
519
+ Returns (0, 0, 0) if progress information is unavailable
520
+ """
521
+ print_status = await self.get_print_status()
522
+ if not print_status:
523
+ return (0, 0, 0)
524
+
525
+ layer_percent = print_status.get_print_percent()
526
+ sd_percent = print_status.get_sd_percent()
527
+
528
+ # Handle NaN values
529
+ if layer_percent != layer_percent: # NaN check
530
+ layer_percent = 0
531
+ if sd_percent != sd_percent: # NaN check
532
+ sd_percent = 0
533
+
534
+ try:
535
+ current_layer = int(print_status.layer_current) if print_status.layer_current else 0
536
+ except ValueError:
537
+ current_layer = 0
538
+
539
+ return (int(layer_percent), int(sd_percent), current_layer)
540
+
541
+ async def wait_for_part_cool(
542
+ self, target_temp: float = 50.0, timeout_seconds: int = 1800
543
+ ) -> bool:
544
+ """
545
+ Wait for printer components (extruder and bed) to cool down to a safe temperature.
546
+
547
+ This method cancels heating for both extruder and bed, then waits for them to cool down.
548
+
549
+ Args:
550
+ target_temp: The target temperature to wait for (default: 50°C)
551
+ timeout_seconds: Maximum time to wait in seconds (default: 30 minutes)
552
+
553
+ Returns:
554
+ True if components cooled to target temperature, False if timeout or error
555
+ """
556
+ logger.info(f"Starting cooling process - waiting for parts to cool to {target_temp}°C")
557
+
558
+ # Cancel heating for both extruder and bed
559
+ extruder_cancel_ok = await self.cancel_extruder_temp()
560
+ bed_cancel_ok = await self.cancel_bed_temp()
561
+
562
+ if not (extruder_cancel_ok and bed_cancel_ok):
563
+ logger.error("Failed to cancel heating - cannot wait for cooling")
564
+ return False
565
+
566
+ start_time = asyncio.get_event_loop().time()
567
+ timeout_time = start_time + timeout_seconds
568
+
569
+ extruder_cooled = False
570
+ bed_cooled = False
571
+
572
+ while asyncio.get_event_loop().time() < timeout_time:
573
+ # Check current temperatures
574
+ temp_info = await self.get_temp_info()
575
+ if not temp_info:
576
+ logger.warning("Could not get temperature info during cooling")
577
+ await asyncio.sleep(10)
578
+ continue
579
+
580
+ # Check extruder temperature
581
+ if not extruder_cooled:
582
+ extruder_temp = temp_info.get_extruder_temp()
583
+ if extruder_temp:
584
+ current_extruder_temp = extruder_temp.get_current()
585
+ if current_extruder_temp <= target_temp:
586
+ extruder_cooled = True
587
+ logger.info(f"Extruder cooled to {current_extruder_temp}°C")
588
+
589
+ # Check bed temperature
590
+ if not bed_cooled:
591
+ bed_temp = temp_info.get_bed_temp()
592
+ if bed_temp:
593
+ current_bed_temp = bed_temp.get_current()
594
+ if current_bed_temp <= target_temp:
595
+ bed_cooled = True
596
+ logger.info(f"Bed cooled to {current_bed_temp}°C")
597
+
598
+ # Check if both have cooled
599
+ if extruder_cooled and bed_cooled:
600
+ logger.info("All components have cooled to target temperature")
601
+ return True
602
+
603
+ # Wait before next check
604
+ await asyncio.sleep(10) # Check every 10 seconds
605
+
606
+ # Timeout reached
607
+ logger.warning(f"Timeout after {timeout_seconds} seconds waiting for cooling")
608
+ logger.warning(f"Extruder cooled: {extruder_cooled}, Bed cooled: {bed_cooled}")
609
+ return False