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
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared HTTP transport for the modern printers (port 8898).
|
|
3
|
+
|
|
4
|
+
This is the base layer under every HTTP backend (dual-API and HTTP-only). It owns the
|
|
5
|
+
aiohttp session, the credentials, the FIFO command lock, the shared request shapes and
|
|
6
|
+
the camera probe. It has no model logic: a backend decides what to send, this class only
|
|
7
|
+
sends it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import logging
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import aiohttp
|
|
19
|
+
from pydantic import ValidationError
|
|
20
|
+
|
|
21
|
+
from ..api.constants.endpoints import CAMERA_STREAM_PORT, Endpoints
|
|
22
|
+
from ..api.misc.redaction import redact_mapping, redact_model
|
|
23
|
+
from ..api.network.utils import NetworkUtils, json_from_response
|
|
24
|
+
from ..exceptions import FlashForgeResponseError
|
|
25
|
+
from ..models.machine_info import FFGcodeFileEntry
|
|
26
|
+
from ..models.responses import (
|
|
27
|
+
DetailResponse,
|
|
28
|
+
GCodeListResponse,
|
|
29
|
+
GenericResponse,
|
|
30
|
+
ProductResponse,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
#: Uploads have no total limit (large files over printer Wi-Fi take minutes), but keep
|
|
36
|
+
#: connect and read limits so a printer that stops answering is still caught.
|
|
37
|
+
UPLOAD_TIMEOUT = aiohttp.ClientTimeout(total=None, sock_connect=30, sock_read=300)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class DetailResult:
|
|
42
|
+
"""Result of ``POST /detail``. Exactly one of ``response`` or ``error`` is set."""
|
|
43
|
+
|
|
44
|
+
response: DetailResponse | None
|
|
45
|
+
#: Plain-language reason when the request failed or the printer rejected it.
|
|
46
|
+
error: str | None
|
|
47
|
+
#: The printer's code when it rejected the request (-2, 1, -1, ...), else None.
|
|
48
|
+
code: int | None = None
|
|
49
|
+
#: False when the HTTP API did not answer at all (network error or a non-200 status), as
|
|
50
|
+
#: opposed to a printer that answered and rejected the request.
|
|
51
|
+
reachable: bool = True
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def describe_detail_rejection(code: int, message: str) -> str:
|
|
55
|
+
"""
|
|
56
|
+
Turns a rejected ``/detail`` response into a plain-language reason.
|
|
57
|
+
|
|
58
|
+
Codes: -2 = LAN-only mode is off, 1 = wrong serial number or check code (the
|
|
59
|
+
message says which), -1 = missing or malformed fields.
|
|
60
|
+
"""
|
|
61
|
+
raw = f'(code {code}, "{message}")'
|
|
62
|
+
if code == -2:
|
|
63
|
+
return f"The printer is not in LAN-only mode. Turn on LAN-only mode on the printer {raw}"
|
|
64
|
+
if code == 1:
|
|
65
|
+
if "sn is different" in message.lower():
|
|
66
|
+
return f"The serial number is wrong {raw}"
|
|
67
|
+
if "access code is different" in message.lower():
|
|
68
|
+
return f"The check code is wrong {raw}"
|
|
69
|
+
return f"The printer rejected the serial number or check code {raw}"
|
|
70
|
+
if code == -1:
|
|
71
|
+
return f"The printer rejected the request parameters {raw}"
|
|
72
|
+
return f"The printer rejected the request {raw}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def _local_file_size(file_path: str) -> int | None:
|
|
76
|
+
"""Size of a local file, or None if it is not a regular file. Runs off the event loop."""
|
|
77
|
+
|
|
78
|
+
def _size() -> int | None:
|
|
79
|
+
path = Path(file_path)
|
|
80
|
+
return path.stat().st_size if path.is_file() else None
|
|
81
|
+
|
|
82
|
+
return await asyncio.to_thread(_size)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class HttpCore:
|
|
86
|
+
"""HTTP transport shared by every modern backend."""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
ip_address: str,
|
|
91
|
+
serial_number: str,
|
|
92
|
+
check_code: str,
|
|
93
|
+
*,
|
|
94
|
+
http_port: int | None = None,
|
|
95
|
+
timeout_s: float = 15.0,
|
|
96
|
+
) -> None:
|
|
97
|
+
self.ip_address = ip_address
|
|
98
|
+
self.serial_number = serial_number
|
|
99
|
+
self.check_code = check_code
|
|
100
|
+
self._port = http_port if http_port is not None else 8898
|
|
101
|
+
self._timeout_s = timeout_s
|
|
102
|
+
self._session: aiohttp.ClientSession | None = None
|
|
103
|
+
# FIFO lock for command POSTs (/product, /control, /printGcode). asyncio.Lock
|
|
104
|
+
# serves waiters in arrival order, so commands run one at a time. Uploads and
|
|
105
|
+
# reads stay off it: an upload can run for minutes, and pause or stop must
|
|
106
|
+
# never wait behind one.
|
|
107
|
+
self._command_lock = asyncio.Lock()
|
|
108
|
+
self._queued = 0
|
|
109
|
+
|
|
110
|
+
# ---- Basics --------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def busy(self) -> bool:
|
|
114
|
+
"""True while at least one command is queued or in flight."""
|
|
115
|
+
return self._queued > 0
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def command_lock(self) -> asyncio.Lock:
|
|
119
|
+
"""The FIFO lock that serializes command POSTs."""
|
|
120
|
+
return self._command_lock
|
|
121
|
+
|
|
122
|
+
def url(self, endpoint: str) -> str:
|
|
123
|
+
"""Full URL for an API path."""
|
|
124
|
+
return f"http://{self.ip_address}:{self._port}{endpoint}"
|
|
125
|
+
|
|
126
|
+
def credentials(self) -> dict[str, str]:
|
|
127
|
+
"""The serial number and check code that every request body carries."""
|
|
128
|
+
return {"serialNumber": self.serial_number, "checkCode": self.check_code}
|
|
129
|
+
|
|
130
|
+
async def session(self) -> aiohttp.ClientSession:
|
|
131
|
+
"""The shared aiohttp session (created on first use)."""
|
|
132
|
+
if self._session is None or self._session.closed:
|
|
133
|
+
self._session = aiohttp.ClientSession(
|
|
134
|
+
timeout=aiohttp.ClientTimeout(total=self._timeout_s),
|
|
135
|
+
headers={"Accept": "*/*"},
|
|
136
|
+
)
|
|
137
|
+
return self._session
|
|
138
|
+
|
|
139
|
+
async def close(self) -> None:
|
|
140
|
+
"""Closes the HTTP session."""
|
|
141
|
+
if self._session is not None and not self._session.closed:
|
|
142
|
+
await self._session.close()
|
|
143
|
+
self._session = None
|
|
144
|
+
|
|
145
|
+
async def post_json(self, endpoint: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
146
|
+
"""
|
|
147
|
+
POSTs JSON and returns the decoded body.
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
aiohttp.ClientError / asyncio.TimeoutError: the request did not get through.
|
|
151
|
+
FlashForgeResponseError: the printer answered with a non-200 status or a body
|
|
152
|
+
that is not a JSON object.
|
|
153
|
+
"""
|
|
154
|
+
session = await self.session()
|
|
155
|
+
async with session.post(
|
|
156
|
+
self.url(endpoint), json=body, headers={"Content-Type": "application/json"}
|
|
157
|
+
) as response:
|
|
158
|
+
if response.status != 200:
|
|
159
|
+
raise FlashForgeResponseError(f"HTTP status {response.status}", endpoint=endpoint)
|
|
160
|
+
data = await json_from_response(response)
|
|
161
|
+
if not isinstance(data, dict):
|
|
162
|
+
raise FlashForgeResponseError(
|
|
163
|
+
f"Expected a JSON object, got {type(data).__name__}", endpoint=endpoint
|
|
164
|
+
)
|
|
165
|
+
return data
|
|
166
|
+
|
|
167
|
+
async def run_exclusive(self, endpoint: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
168
|
+
"""POSTs a command on the FIFO command lock."""
|
|
169
|
+
self._queued += 1
|
|
170
|
+
try:
|
|
171
|
+
async with self._command_lock:
|
|
172
|
+
return await self.post_json(endpoint, body)
|
|
173
|
+
finally:
|
|
174
|
+
self._queued -= 1
|
|
175
|
+
|
|
176
|
+
# ---- Commands ------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
async def send_control_command(self, cmd: str, args: dict[str, Any]) -> bool:
|
|
179
|
+
"""
|
|
180
|
+
Sends a ``/control`` command on the command lock.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
True when the printer acknowledges with a success code. False on a rejection
|
|
184
|
+
or a network error.
|
|
185
|
+
"""
|
|
186
|
+
# Log the command, never the body: it carries the serial number and check code.
|
|
187
|
+
logger.debug("Sending control command %s with args %s", cmd, args)
|
|
188
|
+
try:
|
|
189
|
+
data = await self.run_exclusive(
|
|
190
|
+
Endpoints.CONTROL, {**self.credentials(), "payload": {"cmd": cmd, "args": args}}
|
|
191
|
+
)
|
|
192
|
+
except Exception as error:
|
|
193
|
+
logger.warning("Control command %s failed: %s", cmd, error)
|
|
194
|
+
return False
|
|
195
|
+
logger.debug("Control command %s reply: %s", cmd, data)
|
|
196
|
+
return NetworkUtils.is_ok(data)
|
|
197
|
+
|
|
198
|
+
async def send_print_command(self, body: dict[str, Any]) -> bool:
|
|
199
|
+
"""
|
|
200
|
+
Sends ``POST /printGcode`` on the command lock.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
True when the printer accepts the print.
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
The network error, so a caller can tell "rejected" from "not sent".
|
|
207
|
+
"""
|
|
208
|
+
data = await self.run_exclusive(Endpoints.GCODE_PRINT, {**self.credentials(), **body})
|
|
209
|
+
return NetworkUtils.is_ok(data)
|
|
210
|
+
|
|
211
|
+
# ---- Reads ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
async def fetch_detail_raw(self) -> dict[str, Any] | None:
|
|
214
|
+
"""
|
|
215
|
+
``/detail`` as the plain decoded JSON, with no model validation. Lets a caller read
|
|
216
|
+
identity fields (``pid``) without validating the other ~50 fields (ff-5mp-hass#18).
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
The decoded body, or None when the printer could not be reached.
|
|
220
|
+
|
|
221
|
+
Raises:
|
|
222
|
+
FlashForgeResponseError: the printer answered with a body that is not JSON.
|
|
223
|
+
"""
|
|
224
|
+
try:
|
|
225
|
+
return await self.post_json(Endpoints.DETAIL, self.credentials())
|
|
226
|
+
except FlashForgeResponseError as error:
|
|
227
|
+
if "HTTP status" in error.message:
|
|
228
|
+
logger.warning("Non-200 status from /detail: %s", error.message)
|
|
229
|
+
return None
|
|
230
|
+
raise
|
|
231
|
+
except Exception as error:
|
|
232
|
+
logger.warning("Could not reach the printer's /detail endpoint: %s", error)
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
async def fetch_detail(self) -> DetailResult:
|
|
236
|
+
"""
|
|
237
|
+
Fetches and validates ``/detail``. A failure is described in plain language.
|
|
238
|
+
|
|
239
|
+
Raises:
|
|
240
|
+
FlashForgeResponseError: the printer answered, but the body did not validate.
|
|
241
|
+
This is distinct from ``error`` (no answer, or a refusal): only this one is a
|
|
242
|
+
bug report.
|
|
243
|
+
"""
|
|
244
|
+
data = await self.fetch_detail_raw()
|
|
245
|
+
if data is None:
|
|
246
|
+
return DetailResult(
|
|
247
|
+
None,
|
|
248
|
+
f"No response from the printer HTTP API at {self.url(Endpoints.DETAIL)}. "
|
|
249
|
+
"Make sure the printer is on and in LAN-only mode: some firmware (for example "
|
|
250
|
+
"the AD5X) does not start the HTTP API in cloud mode.",
|
|
251
|
+
reachable=False,
|
|
252
|
+
)
|
|
253
|
+
code = data.get("code")
|
|
254
|
+
if isinstance(code, int) and not NetworkUtils.is_ok(data):
|
|
255
|
+
message = str(data.get("message", ""))
|
|
256
|
+
logger.warning("The printer refused /detail (code %s, message %r).", code, message)
|
|
257
|
+
return DetailResult(None, describe_detail_rejection(code, message), code)
|
|
258
|
+
try:
|
|
259
|
+
response = DetailResponse(**data)
|
|
260
|
+
except Exception as error:
|
|
261
|
+
logger.warning(
|
|
262
|
+
"The printer answered /detail with a payload that failed validation. This is "
|
|
263
|
+
"NOT a connectivity problem - please report it with the debug dump. %s",
|
|
264
|
+
error,
|
|
265
|
+
)
|
|
266
|
+
logger.debug("Payload that failed validation: %s", redact_model(data))
|
|
267
|
+
raise FlashForgeResponseError(
|
|
268
|
+
"The printer's /detail response could not be validated",
|
|
269
|
+
endpoint=Endpoints.DETAIL,
|
|
270
|
+
cause=error,
|
|
271
|
+
) from error
|
|
272
|
+
return DetailResult(response, None)
|
|
273
|
+
|
|
274
|
+
async def fetch_product(self) -> ProductResponse | None:
|
|
275
|
+
"""Fetches ``/product`` on the command lock. None on any failure (logged)."""
|
|
276
|
+
try:
|
|
277
|
+
data = await self.run_exclusive(Endpoints.PRODUCT, self.credentials())
|
|
278
|
+
if not NetworkUtils.is_ok(data):
|
|
279
|
+
return None
|
|
280
|
+
return ProductResponse(**data)
|
|
281
|
+
except ValidationError as error:
|
|
282
|
+
# Distinct from a rejected check code: the printer answered with code 0 but we
|
|
283
|
+
# could not parse it (usually a new firmware field).
|
|
284
|
+
logger.warning(
|
|
285
|
+
"Could not parse the /product response; reporting the printer as "
|
|
286
|
+
"unavailable rather than the credentials as rejected. %s",
|
|
287
|
+
error,
|
|
288
|
+
)
|
|
289
|
+
return None
|
|
290
|
+
except Exception as error:
|
|
291
|
+
logger.warning("/product failed: %s", error)
|
|
292
|
+
return None
|
|
293
|
+
|
|
294
|
+
async def fetch_recent_files(self) -> list[FFGcodeFileEntry]:
|
|
295
|
+
"""
|
|
296
|
+
``/gcodeList``. Returns ``gcodeListDetail`` when the printer sends it (AD5X only),
|
|
297
|
+
otherwise the plain names as entries. Empty list on failure.
|
|
298
|
+
"""
|
|
299
|
+
try:
|
|
300
|
+
data = await self.post_json(Endpoints.GCODE_LIST, self.credentials())
|
|
301
|
+
if not NetworkUtils.is_ok(data):
|
|
302
|
+
return []
|
|
303
|
+
result = GCodeListResponse(**data)
|
|
304
|
+
except Exception as error:
|
|
305
|
+
logger.warning("/gcodeList failed: %s", error)
|
|
306
|
+
return []
|
|
307
|
+
if result.gcode_list_detail:
|
|
308
|
+
return list(result.gcode_list_detail)
|
|
309
|
+
entries: list[FFGcodeFileEntry] = []
|
|
310
|
+
for item in result.gcode_list or []:
|
|
311
|
+
if isinstance(item, str):
|
|
312
|
+
entries.append(FFGcodeFileEntry(gcodeFileName=item, printingTime=0))
|
|
313
|
+
else:
|
|
314
|
+
entries.append(item)
|
|
315
|
+
return entries
|
|
316
|
+
|
|
317
|
+
async def fetch_thumbnail(self, file_name: str) -> bytes | None:
|
|
318
|
+
"""A file thumbnail (PNG bytes), or None when there is none or on failure."""
|
|
319
|
+
import base64
|
|
320
|
+
|
|
321
|
+
try:
|
|
322
|
+
data = await self.post_json(
|
|
323
|
+
Endpoints.GCODE_THUMB, {**self.credentials(), "fileName": file_name}
|
|
324
|
+
)
|
|
325
|
+
except Exception as error:
|
|
326
|
+
logger.warning("/gcodeThumb failed: %s", error)
|
|
327
|
+
return None
|
|
328
|
+
image = data.get("imageData")
|
|
329
|
+
if not NetworkUtils.is_ok(data) or not isinstance(image, str) or not image:
|
|
330
|
+
return None
|
|
331
|
+
try:
|
|
332
|
+
return base64.b64decode(image)
|
|
333
|
+
except Exception:
|
|
334
|
+
return None
|
|
335
|
+
|
|
336
|
+
# ---- Upload --------------------------------------------------------------------------
|
|
337
|
+
|
|
338
|
+
async def upload(self, file_path: str, headers: dict[str, str]) -> bool:
|
|
339
|
+
"""
|
|
340
|
+
Uploads a file with ``POST /uploadGcode``. The backend gives the model-specific
|
|
341
|
+
headers. The upload stays off the command lock, and the file is opened off the event
|
|
342
|
+
loop.
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
True when the printer accepts the file. False when the file is missing or the
|
|
346
|
+
printer rejects it.
|
|
347
|
+
"""
|
|
348
|
+
file_size = await _local_file_size(file_path)
|
|
349
|
+
if file_size is None:
|
|
350
|
+
logger.warning("upload: file not found at %s", file_path)
|
|
351
|
+
return False
|
|
352
|
+
request_headers = {
|
|
353
|
+
**self.credentials(),
|
|
354
|
+
"fileSize": str(file_size),
|
|
355
|
+
**headers,
|
|
356
|
+
"Expect": "100-continue",
|
|
357
|
+
}
|
|
358
|
+
logger.debug("Upload request headers: %s", redact_mapping(request_headers))
|
|
359
|
+
try:
|
|
360
|
+
async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
|
|
361
|
+
with await asyncio.to_thread(open, file_path, "rb") as handle:
|
|
362
|
+
form = aiohttp.FormData()
|
|
363
|
+
form.add_field(
|
|
364
|
+
"gcodeFile",
|
|
365
|
+
handle,
|
|
366
|
+
filename=Path(file_path).name,
|
|
367
|
+
content_type="application/octet-stream",
|
|
368
|
+
)
|
|
369
|
+
async with session.post(
|
|
370
|
+
self.url(Endpoints.UPLOAD_FILE), data=form, headers=request_headers
|
|
371
|
+
) as response:
|
|
372
|
+
if response.status != 200:
|
|
373
|
+
logger.warning("Upload failed: HTTP status %s", response.status)
|
|
374
|
+
return False
|
|
375
|
+
result = await json_from_response(response)
|
|
376
|
+
except Exception as error:
|
|
377
|
+
logger.warning("Upload failed: %s", error)
|
|
378
|
+
return False
|
|
379
|
+
if not NetworkUtils.is_ok(result):
|
|
380
|
+
logger.warning(
|
|
381
|
+
"Upload rejected: code=%s, message=%s", result.get("code"), result.get("message")
|
|
382
|
+
)
|
|
383
|
+
return False
|
|
384
|
+
return True
|
|
385
|
+
|
|
386
|
+
# ---- Camera --------------------------------------------------------------------------
|
|
387
|
+
|
|
388
|
+
async def detect_camera_stream(self, timeout_ms: int = 3000) -> str:
|
|
389
|
+
"""
|
|
390
|
+
Probes the built-in camera stream (port 8080). Falls back to a short GET when the
|
|
391
|
+
MJPEG server rejects HEAD.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
The stream URL, or an empty string when no stream answers.
|
|
395
|
+
"""
|
|
396
|
+
probe_url = f"http://{self.ip_address}:{CAMERA_STREAM_PORT}/?action=stream"
|
|
397
|
+
timeout = aiohttp.ClientTimeout(total=timeout_ms / 1000)
|
|
398
|
+
for method in ("head", "get"):
|
|
399
|
+
if await self._probe_camera(method, probe_url, timeout):
|
|
400
|
+
return probe_url
|
|
401
|
+
return ""
|
|
402
|
+
|
|
403
|
+
async def _probe_camera(
|
|
404
|
+
self, method: str, probe_url: str, timeout: aiohttp.ClientTimeout
|
|
405
|
+
) -> bool:
|
|
406
|
+
try:
|
|
407
|
+
session = await self.session()
|
|
408
|
+
request = session.head if method == "head" else session.get
|
|
409
|
+
async with request(probe_url, timeout=timeout) as response:
|
|
410
|
+
return self.is_valid_camera_response(
|
|
411
|
+
response.status, response.headers.get("Content-Type", "")
|
|
412
|
+
)
|
|
413
|
+
except Exception:
|
|
414
|
+
return False
|
|
415
|
+
|
|
416
|
+
@staticmethod
|
|
417
|
+
def is_valid_camera_response(status: int, content_type: str | None) -> bool:
|
|
418
|
+
"""True for HTTP 200 with an empty, multipart or MJPEG content type."""
|
|
419
|
+
if status != 200:
|
|
420
|
+
return False
|
|
421
|
+
normalized = (content_type or "").lower()
|
|
422
|
+
return normalized == "" or "multipart" in normalized or "video/x-mjpeg" in normalized
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
__all__ = [
|
|
426
|
+
"DetailResult",
|
|
427
|
+
"GenericResponse",
|
|
428
|
+
"HttpCore",
|
|
429
|
+
"UPLOAD_TIMEOUT",
|
|
430
|
+
"describe_detail_rejection",
|
|
431
|
+
]
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared behavior of every modern printer that has the HTTP API (port 8898).
|
|
3
|
+
|
|
4
|
+
The dual-API family (5M, 5M Pro, AD5X) and the HTTP-only family (Creator 5 series) both
|
|
5
|
+
extend this class. Neither extends the other.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
|
|
15
|
+
from ..api.constants.commands import Commands
|
|
16
|
+
from ..capabilities import snap_to_model_palette
|
|
17
|
+
from ..capabilities.models import PrinterModelId
|
|
18
|
+
from ..capabilities.printer_capabilities import (
|
|
19
|
+
PrinterCapabilities,
|
|
20
|
+
PrinterReport,
|
|
21
|
+
resolve_capabilities,
|
|
22
|
+
)
|
|
23
|
+
from ..exceptions import FlashForgeResponseError, InvalidParameterError
|
|
24
|
+
from ..models.machine_info import FFGcodeFileEntry, FFMachineInfo
|
|
25
|
+
from ..models.machine_info_parser import MachineInfoParser
|
|
26
|
+
from ..models.responses import Product
|
|
27
|
+
from ..status.printer_snapshot import PrinterSnapshot, snapshot_from_machine_info
|
|
28
|
+
from .http_core import HttpCore
|
|
29
|
+
from .printer_backend import PrinterBackend, PrinterIdentity
|
|
30
|
+
from .types import MaterialMapping, PrintOverrides
|
|
31
|
+
|
|
32
|
+
#: The "no change" value for ``printerCtl_cmd``. Each printer applies a field only when the
|
|
33
|
+
#: value is inside its accepted range, and -200 is outside every range on every model. The
|
|
34
|
+
#: Creator 5 changes -100 to 0, so -100 is not a safe "no change" value.
|
|
35
|
+
PRINTER_CTL_NO_CHANGE = -200
|
|
36
|
+
|
|
37
|
+
_HEX = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate_material_mappings(mappings: Sequence[MaterialMapping]) -> None:
|
|
41
|
+
"""
|
|
42
|
+
Validates mappings: at most 4, toolId 0-3 and each toolId once, slotId 1-4 (native), a
|
|
43
|
+
material name and "#RRGGBB" colors. Several tools can use the same slot (the printers
|
|
44
|
+
accept it); a repeated toolId is refused because the printers silently keep one entry. Raises :class:`InvalidParameterError` on the first problem. The
|
|
45
|
+
pydantic model checks most of this on construction; this also catches
|
|
46
|
+
``model_construct`` input and the count limit.
|
|
47
|
+
"""
|
|
48
|
+
if len(mappings) > 4:
|
|
49
|
+
raise InvalidParameterError("At most 4 material mappings are allowed.")
|
|
50
|
+
seen_tools: set[int] = set()
|
|
51
|
+
for i, m in enumerate(mappings):
|
|
52
|
+
if not isinstance(m.tool_id, int) or not 0 <= m.tool_id <= 3:
|
|
53
|
+
raise InvalidParameterError(f"Mapping {i}: tool_id must be 0-3, got {m.tool_id}.")
|
|
54
|
+
if m.tool_id in seen_tools:
|
|
55
|
+
raise InvalidParameterError(
|
|
56
|
+
f"Mapping {i}: tool_id {m.tool_id} is mapped more than once."
|
|
57
|
+
)
|
|
58
|
+
seen_tools.add(m.tool_id)
|
|
59
|
+
if not isinstance(m.slot_id, int) or not 1 <= m.slot_id <= 4:
|
|
60
|
+
raise InvalidParameterError(f"Mapping {i}: slot_id must be 1-4, got {m.slot_id}.")
|
|
61
|
+
if not m.material_name or not m.material_name.strip():
|
|
62
|
+
raise InvalidParameterError(f"Mapping {i}: material_name must not be empty.")
|
|
63
|
+
if not _HEX.match(m.tool_material_color):
|
|
64
|
+
raise InvalidParameterError(
|
|
65
|
+
f"Mapping {i}: tool_material_color must be #RRGGBB, got {m.tool_material_color}."
|
|
66
|
+
)
|
|
67
|
+
if not _HEX.match(m.slot_material_color):
|
|
68
|
+
raise InvalidParameterError(
|
|
69
|
+
f"Mapping {i}: slot_material_color must be #RRGGBB, got {m.slot_material_color}."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def encode_material_mappings(mappings: Sequence[MaterialMapping]) -> str:
|
|
74
|
+
"""Encodes mappings for the base64 ``materialMappings`` upload header."""
|
|
75
|
+
raw = json.dumps([m.to_wire() for m in mappings], separators=(",", ":"))
|
|
76
|
+
return base64.b64encode(raw.encode("utf-8")).decode("ascii")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class HttpPrinterBackend(PrinterBackend):
|
|
80
|
+
"""Base class of the modern (HTTP API) printers."""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
model: PrinterModelId,
|
|
85
|
+
http: HttpCore,
|
|
86
|
+
info: FFMachineInfo,
|
|
87
|
+
) -> None:
|
|
88
|
+
self.http = http
|
|
89
|
+
#: Raw ``/product`` control states from the last connect.
|
|
90
|
+
self.product: Product | None = None
|
|
91
|
+
#: Built-in camera stream URL. Empty when none is known.
|
|
92
|
+
self.camera_stream_url = info.camera_stream_url
|
|
93
|
+
self._last_info = info
|
|
94
|
+
super().__init__(
|
|
95
|
+
model,
|
|
96
|
+
self._capabilities_for(model, info, None),
|
|
97
|
+
PrinterIdentity(
|
|
98
|
+
ip_address=http.ip_address,
|
|
99
|
+
serial_number=http.serial_number,
|
|
100
|
+
name=info.name,
|
|
101
|
+
firmware_version=info.firmware_version,
|
|
102
|
+
mac_address=info.mac_address,
|
|
103
|
+
),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def _capabilities_for(
|
|
107
|
+
self, model: PrinterModelId, info: FFMachineInfo, product: Product | None
|
|
108
|
+
) -> PrinterCapabilities:
|
|
109
|
+
return resolve_capabilities(
|
|
110
|
+
model,
|
|
111
|
+
PrinterReport(camera_available=info.has_camera),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
async def initialize(self) -> bool:
|
|
115
|
+
"""
|
|
116
|
+
Finishes the connection after ``/detail`` was verified: reads ``/product`` and
|
|
117
|
+
resolves the capabilities. The factory calls this once. The dual-API family extends
|
|
118
|
+
it to open the TCP channel.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
False when ``/product`` fails.
|
|
122
|
+
"""
|
|
123
|
+
product = await self.http.fetch_product()
|
|
124
|
+
if product is None:
|
|
125
|
+
return False
|
|
126
|
+
self.product = product.product
|
|
127
|
+
self.capabilities = self._capabilities_for(self.model, self._last_info, self.product)
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
async def dispose(self) -> None:
|
|
131
|
+
self.camera_stream_url = ""
|
|
132
|
+
await self.http.close()
|
|
133
|
+
|
|
134
|
+
# ---- Status --------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
async def get_machine_info(self) -> FFMachineInfo:
|
|
137
|
+
"""
|
|
138
|
+
The parsed ``/detail``.
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
FlashForgeResponseError: no answer, a refusal, or a payload that did not parse.
|
|
142
|
+
"""
|
|
143
|
+
result = await self.http.fetch_detail()
|
|
144
|
+
if result.response is None:
|
|
145
|
+
raise FlashForgeResponseError(
|
|
146
|
+
result.error or "No /detail response.", endpoint="/detail"
|
|
147
|
+
)
|
|
148
|
+
info = MachineInfoParser.from_detail(result.response.detail)
|
|
149
|
+
if info is None:
|
|
150
|
+
raise FlashForgeResponseError(
|
|
151
|
+
"The /detail payload was read but could not be converted into machine info",
|
|
152
|
+
endpoint="/detail",
|
|
153
|
+
)
|
|
154
|
+
self._last_info = info
|
|
155
|
+
if info.camera_stream_url:
|
|
156
|
+
self.camera_stream_url = info.camera_stream_url
|
|
157
|
+
return info
|
|
158
|
+
|
|
159
|
+
async def get_status(self) -> PrinterSnapshot:
|
|
160
|
+
return snapshot_from_machine_info(await self.get_machine_info(), self.capabilities)
|
|
161
|
+
|
|
162
|
+
# ---- Jobs ----------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
async def _send_job_control(self, action: str) -> bool:
|
|
165
|
+
return await self.http.send_control_command(
|
|
166
|
+
Commands.JOB_CONTROL_CMD, {"jobID": "", "action": action}
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
async def pause_job(self) -> bool:
|
|
170
|
+
return await self._send_job_control("pause")
|
|
171
|
+
|
|
172
|
+
async def resume_job(self) -> bool:
|
|
173
|
+
return await self._send_job_control("continue")
|
|
174
|
+
|
|
175
|
+
async def cancel_job(self) -> bool:
|
|
176
|
+
return await self._send_job_control("cancel")
|
|
177
|
+
|
|
178
|
+
async def clear_platform(self) -> bool:
|
|
179
|
+
return await self.http.send_control_command(
|
|
180
|
+
Commands.STATE_CONTROL_CMD, {"action": "setClearPlatform"}
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
async def get_recent_files(self) -> list[FFGcodeFileEntry]:
|
|
184
|
+
return await self.http.fetch_recent_files()
|
|
185
|
+
|
|
186
|
+
async def get_thumbnail(self, file_name: str) -> bytes | None:
|
|
187
|
+
return await self.http.fetch_thumbnail(file_name)
|
|
188
|
+
|
|
189
|
+
# ---- Light and camera ----------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
async def set_led(self, on: bool) -> bool:
|
|
192
|
+
"""The light over ``lightControl_cmd`` (every modern model, also a user-fitted light)."""
|
|
193
|
+
if self.capabilities.led.transport != "http":
|
|
194
|
+
self._unsupported("set_led", self.capabilities.led.reason)
|
|
195
|
+
return await self.http.send_control_command(
|
|
196
|
+
Commands.LIGHT_CONTROL_CMD, {"status": "open" if on else "close"}
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
async def detect_camera_stream(self, timeout_ms: int = 3000) -> str:
|
|
200
|
+
url = await self.http.detect_camera_stream(timeout_ms)
|
|
201
|
+
if url:
|
|
202
|
+
self.camera_stream_url = url
|
|
203
|
+
return url
|
|
204
|
+
|
|
205
|
+
# ---- Active print --------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
def _supports_left_cooling_fan(self) -> bool:
|
|
208
|
+
return False
|
|
209
|
+
|
|
210
|
+
async def set_print_overrides(self, overrides: PrintOverrides) -> bool:
|
|
211
|
+
"""
|
|
212
|
+
Sends ``printerCtl_cmd``. Only the fields the caller sets change; the others are sent
|
|
213
|
+
as :data:`PRINTER_CTL_NO_CHANGE`. The printer always replies success, so an
|
|
214
|
+
out-of-range value is not reported.
|
|
215
|
+
|
|
216
|
+
Raises:
|
|
217
|
+
RuntimeError: no print is active.
|
|
218
|
+
"""
|
|
219
|
+
if overrides.left_cooling_fan_speed is not None and not self._supports_left_cooling_fan():
|
|
220
|
+
self._unsupported("set_print_overrides", "Only the AD5X has a left cooling fan.")
|
|
221
|
+
info = await self.get_machine_info()
|
|
222
|
+
if info.status != "printing":
|
|
223
|
+
raise RuntimeError("printerCtl_cmd needs an active print.")
|
|
224
|
+
|
|
225
|
+
def keep(value: float | None) -> float:
|
|
226
|
+
return PRINTER_CTL_NO_CHANGE if value is None else value
|
|
227
|
+
|
|
228
|
+
payload: dict[str, float] = {
|
|
229
|
+
"zAxisCompensation": keep(overrides.z_offset),
|
|
230
|
+
"speed": keep(overrides.print_speed),
|
|
231
|
+
"chamberFan": keep(overrides.chamber_fan_speed),
|
|
232
|
+
"coolingFan": keep(overrides.cooling_fan_speed),
|
|
233
|
+
}
|
|
234
|
+
if overrides.left_cooling_fan_speed is not None:
|
|
235
|
+
payload["coolingLeftFan"] = overrides.left_cooling_fan_speed
|
|
236
|
+
return await self.http.send_control_command(Commands.PRINTER_CONTROL_CMD, payload)
|
|
237
|
+
|
|
238
|
+
# ---- Material station helpers --------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
async def _send_slot_config(self, slot_id: int, material_name: str, hex_color: str) -> bool:
|
|
241
|
+
"""
|
|
242
|
+
Sends ``msConfig_cmd``. The color snaps to this model's 24-color firmware palette:
|
|
243
|
+
the printer draws the slot icon only on an exact, case-sensitive "#RRGGBB" match.
|
|
244
|
+
"""
|
|
245
|
+
slots = self.capabilities.material_station.slot_count
|
|
246
|
+
if not isinstance(slot_id, int) or not 1 <= slot_id <= slots:
|
|
247
|
+
raise InvalidParameterError(f"slot_id must be 1-{slots}, got {slot_id}.")
|
|
248
|
+
snapped = snap_to_model_palette(self.model, hex_color)
|
|
249
|
+
if snapped is None:
|
|
250
|
+
self._unsupported("configure_slot", self.capabilities.material_station.reason)
|
|
251
|
+
return await self.http.send_control_command(
|
|
252
|
+
Commands.MATERIAL_STATION_CONFIG_CMD,
|
|
253
|
+
{"slot": slot_id, "mt": material_name, "rgb": snapped.hex},
|
|
254
|
+
)
|