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,427 +1,427 @@
1
- """
2
- Adventurer 3 TCP client and typed helpers.
3
- """
4
-
5
- from __future__ import annotations
6
-
7
- import asyncio
8
- import re
9
- from dataclasses import dataclass
10
- from typing import TYPE_CHECKING
11
-
12
- from .gcode.gcodes import GCodes
13
- from .parsers import EndstopStatus, LocationInfo, PrintStatus, TempInfo
14
- from .tcp_client import FlashForgeTcpClient, FlashForgeTcpClientOptions
15
-
16
- if TYPE_CHECKING:
17
- from .gcode import A3GCodeController
18
-
19
-
20
- @dataclass(slots=True)
21
- class A3BuildVolume:
22
- """Build volume metadata reported by Adventurer 3 M115 replies."""
23
-
24
- x: int
25
- y: int
26
- z: int
27
-
28
-
29
- @dataclass(slots=True)
30
- class A3PrinterInfo:
31
- """Structured Adventurer 3 printer info parsed from M115."""
32
-
33
- machine_type: str
34
- machine_name: str
35
- firmware: str
36
- serial_number: str
37
- build_volume: A3BuildVolume
38
- tool_count: int
39
- mac_address: str
40
- raw: str
41
-
42
-
43
- @dataclass(slots=True)
44
- class A3FileEntry:
45
- """File entry returned by the documented Adventurer 3 M661 response format."""
46
-
47
- name: str
48
- path: str
49
- size: int | None = None
50
-
51
-
52
- @dataclass(slots=True)
53
- class A3Thumbnail:
54
- """Thumbnail payload returned by Adventurer 3 M662."""
55
-
56
- data: bytes
57
- width: int | None = None
58
- height: int | None = None
59
-
60
-
61
- class FlashForgeA3Client(FlashForgeTcpClient):
62
- """TCP client for FlashForge Adventurer 3 printers."""
63
-
64
- def __init__(self, hostname: str, options: FlashForgeTcpClientOptions | None = None) -> None:
65
- super().__init__(hostname, options)
66
- self._control: A3GCodeController | None = None
67
-
68
- def gcode(self) -> A3GCodeController:
69
- """Return the Adventurer 3 G-code controller."""
70
- if self._control is None:
71
- from .gcode import A3GCodeController
72
-
73
- self._control = A3GCodeController(self)
74
- return self._control
75
-
76
- def should_skip_response_wait(self, cmd: str) -> bool:
77
- bare_cmd = self._strip_protocol_prefix(cmd)
78
- return bool(re.match(r"^(G1|G28|G90|G91|G92)\b", bare_cmd))
79
-
80
- def should_use_inactivity_completion(self, cmd: str) -> bool:
81
- return not self.is_binary_command(cmd) and not self.should_skip_response_wait(cmd)
82
-
83
- def get_inactivity_completion_delay_ms(self, cmd: str) -> int:
84
- bare_cmd = self._strip_protocol_prefix(cmd)
85
- if bare_cmd.startswith("M661"):
86
- return 500
87
- if (
88
- bare_cmd.startswith("M115")
89
- or bare_cmd.startswith("M119")
90
- or bare_cmd.startswith("M650")
91
- ):
92
- return 250
93
- return 200
94
-
95
- def get_response_completion_delay_ms(self, cmd: str, binary: bool) -> int:
96
- if binary and self._strip_protocol_prefix(cmd).startswith("M662"):
97
- return 0
98
- return super().get_response_completion_delay_ms(cmd, binary)
99
-
100
- def is_binary_response_complete(self, cmd: str, response: bytearray) -> bool:
101
- if not self._strip_protocol_prefix(cmd).startswith("M662"):
102
- return super().is_binary_response_complete(cmd, response)
103
-
104
- buffer = bytes(response)
105
- text_prefix = buffer.decode("utf-8", errors="ignore")
106
- if "Error: File not exists" in text_prefix:
107
- return True
108
-
109
- magic_offset = buffer.find(b"\xa2\xa2\x2a\x2a")
110
- if magic_offset == -1 or len(buffer) < magic_offset + 8:
111
- return False
112
-
113
- length = int.from_bytes(buffer[magic_offset + 4 : magic_offset + 8], byteorder="big")
114
- return len(buffer) >= magic_offset + 8 + length
115
-
116
- def normalize_text_response(self, _cmd: str, response: str) -> str:
117
- return self._normalize_a3_text_response(response)
118
-
119
- async def init_control(self) -> bool:
120
- """Initialize control by sending the legacy M601 S1 login command."""
121
- try:
122
- await asyncio.sleep(0.5)
123
- response = await self.send_command_async(GCodes.CMD_LOGIN)
124
- if response is None:
125
- return False
126
- if "Error: have been connected" in response:
127
- return True
128
- return self._is_successful_command_response(GCodes.CMD_LOGIN, response)
129
- except Exception:
130
- return False
131
-
132
- async def get_printer_info(self) -> A3PrinterInfo | None:
133
- """Get printer information using the documented Adventurer 3 M115 response."""
134
- response = await self.send_command_async("~M115")
135
- if response is None:
136
- return None
137
-
138
- normalized = self._normalize_a3_text_response(response)
139
- lines = self._get_normalized_lines(normalized)
140
- info = A3PrinterInfo(
141
- machine_type="",
142
- machine_name="",
143
- firmware="",
144
- serial_number="",
145
- build_volume=A3BuildVolume(x=150, y=150, z=150),
146
- tool_count=1,
147
- mac_address="",
148
- raw=normalized,
149
- )
150
-
151
- for line in lines:
152
- if line.startswith("Machine Type:"):
153
- info.machine_type = line.replace("Machine Type:", "", 1).strip()
154
- elif line.startswith("Machine Name:"):
155
- info.machine_name = line.replace("Machine Name:", "", 1).strip()
156
- elif line.startswith("Firmware:"):
157
- info.firmware = line.replace("Firmware:", "", 1).strip()
158
- elif line.startswith("SN:"):
159
- info.serial_number = line.replace("SN:", "", 1).strip()
160
- elif line.startswith("Serial Number:"):
161
- info.serial_number = line.replace("Serial Number:", "", 1).strip()
162
- elif line.startswith("Tool Count:"):
163
- try:
164
- info.tool_count = int(line.replace("Tool Count:", "", 1).strip())
165
- except ValueError:
166
- info.tool_count = 1
167
- elif line.startswith("Mac Address:"):
168
- info.mac_address = line.replace("Mac Address:", "", 1).strip()
169
- else:
170
- volume_match = re.search(
171
- r"X:\s*(\d+)\s+Y:\s*(\d+)\s+Z:\s*(\d+)", line, re.IGNORECASE
172
- )
173
- if volume_match:
174
- info.build_volume = A3BuildVolume(
175
- x=int(volume_match.group(1)),
176
- y=int(volume_match.group(2)),
177
- z=int(volume_match.group(3)),
178
- )
179
-
180
- if not info.machine_type or not info.firmware:
181
- return None
182
- return info
183
-
184
- async def get_endstop_status(self) -> EndstopStatus | None:
185
- """Get the printer endstop and machine status using M119."""
186
- response = await self.send_command_async("~M119")
187
- if response is None:
188
- return None
189
- return EndstopStatus().from_replay(self._normalize_a3_text_response(response))
190
-
191
- async def set_printer_name(self, name: str) -> bool:
192
- """Set the printer name using M610."""
193
- return await self.send_cmd_ok(f"~M610 {name}")
194
-
195
- async def list_files(self) -> list[A3FileEntry]:
196
- """List files from printer storage using M661."""
197
- response = await self.send_command_async("~M661")
198
- if response is None:
199
- return []
200
- return self._parse_file_list(response)
201
-
202
- async def get_thumbnail(self, filename: str) -> A3Thumbnail | None:
203
- """Get a file thumbnail using M662."""
204
- response = await self.send_command_async(f"~M662 {filename}")
205
- if response is None:
206
- return None
207
- return self._parse_thumbnail(response)
208
-
209
- async def select_file(self, filename: str) -> bool:
210
- """Select a file for printing using M23."""
211
- resolved_path = filename if filename.startswith("/") else f"/data/{filename}"
212
- return await self.send_cmd_ok(f"~M23 {resolved_path}")
213
-
214
- async def start_print(self) -> bool:
215
- """Start the selected print job using M24."""
216
- return await self.send_cmd_ok("~M24")
217
-
218
- async def pause_print(self) -> bool:
219
- """Pause the active print job using M25."""
220
- return await self.send_cmd_ok("~M25")
221
-
222
- async def stop_print(self) -> bool:
223
- """Stop the active print job using M26."""
224
- return await self.send_cmd_ok("~M26")
225
-
226
- async def get_print_status(self) -> PrintStatus | None:
227
- """Get print progress using M27."""
228
- response = await self.send_command_async("~M27")
229
- if response is None:
230
- return None
231
- return PrintStatus().from_replay(self._normalize_a3_text_response(response))
232
-
233
- async def get_position(self) -> LocationInfo | None:
234
- """Get the current position using M114."""
235
- response = await self.send_command_async("~M114")
236
- if response is None:
237
- return None
238
- return LocationInfo().from_replay(self._normalize_a3_text_response(response))
239
-
240
- async def get_position_xyze(self) -> LocationInfo | None:
241
- """Get the detailed position using M663 when the firmware supports it."""
242
- response = await self.send_command_async("~M663")
243
- if response is None:
244
- return None
245
- return LocationInfo().from_replay(self._normalize_a3_text_response(response))
246
-
247
- async def home(self) -> bool:
248
- """Home all axes using G28."""
249
- return await self.send_cmd_ok("~G28")
250
-
251
- async def move(self, x: float, y: float, z: float, feedrate: int) -> bool:
252
- """Move the print head using G1."""
253
- return await self.send_cmd_ok(f"~G1 X{x} Y{y} Z{z} F{feedrate}")
254
-
255
- async def get_temp_info(self) -> TempInfo | None:
256
- """Get temperature information using M105."""
257
- response = await self.send_command_async("~M105")
258
- if response is None:
259
- return None
260
- return TempInfo().from_replay(self._normalize_a3_text_response(response))
261
-
262
- async def send_cmd_ok(self, cmd: str) -> bool:
263
- """Send a command and apply Adventurer 3 success semantics."""
264
- try:
265
- mapped_cmd = self._map_controller_command(cmd)
266
- response = await self.send_command_async(mapped_cmd)
267
- if response is None:
268
- return False
269
- if self.should_skip_response_wait(mapped_cmd):
270
- return True
271
- return self._is_successful_command_response(mapped_cmd, response)
272
- except Exception:
273
- return False
274
-
275
- async def enable_motors(self) -> bool:
276
- """Enable stepper motors using M17."""
277
- return await self.send_cmd_ok("~M17")
278
-
279
- async def disable_motors(self) -> bool:
280
- """Disable stepper motors using M18."""
281
- return await self.send_cmd_ok("~M18")
282
-
283
- async def emergency_stop(self) -> bool:
284
- """Perform an emergency stop using M112."""
285
- return await self.send_cmd_ok("~M112")
286
-
287
- async def cancel_heat_wait(self) -> bool:
288
- """Send M108. The Adventurer 3 firmware acknowledges it but treats it as a no-op."""
289
- return await self.send_cmd_ok("~M108")
290
-
291
- async def led_control(self, params: str) -> bool:
292
- """Control the accessory LED bar using M146."""
293
- return await self.send_cmd_ok(f"~M146 {params}")
294
-
295
- async def custom_m144(self, params: str | None = None) -> str | None:
296
- """Send M144 directly."""
297
- cmd = f"~M144 {params}" if params else "~M144"
298
- return await self.send_command_async(cmd)
299
-
300
- async def custom_m145(self, params: str | None = None) -> str | None:
301
- """Send M145 directly."""
302
- cmd = f"~M145 {params}" if params else "~M145"
303
- return await self.send_command_async(cmd)
304
-
305
- async def custom_m611(self) -> str | None:
306
- """Send M611 directly."""
307
- return await self.send_command_async("~M611")
308
-
309
- async def custom_m612(self) -> str | None:
310
- """Send M612 directly."""
311
- return await self.send_command_async("~M612")
312
-
313
- async def custom_m650(self) -> str | None:
314
- """Send M650 directly."""
315
- return await self.send_command_async("~M650")
316
-
317
- async def custom_m651(self) -> str | None:
318
- """Send M651 directly."""
319
- return await self.send_command_async("~M651")
320
-
321
- async def custom_m652(self) -> str | None:
322
- """Send M652 directly."""
323
- return await self.send_command_async("~M652")
324
-
325
- async def custom_m653(self, params: str) -> bool:
326
- """Send M653 with parameters."""
327
- return await self.send_cmd_ok(f"~M653 {params}")
328
-
329
- async def custom_m654(self, params: str) -> bool:
330
- """Send M654 with parameters."""
331
- return await self.send_cmd_ok(f"~M654 {params}")
332
-
333
- def _parse_file_list(self, response: str) -> list[A3FileEntry]:
334
- lines = self._get_normalized_lines(response)
335
- if any("CMD M661 Error." in line for line in lines):
336
- return []
337
-
338
- files: list[A3FileEntry] = []
339
- count_index = next(
340
- (
341
- index
342
- for index, line in enumerate(lines)
343
- if re.search(r"info_list\.size:\s*\d+", line)
344
- ),
345
- -1,
346
- )
347
- if count_index == -1:
348
- return files
349
-
350
- count_match = re.search(r"info_list\.size:\s*(\d+)", lines[count_index], re.IGNORECASE)
351
- file_count = int(count_match.group(1)) if count_match else 0
352
- for line in lines[count_index + 1 :]:
353
- if len(files) >= file_count:
354
- break
355
- if not line or line == "ok" or line.startswith("CMD "):
356
- continue
357
- files.append(A3FileEntry(name=line, path=f"/data/{line}"))
358
-
359
- return files
360
-
361
- def _parse_thumbnail(self, response: str) -> A3Thumbnail | None:
362
- buffer = response.encode("latin1")
363
- error_text = buffer.decode("utf-8", errors="ignore")
364
- if "Error: File not exists" in error_text:
365
- return None
366
-
367
- magic_offset = buffer.find(b"\xa2\xa2\x2a\x2a")
368
- if magic_offset == -1 or len(buffer) < magic_offset + 8:
369
- return None
370
-
371
- payload_length = int.from_bytes(
372
- buffer[magic_offset + 4 : magic_offset + 8], byteorder="big"
373
- )
374
- payload_end = magic_offset + 8 + payload_length
375
- if len(buffer) < payload_end:
376
- return None
377
-
378
- return A3Thumbnail(data=buffer[magic_offset + 8 : payload_end])
379
-
380
- def _normalize_a3_text_response(self, response: str) -> str:
381
- normalized = response.replace("\r\n", "\n").replace("\r", "\n")
382
- lines = normalized.split("\n")
383
- if lines:
384
- lines[0] = re.sub(r"^(ack|echo):\s*", "", lines[0], flags=re.IGNORECASE)
385
- normalized = "\n".join(lines).rstrip()
386
-
387
- if normalized.startswith('"') and normalized.endswith('"'):
388
- normalized = normalized[1:-1]
389
-
390
- return normalized.rstrip()
391
-
392
- def _get_normalized_lines(self, response: str) -> list[str]:
393
- return [
394
- line.strip()
395
- for line in self._normalize_a3_text_response(response).split("\n")
396
- if line.strip()
397
- ]
398
-
399
- def _map_controller_command(self, cmd: str) -> str:
400
- if cmd == "~M146 r255 g255 b255 F0":
401
- return "~M146 1"
402
- if cmd == "~M146 r0 g0 b0 F0":
403
- return "~M146 0"
404
- return cmd
405
-
406
- def _is_successful_command_response(self, cmd: str, response: str) -> bool:
407
- normalized = self._normalize_a3_text_response(response).strip()
408
- if not normalized:
409
- return self.should_skip_response_wait(cmd)
410
-
411
- if "Error:" in normalized or "Control failed." in normalized:
412
- return False
413
-
414
- bare_cmd = self._strip_protocol_prefix(cmd)
415
- if bare_cmd.startswith("M23"):
416
- return "File opened" in normalized or "ok" in normalized
417
- if bare_cmd.startswith("M112"):
418
- return (
419
- bool(re.search(r"Emergency Stop", normalized, re.IGNORECASE))
420
- or "Received." in normalized
421
- )
422
- if "ok" in normalized or "Received." in normalized:
423
- return True
424
- return normalized.startswith(bare_cmd)
425
-
426
- def _strip_protocol_prefix(self, cmd: str) -> str:
427
- return cmd.strip().removeprefix("~")
1
+ """
2
+ Adventurer 3 TCP client and typed helpers.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import re
9
+ from dataclasses import dataclass
10
+ from typing import TYPE_CHECKING
11
+
12
+ from .gcode.gcodes import GCodes
13
+ from .parsers import EndstopStatus, LocationInfo, PrintStatus, TempInfo
14
+ from .tcp_client import FlashForgeTcpClient, FlashForgeTcpClientOptions
15
+
16
+ if TYPE_CHECKING:
17
+ from .gcode import A3GCodeController
18
+
19
+
20
+ @dataclass(slots=True)
21
+ class A3BuildVolume:
22
+ """Build volume metadata reported by Adventurer 3 M115 replies."""
23
+
24
+ x: int
25
+ y: int
26
+ z: int
27
+
28
+
29
+ @dataclass(slots=True)
30
+ class A3PrinterInfo:
31
+ """Structured Adventurer 3 printer info parsed from M115."""
32
+
33
+ machine_type: str
34
+ machine_name: str
35
+ firmware: str
36
+ serial_number: str
37
+ build_volume: A3BuildVolume
38
+ tool_count: int
39
+ mac_address: str
40
+ raw: str
41
+
42
+
43
+ @dataclass(slots=True)
44
+ class A3FileEntry:
45
+ """File entry returned by the documented Adventurer 3 M661 response format."""
46
+
47
+ name: str
48
+ path: str
49
+ size: int | None = None
50
+
51
+
52
+ @dataclass(slots=True)
53
+ class A3Thumbnail:
54
+ """Thumbnail payload returned by Adventurer 3 M662."""
55
+
56
+ data: bytes
57
+ width: int | None = None
58
+ height: int | None = None
59
+
60
+
61
+ class FlashForgeA3Client(FlashForgeTcpClient):
62
+ """TCP client for FlashForge Adventurer 3 printers."""
63
+
64
+ def __init__(self, hostname: str, options: FlashForgeTcpClientOptions | None = None) -> None:
65
+ super().__init__(hostname, options)
66
+ self._control: A3GCodeController | None = None
67
+
68
+ def gcode(self) -> A3GCodeController:
69
+ """Return the Adventurer 3 G-code controller."""
70
+ if self._control is None:
71
+ from .gcode import A3GCodeController
72
+
73
+ self._control = A3GCodeController(self)
74
+ return self._control
75
+
76
+ def should_skip_response_wait(self, cmd: str) -> bool:
77
+ bare_cmd = self._strip_protocol_prefix(cmd)
78
+ return bool(re.match(r"^(G1|G28|G90|G91|G92)\b", bare_cmd))
79
+
80
+ def should_use_inactivity_completion(self, cmd: str) -> bool:
81
+ return not self.is_binary_command(cmd) and not self.should_skip_response_wait(cmd)
82
+
83
+ def get_inactivity_completion_delay_ms(self, cmd: str) -> int:
84
+ bare_cmd = self._strip_protocol_prefix(cmd)
85
+ if bare_cmd.startswith("M661"):
86
+ return 500
87
+ if (
88
+ bare_cmd.startswith("M115")
89
+ or bare_cmd.startswith("M119")
90
+ or bare_cmd.startswith("M650")
91
+ ):
92
+ return 250
93
+ return 200
94
+
95
+ def get_response_completion_delay_ms(self, cmd: str, binary: bool) -> int:
96
+ if binary and self._strip_protocol_prefix(cmd).startswith("M662"):
97
+ return 0
98
+ return super().get_response_completion_delay_ms(cmd, binary)
99
+
100
+ def is_binary_response_complete(self, cmd: str, response: bytearray) -> bool:
101
+ if not self._strip_protocol_prefix(cmd).startswith("M662"):
102
+ return super().is_binary_response_complete(cmd, response)
103
+
104
+ buffer = bytes(response)
105
+ text_prefix = buffer.decode("utf-8", errors="ignore")
106
+ if "Error: File not exists" in text_prefix:
107
+ return True
108
+
109
+ magic_offset = buffer.find(b"\xa2\xa2\x2a\x2a")
110
+ if magic_offset == -1 or len(buffer) < magic_offset + 8:
111
+ return False
112
+
113
+ length = int.from_bytes(buffer[magic_offset + 4 : magic_offset + 8], byteorder="big")
114
+ return len(buffer) >= magic_offset + 8 + length
115
+
116
+ def normalize_text_response(self, _cmd: str, response: str) -> str:
117
+ return self._normalize_a3_text_response(response)
118
+
119
+ async def init_control(self) -> bool:
120
+ """Initialize control by sending the legacy M601 S1 login command."""
121
+ try:
122
+ await asyncio.sleep(0.5)
123
+ response = await self.send_command_async(GCodes.CMD_LOGIN)
124
+ if response is None:
125
+ return False
126
+ if "Error: have been connected" in response:
127
+ return True
128
+ return self._is_successful_command_response(GCodes.CMD_LOGIN, response)
129
+ except Exception:
130
+ return False
131
+
132
+ async def get_printer_info(self) -> A3PrinterInfo | None:
133
+ """Get printer information using the documented Adventurer 3 M115 response."""
134
+ response = await self.send_command_async("~M115")
135
+ if response is None:
136
+ return None
137
+
138
+ normalized = self._normalize_a3_text_response(response)
139
+ lines = self._get_normalized_lines(normalized)
140
+ info = A3PrinterInfo(
141
+ machine_type="",
142
+ machine_name="",
143
+ firmware="",
144
+ serial_number="",
145
+ build_volume=A3BuildVolume(x=150, y=150, z=150),
146
+ tool_count=1,
147
+ mac_address="",
148
+ raw=normalized,
149
+ )
150
+
151
+ for line in lines:
152
+ if line.startswith("Machine Type:"):
153
+ info.machine_type = line.replace("Machine Type:", "", 1).strip()
154
+ elif line.startswith("Machine Name:"):
155
+ info.machine_name = line.replace("Machine Name:", "", 1).strip()
156
+ elif line.startswith("Firmware:"):
157
+ info.firmware = line.replace("Firmware:", "", 1).strip()
158
+ elif line.startswith("SN:"):
159
+ info.serial_number = line.replace("SN:", "", 1).strip()
160
+ elif line.startswith("Serial Number:"):
161
+ info.serial_number = line.replace("Serial Number:", "", 1).strip()
162
+ elif line.startswith("Tool Count:"):
163
+ try:
164
+ info.tool_count = int(line.replace("Tool Count:", "", 1).strip())
165
+ except ValueError:
166
+ info.tool_count = 1
167
+ elif line.startswith("Mac Address:"):
168
+ info.mac_address = line.replace("Mac Address:", "", 1).strip()
169
+ else:
170
+ volume_match = re.search(
171
+ r"X:\s*(\d+)\s+Y:\s*(\d+)\s+Z:\s*(\d+)", line, re.IGNORECASE
172
+ )
173
+ if volume_match:
174
+ info.build_volume = A3BuildVolume(
175
+ x=int(volume_match.group(1)),
176
+ y=int(volume_match.group(2)),
177
+ z=int(volume_match.group(3)),
178
+ )
179
+
180
+ if not info.machine_type or not info.firmware:
181
+ return None
182
+ return info
183
+
184
+ async def get_endstop_status(self) -> EndstopStatus | None:
185
+ """Get the printer endstop and machine status using M119."""
186
+ response = await self.send_command_async("~M119")
187
+ if response is None:
188
+ return None
189
+ return EndstopStatus().from_replay(self._normalize_a3_text_response(response))
190
+
191
+ async def set_printer_name(self, name: str) -> bool:
192
+ """Set the printer name using M610."""
193
+ return await self.send_cmd_ok(f"~M610 {name}")
194
+
195
+ async def list_files(self) -> list[A3FileEntry]:
196
+ """List files from printer storage using M661."""
197
+ response = await self.send_command_async("~M661")
198
+ if response is None:
199
+ return []
200
+ return self._parse_file_list(response)
201
+
202
+ async def get_thumbnail(self, filename: str) -> A3Thumbnail | None:
203
+ """Get a file thumbnail using M662."""
204
+ response = await self.send_command_async(f"~M662 {filename}")
205
+ if response is None:
206
+ return None
207
+ return self._parse_thumbnail(response)
208
+
209
+ async def select_file(self, filename: str) -> bool:
210
+ """Select a file for printing using M23."""
211
+ resolved_path = filename if filename.startswith("/") else f"/data/{filename}"
212
+ return await self.send_cmd_ok(f"~M23 {resolved_path}")
213
+
214
+ async def start_print(self) -> bool:
215
+ """Start the selected print job using M24."""
216
+ return await self.send_cmd_ok("~M24")
217
+
218
+ async def pause_print(self) -> bool:
219
+ """Pause the active print job using M25."""
220
+ return await self.send_cmd_ok("~M25")
221
+
222
+ async def stop_print(self) -> bool:
223
+ """Stop the active print job using M26."""
224
+ return await self.send_cmd_ok("~M26")
225
+
226
+ async def get_print_status(self) -> PrintStatus | None:
227
+ """Get print progress using M27."""
228
+ response = await self.send_command_async("~M27")
229
+ if response is None:
230
+ return None
231
+ return PrintStatus().from_replay(self._normalize_a3_text_response(response))
232
+
233
+ async def get_position(self) -> LocationInfo | None:
234
+ """Get the current position using M114."""
235
+ response = await self.send_command_async("~M114")
236
+ if response is None:
237
+ return None
238
+ return LocationInfo().from_replay(self._normalize_a3_text_response(response))
239
+
240
+ async def get_position_xyze(self) -> LocationInfo | None:
241
+ """Get the detailed position using M663 when the firmware supports it."""
242
+ response = await self.send_command_async("~M663")
243
+ if response is None:
244
+ return None
245
+ return LocationInfo().from_replay(self._normalize_a3_text_response(response))
246
+
247
+ async def home(self) -> bool:
248
+ """Home all axes using G28."""
249
+ return await self.send_cmd_ok("~G28")
250
+
251
+ async def move(self, x: float, y: float, z: float, feedrate: int) -> bool:
252
+ """Move the print head using G1."""
253
+ return await self.send_cmd_ok(f"~G1 X{x} Y{y} Z{z} F{feedrate}")
254
+
255
+ async def get_temp_info(self) -> TempInfo | None:
256
+ """Get temperature information using M105."""
257
+ response = await self.send_command_async("~M105")
258
+ if response is None:
259
+ return None
260
+ return TempInfo().from_replay(self._normalize_a3_text_response(response))
261
+
262
+ async def send_cmd_ok(self, cmd: str) -> bool:
263
+ """Send a command and apply Adventurer 3 success semantics."""
264
+ try:
265
+ mapped_cmd = self._map_controller_command(cmd)
266
+ response = await self.send_command_async(mapped_cmd)
267
+ if response is None:
268
+ return False
269
+ if self.should_skip_response_wait(mapped_cmd):
270
+ return True
271
+ return self._is_successful_command_response(mapped_cmd, response)
272
+ except Exception:
273
+ return False
274
+
275
+ async def enable_motors(self) -> bool:
276
+ """Enable stepper motors using M17."""
277
+ return await self.send_cmd_ok("~M17")
278
+
279
+ async def disable_motors(self) -> bool:
280
+ """Disable stepper motors using M18."""
281
+ return await self.send_cmd_ok("~M18")
282
+
283
+ async def emergency_stop(self) -> bool:
284
+ """Perform an emergency stop using M112."""
285
+ return await self.send_cmd_ok("~M112")
286
+
287
+ async def cancel_heat_wait(self) -> bool:
288
+ """Send M108. The Adventurer 3 firmware acknowledges it but treats it as a no-op."""
289
+ return await self.send_cmd_ok("~M108")
290
+
291
+ async def led_control(self, params: str) -> bool:
292
+ """Control the accessory LED bar using M146."""
293
+ return await self.send_cmd_ok(f"~M146 {params}")
294
+
295
+ async def custom_m144(self, params: str | None = None) -> str | None:
296
+ """Send M144 directly."""
297
+ cmd = f"~M144 {params}" if params else "~M144"
298
+ return await self.send_command_async(cmd)
299
+
300
+ async def custom_m145(self, params: str | None = None) -> str | None:
301
+ """Send M145 directly."""
302
+ cmd = f"~M145 {params}" if params else "~M145"
303
+ return await self.send_command_async(cmd)
304
+
305
+ async def custom_m611(self) -> str | None:
306
+ """Send M611 directly."""
307
+ return await self.send_command_async("~M611")
308
+
309
+ async def custom_m612(self) -> str | None:
310
+ """Send M612 directly."""
311
+ return await self.send_command_async("~M612")
312
+
313
+ async def custom_m650(self) -> str | None:
314
+ """Send M650 directly."""
315
+ return await self.send_command_async("~M650")
316
+
317
+ async def custom_m651(self) -> str | None:
318
+ """Send M651 directly."""
319
+ return await self.send_command_async("~M651")
320
+
321
+ async def custom_m652(self) -> str | None:
322
+ """Send M652 directly."""
323
+ return await self.send_command_async("~M652")
324
+
325
+ async def custom_m653(self, params: str) -> bool:
326
+ """Send M653 with parameters."""
327
+ return await self.send_cmd_ok(f"~M653 {params}")
328
+
329
+ async def custom_m654(self, params: str) -> bool:
330
+ """Send M654 with parameters."""
331
+ return await self.send_cmd_ok(f"~M654 {params}")
332
+
333
+ def _parse_file_list(self, response: str) -> list[A3FileEntry]:
334
+ lines = self._get_normalized_lines(response)
335
+ if any("CMD M661 Error." in line for line in lines):
336
+ return []
337
+
338
+ files: list[A3FileEntry] = []
339
+ count_index = next(
340
+ (
341
+ index
342
+ for index, line in enumerate(lines)
343
+ if re.search(r"info_list\.size:\s*\d+", line)
344
+ ),
345
+ -1,
346
+ )
347
+ if count_index == -1:
348
+ return files
349
+
350
+ count_match = re.search(r"info_list\.size:\s*(\d+)", lines[count_index], re.IGNORECASE)
351
+ file_count = int(count_match.group(1)) if count_match else 0
352
+ for line in lines[count_index + 1 :]:
353
+ if len(files) >= file_count:
354
+ break
355
+ if not line or line == "ok" or line.startswith("CMD "):
356
+ continue
357
+ files.append(A3FileEntry(name=line, path=f"/data/{line}"))
358
+
359
+ return files
360
+
361
+ def _parse_thumbnail(self, response: str) -> A3Thumbnail | None:
362
+ buffer = response.encode("latin1")
363
+ error_text = buffer.decode("utf-8", errors="ignore")
364
+ if "Error: File not exists" in error_text:
365
+ return None
366
+
367
+ magic_offset = buffer.find(b"\xa2\xa2\x2a\x2a")
368
+ if magic_offset == -1 or len(buffer) < magic_offset + 8:
369
+ return None
370
+
371
+ payload_length = int.from_bytes(
372
+ buffer[magic_offset + 4 : magic_offset + 8], byteorder="big"
373
+ )
374
+ payload_end = magic_offset + 8 + payload_length
375
+ if len(buffer) < payload_end:
376
+ return None
377
+
378
+ return A3Thumbnail(data=buffer[magic_offset + 8 : payload_end])
379
+
380
+ def _normalize_a3_text_response(self, response: str) -> str:
381
+ normalized = response.replace("\r\n", "\n").replace("\r", "\n")
382
+ lines = normalized.split("\n")
383
+ if lines:
384
+ lines[0] = re.sub(r"^(ack|echo):\s*", "", lines[0], flags=re.IGNORECASE)
385
+ normalized = "\n".join(lines).rstrip()
386
+
387
+ if normalized.startswith('"') and normalized.endswith('"'):
388
+ normalized = normalized[1:-1]
389
+
390
+ return normalized.rstrip()
391
+
392
+ def _get_normalized_lines(self, response: str) -> list[str]:
393
+ return [
394
+ line.strip()
395
+ for line in self._normalize_a3_text_response(response).split("\n")
396
+ if line.strip()
397
+ ]
398
+
399
+ def _map_controller_command(self, cmd: str) -> str:
400
+ if cmd == "~M146 r255 g255 b255 F0":
401
+ return "~M146 1"
402
+ if cmd == "~M146 r0 g0 b0 F0":
403
+ return "~M146 0"
404
+ return cmd
405
+
406
+ def _is_successful_command_response(self, cmd: str, response: str) -> bool:
407
+ normalized = self._normalize_a3_text_response(response).strip()
408
+ if not normalized:
409
+ return self.should_skip_response_wait(cmd)
410
+
411
+ if "Error:" in normalized or "Control failed." in normalized:
412
+ return False
413
+
414
+ bare_cmd = self._strip_protocol_prefix(cmd)
415
+ if bare_cmd.startswith("M23"):
416
+ return "File opened" in normalized or "ok" in normalized
417
+ if bare_cmd.startswith("M112"):
418
+ return (
419
+ bool(re.search(r"Emergency Stop", normalized, re.IGNORECASE))
420
+ or "Received." in normalized
421
+ )
422
+ if "ok" in normalized or "Received." in normalized:
423
+ return True
424
+ return normalized.startswith(bare_cmd)
425
+
426
+ def _strip_protocol_prefix(self, cmd: str) -> str:
427
+ return cmd.strip().removeprefix("~")