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.
- flashforge/__init__.py +137 -56
- flashforge/_removed.py +65 -0
- flashforge/api/__init__.py +12 -18
- flashforge/api/constants/__init__.py +11 -11
- flashforge/api/constants/commands.py +18 -15
- flashforge/api/constants/endpoints.py +11 -11
- flashforge/api/misc/__init__.py +8 -8
- flashforge/api/network/__init__.py +11 -11
- flashforge/api/network/utils.py +71 -71
- flashforge/backends/__init__.py +80 -0
- flashforge/backends/connect.py +275 -0
- flashforge/backends/creator5_backend.py +191 -0
- flashforge/backends/dual_api_backend.py +170 -0
- flashforge/backends/dual_api_models.py +145 -0
- flashforge/backends/http_core.py +431 -0
- flashforge/backends/http_printer_backend.py +254 -0
- flashforge/backends/legacy_backend.py +436 -0
- flashforge/backends/printer_backend.py +217 -0
- flashforge/backends/types.py +125 -0
- flashforge/capabilities/__init__.py +98 -0
- flashforge/capabilities/models.py +67 -0
- flashforge/capabilities/palettes/__init__.py +28 -0
- flashforge/capabilities/palettes/ad5x_palette.py +70 -0
- flashforge/capabilities/palettes/creator5_palette.py +78 -0
- flashforge/capabilities/palettes/palette.py +54 -0
- flashforge/{api/controls/creator5_palette.py → capabilities/palettes/palette_snap.py} +226 -258
- flashforge/capabilities/printer_capabilities.py +145 -0
- flashforge/capabilities/registry.py +125 -0
- flashforge/capabilities/resolve_model.py +61 -0
- flashforge/discovery/__init__.py +39 -39
- flashforge/discovery/discovery.py +150 -77
- flashforge/exceptions.py +90 -51
- flashforge/models/__init__.py +52 -55
- flashforge/models/machine_info.py +540 -543
- flashforge/{api/controls/info.py → models/machine_info_parser.py} +35 -242
- flashforge/models/responses.py +119 -254
- flashforge/status/__init__.py +43 -0
- flashforge/status/printer_snapshot.py +396 -0
- flashforge/tcp/__init__.py +55 -54
- flashforge/tcp/a3_client.py +427 -427
- flashforge/tcp/a4_client.py +304 -304
- flashforge/tcp/ff_client.py +609 -590
- flashforge/tcp/gcode/__init__.py +15 -13
- flashforge/tcp/gcode/a3_gcode_controller.py +109 -109
- flashforge/tcp/gcode/gcode_controller.py +292 -308
- flashforge/tcp/gcode/gcodes.py +81 -99
- flashforge/tcp/gcode/legacy_gcode_controller.py +56 -0
- flashforge/tcp/parsers/__init__.py +27 -27
- flashforge/tcp/parsers/endstop_status.py +248 -248
- flashforge/tcp/parsers/location_info.py +83 -83
- flashforge/tcp/parsers/print_status.py +180 -180
- flashforge/tcp/parsers/printer_info.py +146 -146
- flashforge/tcp/parsers/temp_info.py +218 -218
- flashforge/tcp/parsers/thumbnail_info.py +274 -274
- flashforge/tcp/tcp_client.py +52 -12
- flashforge/threemf/__init__.py +40 -40
- flashforge/threemf/parser.py +560 -560
- flashforge/threemf/warnings.py +58 -58
- {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/METADATA +46 -47
- flashforge_python_api-3.1.0.dist-info/RECORD +69 -0
- {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/WHEEL +1 -1
- {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/licenses/LICENSE +21 -21
- flashforge/api/controls/__init__.py +0 -17
- flashforge/api/controls/control.py +0 -413
- flashforge/api/controls/files.py +0 -210
- flashforge/api/controls/job_control.py +0 -896
- flashforge/api/controls/temp_control.py +0 -309
- flashforge/client.py +0 -609
- flashforge_python_api-1.6.0.dist-info/RECORD +0 -52
- {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/entry_points.txt +0 -0
|
@@ -1,274 +1,274 @@
|
|
|
1
|
-
"""
|
|
2
|
-
FlashForge Python API - Thumbnail Info Parser
|
|
3
|
-
|
|
4
|
-
Handles the parsing, storage, and manipulation of 3D print file thumbnail images.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import asyncio
|
|
8
|
-
import base64
|
|
9
|
-
import logging
|
|
10
|
-
from pathlib import Path
|
|
11
|
-
from typing import Optional
|
|
12
|
-
|
|
13
|
-
logger = logging.getLogger(__name__)
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
class ThumbnailInfo:
|
|
17
|
-
"""
|
|
18
|
-
Handles the parsing, storage, and manipulation of 3D print file thumbnail images.
|
|
19
|
-
|
|
20
|
-
Thumbnails are typically retrieved from the printer using a command like M662,
|
|
21
|
-
which returns a mixed response containing text (e.g., "ok") followed by raw binary PNG data.
|
|
22
|
-
This class provides methods to extract the PNG data, convert it to various formats, and save it to a file.
|
|
23
|
-
"""
|
|
24
|
-
|
|
25
|
-
def __init__(self) -> None:
|
|
26
|
-
"""Initialize a new ThumbnailInfo instance."""
|
|
27
|
-
self._image_data: bytes | None = None
|
|
28
|
-
self._file_name: str | None = None
|
|
29
|
-
|
|
30
|
-
def from_replay(self, replay: str, file_name: str) -> Optional["ThumbnailInfo"]:
|
|
31
|
-
"""
|
|
32
|
-
Parses thumbnail data from a raw printer response string.
|
|
33
|
-
|
|
34
|
-
The method expects the response to contain an "ok" text delimiter, after which
|
|
35
|
-
the binary PNG data begins. It searches for the PNG signature (0x89 PNG)
|
|
36
|
-
within the binary portion to correctly extract the image.
|
|
37
|
-
|
|
38
|
-
Args:
|
|
39
|
-
replay: The raw string response from the printer, which may include text and binary data
|
|
40
|
-
file_name: The name of the file for which the thumbnail was retrieved
|
|
41
|
-
|
|
42
|
-
Returns:
|
|
43
|
-
A ThumbnailInfo instance populated with the image data if parsing is successful,
|
|
44
|
-
or None if the replay is invalid, "ok" is not found, or the PNG signature is missing
|
|
45
|
-
"""
|
|
46
|
-
if not replay:
|
|
47
|
-
return None
|
|
48
|
-
|
|
49
|
-
try:
|
|
50
|
-
# Store the file name
|
|
51
|
-
self._file_name = file_name
|
|
52
|
-
if "Error: File not exists" in replay:
|
|
53
|
-
return None
|
|
54
|
-
|
|
55
|
-
binary_buffer = replay.encode("latin1")
|
|
56
|
-
magic_marker = b"\xa2\xa2\x2a\x2a"
|
|
57
|
-
magic_offset = binary_buffer.find(magic_marker)
|
|
58
|
-
if magic_offset >= 0 and len(binary_buffer) >= magic_offset + 8:
|
|
59
|
-
payload_length = int.from_bytes(
|
|
60
|
-
binary_buffer[magic_offset + 4 : magic_offset + 8],
|
|
61
|
-
byteorder="big",
|
|
62
|
-
)
|
|
63
|
-
payload_end = magic_offset + 8 + payload_length
|
|
64
|
-
if len(binary_buffer) >= payload_end:
|
|
65
|
-
self._image_data = binary_buffer[magic_offset + 8 : payload_end]
|
|
66
|
-
return self
|
|
67
|
-
|
|
68
|
-
# Find where the PNG data starts (after the "ok" text delimiter)
|
|
69
|
-
ok_index = replay.find("ok")
|
|
70
|
-
if ok_index == -1:
|
|
71
|
-
logger.warning("ThumbnailInfo: no 'ok' delimiter found in the response.")
|
|
72
|
-
return None
|
|
73
|
-
|
|
74
|
-
# Skip the 'ok' text and any immediately following control characters
|
|
75
|
-
# The actual binary data starts after "ok"
|
|
76
|
-
binary_start_index = ok_index + 2 # Length of "ok"
|
|
77
|
-
raw_binary_data = replay[binary_start_index:]
|
|
78
|
-
|
|
79
|
-
# Convert the extracted string part (assumed to be binary) into bytes
|
|
80
|
-
# The printer sends binary data as part of a string reply
|
|
81
|
-
binary_buffer = raw_binary_data.encode("latin1") # Use latin1 to preserve byte values
|
|
82
|
-
|
|
83
|
-
# Look for the PNG file signature (89 50 4E 47 0D 0A 1A 0A) in the buffer
|
|
84
|
-
# to correctly identify the start of the actual image data
|
|
85
|
-
png_signature = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
|
|
86
|
-
png_start = binary_buffer.find(png_signature)
|
|
87
|
-
|
|
88
|
-
if png_start >= 0:
|
|
89
|
-
# Slice the buffer from the start of the PNG signature to get the clean image data
|
|
90
|
-
self._image_data = binary_buffer[png_start:]
|
|
91
|
-
return self
|
|
92
|
-
else:
|
|
93
|
-
logger.warning("ThumbnailInfo: no PNG signature found in the binary data.")
|
|
94
|
-
return None
|
|
95
|
-
|
|
96
|
-
except Exception as e:
|
|
97
|
-
logger.warning("ThumbnailInfo: error parsing the response: %s", e)
|
|
98
|
-
return None
|
|
99
|
-
|
|
100
|
-
def get_image_data(self) -> str | None:
|
|
101
|
-
"""
|
|
102
|
-
Gets the raw thumbnail image data as a Base64 encoded string.
|
|
103
|
-
|
|
104
|
-
Returns:
|
|
105
|
-
A Base64 encoded string of the PNG image data, or None if no image data is available
|
|
106
|
-
"""
|
|
107
|
-
if not self._image_data:
|
|
108
|
-
return None
|
|
109
|
-
return base64.b64encode(self._image_data).decode("ascii")
|
|
110
|
-
|
|
111
|
-
def get_image_bytes(self) -> bytes | None:
|
|
112
|
-
"""
|
|
113
|
-
Gets the raw thumbnail image data as bytes.
|
|
114
|
-
|
|
115
|
-
Returns:
|
|
116
|
-
The PNG image data as bytes, or None if no image data is available
|
|
117
|
-
"""
|
|
118
|
-
return self._image_data
|
|
119
|
-
|
|
120
|
-
def get_file_name(self) -> str | None:
|
|
121
|
-
"""
|
|
122
|
-
Gets the file name associated with this thumbnail.
|
|
123
|
-
|
|
124
|
-
Returns:
|
|
125
|
-
The file name string, or None if it was not set during parsing
|
|
126
|
-
"""
|
|
127
|
-
return self._file_name
|
|
128
|
-
|
|
129
|
-
def to_base64_data_url(self) -> str | None:
|
|
130
|
-
"""
|
|
131
|
-
Converts the thumbnail image data to a Base64 data URL, suitable for embedding in web pages.
|
|
132
|
-
|
|
133
|
-
Returns:
|
|
134
|
-
A Base64 data URL string (e.g., "data:image/png;base64,..."), or None if no image data is available
|
|
135
|
-
"""
|
|
136
|
-
if not self._image_data:
|
|
137
|
-
return None
|
|
138
|
-
|
|
139
|
-
base64_data = base64.b64encode(self._image_data).decode("ascii")
|
|
140
|
-
return f"data:image/png;base64,{base64_data}"
|
|
141
|
-
|
|
142
|
-
@staticmethod
|
|
143
|
-
def _write_file_sync(file_path: str, data: bytes) -> None:
|
|
144
|
-
"""Helper to write bytes to a file synchronously."""
|
|
145
|
-
with open(file_path, "wb") as f:
|
|
146
|
-
f.write(data)
|
|
147
|
-
|
|
148
|
-
async def save_to_file(self, file_path: str | None = None) -> bool:
|
|
149
|
-
"""
|
|
150
|
-
Saves the thumbnail image data to a file.
|
|
151
|
-
|
|
152
|
-
If no file_path is provided, it attempts to generate a filename using the
|
|
153
|
-
original filename (stored during from_replay) with a ".png" extension.
|
|
154
|
-
|
|
155
|
-
Args:
|
|
156
|
-
file_path: Optional. The full path (including filename and extension) where the thumbnail should be saved.
|
|
157
|
-
If not provided, a filename is generated from self._file_name
|
|
158
|
-
|
|
159
|
-
Returns:
|
|
160
|
-
True if the file was saved successfully, False otherwise
|
|
161
|
-
"""
|
|
162
|
-
if not self._image_data:
|
|
163
|
-
logger.warning("ThumbnailInfo: no image data to save.")
|
|
164
|
-
return False
|
|
165
|
-
|
|
166
|
-
try:
|
|
167
|
-
# If no file path is provided, generate one based on the original filename
|
|
168
|
-
if not file_path and self._file_name:
|
|
169
|
-
# Extract the filename without extension
|
|
170
|
-
path_obj = Path(self._file_name)
|
|
171
|
-
base_name = path_obj.stem
|
|
172
|
-
file_path = f"{base_name}.png"
|
|
173
|
-
|
|
174
|
-
if not file_path:
|
|
175
|
-
logger.warning(
|
|
176
|
-
"ThumbnailInfo: no file path provided and no filename to generate one from."
|
|
177
|
-
)
|
|
178
|
-
return False
|
|
179
|
-
|
|
180
|
-
# Write the bytes to file in a separate thread to avoid blocking the event loop
|
|
181
|
-
loop = asyncio.get_running_loop()
|
|
182
|
-
await loop.run_in_executor(None, self._write_file_sync, file_path, self._image_data)
|
|
183
|
-
|
|
184
|
-
logger.debug("ThumbnailInfo: saved the thumbnail to %s", file_path)
|
|
185
|
-
return True
|
|
186
|
-
|
|
187
|
-
except Exception as e:
|
|
188
|
-
logger.warning("ThumbnailInfo: error saving the thumbnail to a file: %s", e)
|
|
189
|
-
return False
|
|
190
|
-
|
|
191
|
-
def save_to_file_sync(self, file_path: str | None = None) -> bool:
|
|
192
|
-
"""
|
|
193
|
-
Synchronous version of save_to_file for compatibility.
|
|
194
|
-
|
|
195
|
-
Args:
|
|
196
|
-
file_path: Optional. The full path where the thumbnail should be saved
|
|
197
|
-
|
|
198
|
-
Returns:
|
|
199
|
-
True if the file was saved successfully, False otherwise
|
|
200
|
-
"""
|
|
201
|
-
if not self._image_data:
|
|
202
|
-
logger.warning("ThumbnailInfo: no image data to save.")
|
|
203
|
-
return False
|
|
204
|
-
|
|
205
|
-
try:
|
|
206
|
-
# If no file path is provided, generate one based on the original filename
|
|
207
|
-
if not file_path and self._file_name:
|
|
208
|
-
# Extract the filename without extension
|
|
209
|
-
path_obj = Path(self._file_name)
|
|
210
|
-
base_name = path_obj.stem
|
|
211
|
-
file_path = f"{base_name}.png"
|
|
212
|
-
|
|
213
|
-
if not file_path:
|
|
214
|
-
logger.warning(
|
|
215
|
-
"ThumbnailInfo: no file path provided and no filename to generate one from."
|
|
216
|
-
)
|
|
217
|
-
return False
|
|
218
|
-
|
|
219
|
-
# Write the bytes to file
|
|
220
|
-
with open(file_path, "wb") as f:
|
|
221
|
-
f.write(self._image_data)
|
|
222
|
-
|
|
223
|
-
logger.debug("ThumbnailInfo: saved the thumbnail to %s", file_path)
|
|
224
|
-
return True
|
|
225
|
-
|
|
226
|
-
except Exception as e:
|
|
227
|
-
logger.warning("ThumbnailInfo: error saving the thumbnail to a file: %s", e)
|
|
228
|
-
return False
|
|
229
|
-
|
|
230
|
-
def get_image_size(self) -> tuple[int, int]:
|
|
231
|
-
"""
|
|
232
|
-
Gets the image dimensions by parsing the PNG header.
|
|
233
|
-
|
|
234
|
-
Returns:
|
|
235
|
-
A tuple of (width, height) in pixels, or (0, 0) if parsing fails
|
|
236
|
-
"""
|
|
237
|
-
if not self._image_data or len(self._image_data) < 24:
|
|
238
|
-
return (0, 0)
|
|
239
|
-
|
|
240
|
-
try:
|
|
241
|
-
# PNG width and height are stored at bytes 16-23 in big-endian format
|
|
242
|
-
width = int.from_bytes(self._image_data[16:20], byteorder="big")
|
|
243
|
-
height = int.from_bytes(self._image_data[20:24], byteorder="big")
|
|
244
|
-
return (width, height)
|
|
245
|
-
except Exception:
|
|
246
|
-
return (0, 0)
|
|
247
|
-
|
|
248
|
-
def has_image_data(self) -> bool:
|
|
249
|
-
"""
|
|
250
|
-
Checks if this instance contains valid image data.
|
|
251
|
-
|
|
252
|
-
Returns:
|
|
253
|
-
True if image data is available, False otherwise
|
|
254
|
-
"""
|
|
255
|
-
return self._image_data is not None and len(self._image_data) > 0
|
|
256
|
-
|
|
257
|
-
def __str__(self) -> str:
|
|
258
|
-
"""String representation of the thumbnail info."""
|
|
259
|
-
if self._image_data:
|
|
260
|
-
width, height = self.get_image_size()
|
|
261
|
-
size_str = f"{len(self._image_data)} bytes, {width}x{height}px"
|
|
262
|
-
else:
|
|
263
|
-
size_str = "no data"
|
|
264
|
-
|
|
265
|
-
return f"ThumbnailInfo(file='{self._file_name}', {size_str})"
|
|
266
|
-
|
|
267
|
-
def __repr__(self) -> str:
|
|
268
|
-
"""Detailed string representation for debugging."""
|
|
269
|
-
return (
|
|
270
|
-
f"ThumbnailInfo("
|
|
271
|
-
f"file_name='{self._file_name}', "
|
|
272
|
-
f"has_data={self.has_image_data()}, "
|
|
273
|
-
f"size={len(self._image_data) if self._image_data else 0} bytes)"
|
|
274
|
-
)
|
|
1
|
+
"""
|
|
2
|
+
FlashForge Python API - Thumbnail Info Parser
|
|
3
|
+
|
|
4
|
+
Handles the parsing, storage, and manipulation of 3D print file thumbnail images.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import base64
|
|
9
|
+
import logging
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ThumbnailInfo:
|
|
17
|
+
"""
|
|
18
|
+
Handles the parsing, storage, and manipulation of 3D print file thumbnail images.
|
|
19
|
+
|
|
20
|
+
Thumbnails are typically retrieved from the printer using a command like M662,
|
|
21
|
+
which returns a mixed response containing text (e.g., "ok") followed by raw binary PNG data.
|
|
22
|
+
This class provides methods to extract the PNG data, convert it to various formats, and save it to a file.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self) -> None:
|
|
26
|
+
"""Initialize a new ThumbnailInfo instance."""
|
|
27
|
+
self._image_data: bytes | None = None
|
|
28
|
+
self._file_name: str | None = None
|
|
29
|
+
|
|
30
|
+
def from_replay(self, replay: str, file_name: str) -> Optional["ThumbnailInfo"]:
|
|
31
|
+
"""
|
|
32
|
+
Parses thumbnail data from a raw printer response string.
|
|
33
|
+
|
|
34
|
+
The method expects the response to contain an "ok" text delimiter, after which
|
|
35
|
+
the binary PNG data begins. It searches for the PNG signature (0x89 PNG)
|
|
36
|
+
within the binary portion to correctly extract the image.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
replay: The raw string response from the printer, which may include text and binary data
|
|
40
|
+
file_name: The name of the file for which the thumbnail was retrieved
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
A ThumbnailInfo instance populated with the image data if parsing is successful,
|
|
44
|
+
or None if the replay is invalid, "ok" is not found, or the PNG signature is missing
|
|
45
|
+
"""
|
|
46
|
+
if not replay:
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
# Store the file name
|
|
51
|
+
self._file_name = file_name
|
|
52
|
+
if "Error: File not exists" in replay:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
binary_buffer = replay.encode("latin1")
|
|
56
|
+
magic_marker = b"\xa2\xa2\x2a\x2a"
|
|
57
|
+
magic_offset = binary_buffer.find(magic_marker)
|
|
58
|
+
if magic_offset >= 0 and len(binary_buffer) >= magic_offset + 8:
|
|
59
|
+
payload_length = int.from_bytes(
|
|
60
|
+
binary_buffer[magic_offset + 4 : magic_offset + 8],
|
|
61
|
+
byteorder="big",
|
|
62
|
+
)
|
|
63
|
+
payload_end = magic_offset + 8 + payload_length
|
|
64
|
+
if len(binary_buffer) >= payload_end:
|
|
65
|
+
self._image_data = binary_buffer[magic_offset + 8 : payload_end]
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
# Find where the PNG data starts (after the "ok" text delimiter)
|
|
69
|
+
ok_index = replay.find("ok")
|
|
70
|
+
if ok_index == -1:
|
|
71
|
+
logger.warning("ThumbnailInfo: no 'ok' delimiter found in the response.")
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
# Skip the 'ok' text and any immediately following control characters
|
|
75
|
+
# The actual binary data starts after "ok"
|
|
76
|
+
binary_start_index = ok_index + 2 # Length of "ok"
|
|
77
|
+
raw_binary_data = replay[binary_start_index:]
|
|
78
|
+
|
|
79
|
+
# Convert the extracted string part (assumed to be binary) into bytes
|
|
80
|
+
# The printer sends binary data as part of a string reply
|
|
81
|
+
binary_buffer = raw_binary_data.encode("latin1") # Use latin1 to preserve byte values
|
|
82
|
+
|
|
83
|
+
# Look for the PNG file signature (89 50 4E 47 0D 0A 1A 0A) in the buffer
|
|
84
|
+
# to correctly identify the start of the actual image data
|
|
85
|
+
png_signature = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
|
|
86
|
+
png_start = binary_buffer.find(png_signature)
|
|
87
|
+
|
|
88
|
+
if png_start >= 0:
|
|
89
|
+
# Slice the buffer from the start of the PNG signature to get the clean image data
|
|
90
|
+
self._image_data = binary_buffer[png_start:]
|
|
91
|
+
return self
|
|
92
|
+
else:
|
|
93
|
+
logger.warning("ThumbnailInfo: no PNG signature found in the binary data.")
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.warning("ThumbnailInfo: error parsing the response: %s", e)
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
def get_image_data(self) -> str | None:
|
|
101
|
+
"""
|
|
102
|
+
Gets the raw thumbnail image data as a Base64 encoded string.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
A Base64 encoded string of the PNG image data, or None if no image data is available
|
|
106
|
+
"""
|
|
107
|
+
if not self._image_data:
|
|
108
|
+
return None
|
|
109
|
+
return base64.b64encode(self._image_data).decode("ascii")
|
|
110
|
+
|
|
111
|
+
def get_image_bytes(self) -> bytes | None:
|
|
112
|
+
"""
|
|
113
|
+
Gets the raw thumbnail image data as bytes.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
The PNG image data as bytes, or None if no image data is available
|
|
117
|
+
"""
|
|
118
|
+
return self._image_data
|
|
119
|
+
|
|
120
|
+
def get_file_name(self) -> str | None:
|
|
121
|
+
"""
|
|
122
|
+
Gets the file name associated with this thumbnail.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
The file name string, or None if it was not set during parsing
|
|
126
|
+
"""
|
|
127
|
+
return self._file_name
|
|
128
|
+
|
|
129
|
+
def to_base64_data_url(self) -> str | None:
|
|
130
|
+
"""
|
|
131
|
+
Converts the thumbnail image data to a Base64 data URL, suitable for embedding in web pages.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
A Base64 data URL string (e.g., "data:image/png;base64,..."), or None if no image data is available
|
|
135
|
+
"""
|
|
136
|
+
if not self._image_data:
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
base64_data = base64.b64encode(self._image_data).decode("ascii")
|
|
140
|
+
return f"data:image/png;base64,{base64_data}"
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _write_file_sync(file_path: str, data: bytes) -> None:
|
|
144
|
+
"""Helper to write bytes to a file synchronously."""
|
|
145
|
+
with open(file_path, "wb") as f:
|
|
146
|
+
f.write(data)
|
|
147
|
+
|
|
148
|
+
async def save_to_file(self, file_path: str | None = None) -> bool:
|
|
149
|
+
"""
|
|
150
|
+
Saves the thumbnail image data to a file.
|
|
151
|
+
|
|
152
|
+
If no file_path is provided, it attempts to generate a filename using the
|
|
153
|
+
original filename (stored during from_replay) with a ".png" extension.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
file_path: Optional. The full path (including filename and extension) where the thumbnail should be saved.
|
|
157
|
+
If not provided, a filename is generated from self._file_name
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
True if the file was saved successfully, False otherwise
|
|
161
|
+
"""
|
|
162
|
+
if not self._image_data:
|
|
163
|
+
logger.warning("ThumbnailInfo: no image data to save.")
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
# If no file path is provided, generate one based on the original filename
|
|
168
|
+
if not file_path and self._file_name:
|
|
169
|
+
# Extract the filename without extension
|
|
170
|
+
path_obj = Path(self._file_name)
|
|
171
|
+
base_name = path_obj.stem
|
|
172
|
+
file_path = f"{base_name}.png"
|
|
173
|
+
|
|
174
|
+
if not file_path:
|
|
175
|
+
logger.warning(
|
|
176
|
+
"ThumbnailInfo: no file path provided and no filename to generate one from."
|
|
177
|
+
)
|
|
178
|
+
return False
|
|
179
|
+
|
|
180
|
+
# Write the bytes to file in a separate thread to avoid blocking the event loop
|
|
181
|
+
loop = asyncio.get_running_loop()
|
|
182
|
+
await loop.run_in_executor(None, self._write_file_sync, file_path, self._image_data)
|
|
183
|
+
|
|
184
|
+
logger.debug("ThumbnailInfo: saved the thumbnail to %s", file_path)
|
|
185
|
+
return True
|
|
186
|
+
|
|
187
|
+
except Exception as e:
|
|
188
|
+
logger.warning("ThumbnailInfo: error saving the thumbnail to a file: %s", e)
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
def save_to_file_sync(self, file_path: str | None = None) -> bool:
|
|
192
|
+
"""
|
|
193
|
+
Synchronous version of save_to_file for compatibility.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
file_path: Optional. The full path where the thumbnail should be saved
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
True if the file was saved successfully, False otherwise
|
|
200
|
+
"""
|
|
201
|
+
if not self._image_data:
|
|
202
|
+
logger.warning("ThumbnailInfo: no image data to save.")
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
try:
|
|
206
|
+
# If no file path is provided, generate one based on the original filename
|
|
207
|
+
if not file_path and self._file_name:
|
|
208
|
+
# Extract the filename without extension
|
|
209
|
+
path_obj = Path(self._file_name)
|
|
210
|
+
base_name = path_obj.stem
|
|
211
|
+
file_path = f"{base_name}.png"
|
|
212
|
+
|
|
213
|
+
if not file_path:
|
|
214
|
+
logger.warning(
|
|
215
|
+
"ThumbnailInfo: no file path provided and no filename to generate one from."
|
|
216
|
+
)
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
# Write the bytes to file
|
|
220
|
+
with open(file_path, "wb") as f:
|
|
221
|
+
f.write(self._image_data)
|
|
222
|
+
|
|
223
|
+
logger.debug("ThumbnailInfo: saved the thumbnail to %s", file_path)
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
except Exception as e:
|
|
227
|
+
logger.warning("ThumbnailInfo: error saving the thumbnail to a file: %s", e)
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
def get_image_size(self) -> tuple[int, int]:
|
|
231
|
+
"""
|
|
232
|
+
Gets the image dimensions by parsing the PNG header.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
A tuple of (width, height) in pixels, or (0, 0) if parsing fails
|
|
236
|
+
"""
|
|
237
|
+
if not self._image_data or len(self._image_data) < 24:
|
|
238
|
+
return (0, 0)
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
# PNG width and height are stored at bytes 16-23 in big-endian format
|
|
242
|
+
width = int.from_bytes(self._image_data[16:20], byteorder="big")
|
|
243
|
+
height = int.from_bytes(self._image_data[20:24], byteorder="big")
|
|
244
|
+
return (width, height)
|
|
245
|
+
except Exception:
|
|
246
|
+
return (0, 0)
|
|
247
|
+
|
|
248
|
+
def has_image_data(self) -> bool:
|
|
249
|
+
"""
|
|
250
|
+
Checks if this instance contains valid image data.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
True if image data is available, False otherwise
|
|
254
|
+
"""
|
|
255
|
+
return self._image_data is not None and len(self._image_data) > 0
|
|
256
|
+
|
|
257
|
+
def __str__(self) -> str:
|
|
258
|
+
"""String representation of the thumbnail info."""
|
|
259
|
+
if self._image_data:
|
|
260
|
+
width, height = self.get_image_size()
|
|
261
|
+
size_str = f"{len(self._image_data)} bytes, {width}x{height}px"
|
|
262
|
+
else:
|
|
263
|
+
size_str = "no data"
|
|
264
|
+
|
|
265
|
+
return f"ThumbnailInfo(file='{self._file_name}', {size_str})"
|
|
266
|
+
|
|
267
|
+
def __repr__(self) -> str:
|
|
268
|
+
"""Detailed string representation for debugging."""
|
|
269
|
+
return (
|
|
270
|
+
f"ThumbnailInfo("
|
|
271
|
+
f"file_name='{self._file_name}', "
|
|
272
|
+
f"has_data={self.has_image_data()}, "
|
|
273
|
+
f"size={len(self._image_data) if self._image_data else 0} bytes)"
|
|
274
|
+
)
|
flashforge/tcp/tcp_client.py
CHANGED
|
@@ -49,12 +49,16 @@ class FlashForgeTcpClient:
|
|
|
49
49
|
self._keep_alive_cancellation_token = False
|
|
50
50
|
self._keep_alive_errors = 0
|
|
51
51
|
self._socket_lock = asyncio.Lock()
|
|
52
|
+
#: Set by dispose(). A disposed client never opens a socket again.
|
|
53
|
+
self._disposed = False
|
|
52
54
|
|
|
53
55
|
logger.info("TcpPrinterClient creation")
|
|
54
56
|
logger.info("Initialized (connection will be established on first command)")
|
|
55
57
|
|
|
56
58
|
async def start_keep_alive(self) -> None:
|
|
57
|
-
"""Start the TCP keep-alive loop."""
|
|
59
|
+
"""Start the TCP keep-alive loop. Does nothing after dispose()."""
|
|
60
|
+
if self._disposed:
|
|
61
|
+
return
|
|
58
62
|
if self._keep_alive_task and not self._keep_alive_task.done():
|
|
59
63
|
return
|
|
60
64
|
|
|
@@ -127,7 +131,8 @@ class FlashForgeTcpClient:
|
|
|
127
131
|
|
|
128
132
|
logger.warning("Invalid or no reply received, resetting connection to printer.")
|
|
129
133
|
await self._reset_socket()
|
|
130
|
-
|
|
134
|
+
if not self._disposed:
|
|
135
|
+
await self._check_socket()
|
|
131
136
|
return None
|
|
132
137
|
|
|
133
138
|
except Exception as error:
|
|
@@ -197,7 +202,12 @@ class FlashForgeTcpClient:
|
|
|
197
202
|
return False
|
|
198
203
|
|
|
199
204
|
async def _check_socket(self) -> None:
|
|
200
|
-
"""Reconnect the TCP socket if it is not ready."""
|
|
205
|
+
"""Reconnect the TCP socket if it is not ready. Never reconnects after dispose()."""
|
|
206
|
+
# After dispose() a pending login retry must not open a new connection (and lock the
|
|
207
|
+
# printer).
|
|
208
|
+
if self._disposed:
|
|
209
|
+
return
|
|
210
|
+
|
|
201
211
|
fix = False
|
|
202
212
|
|
|
203
213
|
if self._writer is None or self._reader is None:
|
|
@@ -236,7 +246,11 @@ class FlashForgeTcpClient:
|
|
|
236
246
|
self._writer = None
|
|
237
247
|
|
|
238
248
|
async def _receive_multi_line_replay_async(self, cmd: str) -> str | None:
|
|
239
|
-
"""
|
|
249
|
+
"""
|
|
250
|
+
Receive a complete multi-line reply for the given command.
|
|
251
|
+
|
|
252
|
+
Ends at once when the socket closes (dispose, printer reset): the read then sees EOF.
|
|
253
|
+
"""
|
|
240
254
|
if not self._reader:
|
|
241
255
|
return None
|
|
242
256
|
|
|
@@ -402,18 +416,37 @@ class FlashForgeTcpClient:
|
|
|
402
416
|
return file_paths
|
|
403
417
|
|
|
404
418
|
async def dispose(self) -> None:
|
|
405
|
-
"""
|
|
419
|
+
"""
|
|
420
|
+
Clean up resources by closing the socket connection.
|
|
421
|
+
|
|
422
|
+
Writes the logout (``~M602``) so the printer releases its control lock, but does not
|
|
423
|
+
wait for a reply: a printer that does not answer would keep the socket (and the lock)
|
|
424
|
+
open for the full command timeout. Waits at most 0.5 s for the write to flush. A reply
|
|
425
|
+
that is still pending ends when the socket closes. After dispose() the client never
|
|
426
|
+
opens a socket again.
|
|
427
|
+
"""
|
|
406
428
|
try:
|
|
407
429
|
logger.info("TcpPrinterClient closing socket")
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
430
|
+
self._disposed = True
|
|
431
|
+
await self.stop_keep_alive()
|
|
432
|
+
|
|
433
|
+
writer = self._writer
|
|
434
|
+
self._reader = None
|
|
435
|
+
self._writer = None
|
|
436
|
+
if writer is None:
|
|
437
|
+
return
|
|
438
|
+
if not writer.is_closing():
|
|
411
439
|
try:
|
|
412
|
-
|
|
440
|
+
writer.write((GCodes.CMD_LOGOUT + "\n").encode("ascii"))
|
|
441
|
+
await asyncio.wait_for(writer.drain(), timeout=0.5)
|
|
413
442
|
except Exception:
|
|
443
|
+
# Logout errors during disposal are acceptable - the socket must close.
|
|
414
444
|
pass
|
|
415
|
-
|
|
416
|
-
|
|
445
|
+
writer.close()
|
|
446
|
+
try:
|
|
447
|
+
await asyncio.wait_for(writer.wait_closed(), timeout=0.5)
|
|
448
|
+
except Exception:
|
|
449
|
+
writer.transport.abort()
|
|
417
450
|
except Exception as error:
|
|
418
451
|
logger.error("Error during dispose: %s", error)
|
|
419
452
|
|
|
@@ -436,12 +469,19 @@ class FlashForgeTcpClient:
|
|
|
436
469
|
if not normalized:
|
|
437
470
|
return False
|
|
438
471
|
|
|
472
|
+
# The firmware spells the M29 size-mismatch error "File Is Not Aviable".
|
|
439
473
|
if re.search(
|
|
440
|
-
r"error:|control failed\.|file is not
|
|
474
|
+
r"error:|control failed\.|file is not av(?:ai|ia)l?able|cannot create file|not enough space",
|
|
441
475
|
normalized,
|
|
442
476
|
flags=re.IGNORECASE,
|
|
443
477
|
):
|
|
444
478
|
return False
|
|
479
|
+
# M29 also reports both sizes: "filesize = <expected> tofile.size = <actual>".
|
|
480
|
+
sizes = re.search(
|
|
481
|
+
r"filesize\s*=\s*(\d+)\s+tofile\.size\s*=\s*(\d+)", normalized, flags=re.IGNORECASE
|
|
482
|
+
)
|
|
483
|
+
if sizes and sizes.group(1) != sizes.group(2):
|
|
484
|
+
return False
|
|
445
485
|
|
|
446
486
|
bare_command = cmd.strip().removeprefix("~").split(maxsplit=1)[0]
|
|
447
487
|
return (
|