flashforge-python-api 1.4.0__py3-none-any.whl → 1.6.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 CHANGED
@@ -127,8 +127,21 @@ from .tcp import (
127
127
  FlashForgeTcpClient as TcpClient,
128
128
  )
129
129
 
130
+ # Sliced 3MF parsing (tools and materials before upload)
131
+ from .threemf import (
132
+ PrinterFamily,
133
+ ThreeMFError,
134
+ ThreeMFFilament,
135
+ ThreeMFFile,
136
+ ThreeMFFormatError,
137
+ ThreeMFMultiplePlatesError,
138
+ ThreeMFNotSlicedError,
139
+ ThreeMFWarning,
140
+ parse_3mf,
141
+ )
142
+
130
143
  FiveMClient = FlashForgeClient
131
- __version__ = "1.4.0"
144
+ __version__ = "1.6.0"
132
145
  __author__ = "FlashForge Python API Contributors"
133
146
  __email__ = "notghosttypes@gmail.com"
134
147
  __description__ = "Python library for controlling FlashForge 3D printers"
@@ -164,6 +177,16 @@ __all__ = [
164
177
  "AD5XUploadParams",
165
178
  "GCodeListResponse",
166
179
  "ThumbnailResponse",
180
+ # Sliced 3MF parsing
181
+ "parse_3mf",
182
+ "PrinterFamily",
183
+ "ThreeMFError",
184
+ "ThreeMFFilament",
185
+ "ThreeMFFile",
186
+ "ThreeMFFormatError",
187
+ "ThreeMFMultiplePlatesError",
188
+ "ThreeMFNotSlicedError",
189
+ "ThreeMFWarning",
167
190
  # Control classes for advanced usage
168
191
  "Control",
169
192
  "JobControl",
@@ -11,5 +11,5 @@ class Commands:
11
11
  TEMP_CONTROL_CMD = "temperatureCtl_cmd"
12
12
  # AD5X + Creator 5 material-station slot metadata (name + color). Filament
13
13
  # load/unload (`ms_cmd`) stays AD5X-only — the Creator 5 firmware has no
14
- # `ms_cmd` (confirmed via Ghidra RE).
14
+ # `ms_cmd` (verified in the firmware).
15
15
  MATERIAL_STATION_CONFIG_CMD = "msConfig_cmd"
@@ -237,8 +237,8 @@ class Control:
237
237
  This information is shown on the printer UI and used for print validation; it
238
238
  does not move any filament. Available on the AD5X and the Creator 5 / Creator 5 Pro.
239
239
 
240
- The ``msConfig_cmd`` handler is firmware-confirmed present on the Creator 5
241
- (Ghidra RE of ``firmwareExe`` 1.9.2). The Creator 5 has no removable IFS; it
240
+ The ``msConfig_cmd`` handler is confirmed present on the Creator 5
241
+ (verified in firmware 1.9.2). The Creator 5 has no removable IFS; it
242
242
  surfaces its 4 tool heads as the 4 "slots", so this sets per-tool material
243
243
  metadata. Both models share the same ``OrcaServer`` command path and wire
244
244
  format. Note that **filament load/unload (``slotAction`` / ``ms_cmd``)
@@ -303,24 +303,21 @@ class Control:
303
303
  logger.debug("Sending control command %s with args %s", command, args)
304
304
 
305
305
  try:
306
- await self.client.is_http_client_busy()
307
-
308
306
  session = await self.client.get_http_session()
309
- async with session.post(
310
- self.client.get_endpoint(Endpoints.CONTROL),
311
- json=payload,
312
- headers={"Content-Type": "application/json"},
313
- ) as response:
314
- data = await json_from_response(response)
315
- logger.debug("Control command %s reply: %s", command, data)
307
+ async with self.client.command_lock:
308
+ async with session.post(
309
+ self.client.get_endpoint(Endpoints.CONTROL),
310
+ json=payload,
311
+ headers={"Content-Type": "application/json"},
312
+ ) as response:
313
+ data = await json_from_response(response)
314
+ logger.debug("Control command %s reply: %s", command, data)
316
315
 
317
- return NetworkUtils.is_ok(data)
316
+ return NetworkUtils.is_ok(data)
318
317
 
319
318
  except Exception as e:
320
319
  logger.warning("Error in send_control_command (%s): %s", command, e)
321
320
  return False
322
- finally:
323
- self.client.release_http_client()
324
321
 
325
322
  async def send_job_control_cmd(self, command: str) -> bool:
326
323
  """
@@ -4,8 +4,8 @@ palette and perceptual nearest-color snapping.
4
4
 
5
5
  The Creator 5 ``msConfig_cmd`` only renders a color icon when the ``rgb`` field is
6
6
  an EXACT, case-sensitive, byte-for-byte match against one of the firmware's 24
7
- built-in palette strings (compared via ``std::operator==`` in ``firmwareExe``
8
- 1.9.2). A non-match leaves the slot's color index at 0 (White). These values
7
+ built-in palette strings (verified in firmware 1.9.2). A non-match leaves the
8
+ slot's color index at 0 (White). These values
9
9
  DIFFER from the AD5X palette (e.g. Blue is ``#4CAAF8`` here vs ``#45A8F9`` on the
10
10
  AD5X), so callers must snap against THIS list specifically.
11
11
 
@@ -43,7 +43,7 @@ class Creator5PaletteColor:
43
43
  """Wire value sent to the printer, always uppercase ``#RRGGBB``."""
44
44
 
45
45
 
46
- #: The firmware's 24-entry UI palette (firmwareExe 1.9.2, Ghidra-confirmed).
46
+ #: The firmware's 24-entry UI palette (verified in firmware 1.9.2).
47
47
  #: Index 0 (White) is also what the firmware falls back to on a no-match.
48
48
  CREATOR5_PALETTE: tuple[Creator5PaletteColor, ...] = (
49
49
  Creator5PaletteColor(0, "White", "#FFFFFF"),
@@ -78,10 +78,9 @@ class Files:
78
78
 
79
79
  The Creator 5 is the surprise there, and it is firmware, not a parsing gap:
80
80
  it is a newer printer than the AD5X but reports less (confirmed against a
81
- Creator 5 Pro, 2026-08-05). Do not describe this method as "AD5X and newer" -
82
- that phrasing cost a downstream integration three releases of chasing a bug
83
- that was never in the code. Callers that need per-tool data on a Creator 5
84
- must parse the 3mf themselves at upload time.
81
+ live Creator 5 Pro, 2026-08-05). Do not describe this method as "AD5X and
82
+ newer" - only the AD5X answers with `gcodeListDetail`. Callers that need
83
+ per-tool data on a Creator 5 must parse the 3mf themselves at upload time.
85
84
 
86
85
  Returns:
87
86
  A list of FFGcodeFileEntry objects. Returns an empty list if the request fails or an error occurs.
@@ -404,7 +404,7 @@ class Info:
404
404
  if machine_info is None:
405
405
  # We validated the payload but could not build our own model from
406
406
  # it - that is a bug on our side, not an unreachable printer, and
407
- # reporting it as the latter is what issue #18 was about.
407
+ # reporting it as the latter is what ff-5mp-hass#18 was about.
408
408
  raise FlashForgeResponseError(
409
409
  "The /detail payload was read but could not be converted into machine info",
410
410
  endpoint=Endpoints.DETAIL,
@@ -462,7 +462,7 @@ class Info:
462
462
  This exists so callers can inspect identity fields - above all `pid` -
463
463
  without first having to successfully validate the ~50 unrelated fields
464
464
  in the payload. A supported printer must never be rejected because of a
465
- field that has nothing to do with whether it is supported (issue #18).
465
+ field that has nothing to do with whether it is supported (ff-5mp-hass#18).
466
466
 
467
467
  Returns:
468
468
  The decoded response body, or None if the printer could not be
@@ -2,6 +2,7 @@
2
2
  FlashForge Python API - Job Control Module
3
3
  """
4
4
 
5
+ import asyncio
5
6
  import base64
6
7
  import json
7
8
  import logging
@@ -29,6 +30,26 @@ if TYPE_CHECKING:
29
30
 
30
31
  logger = logging.getLogger(__name__)
31
32
 
33
+ # Uploads can be hundreds of megabytes over printer Wi-Fi, so the aiohttp default
34
+ # (a 5-minute cap on the whole request) is too short. There is no total cap; the
35
+ # connect and response-read limits still catch a printer that stops answering.
36
+ UPLOAD_TIMEOUT = aiohttp.ClientTimeout(total=None, sock_connect=30, sock_read=300)
37
+
38
+
39
+ async def _local_file_size(file_path: str) -> int | None:
40
+ """
41
+ Return the size of a local file, or None if it is not a regular file.
42
+
43
+ Runs in a worker thread: blocking file I/O on the event loop stalls every
44
+ other task, and Home Assistant reports it as an error.
45
+ """
46
+
47
+ def _size() -> int | None:
48
+ path = Path(file_path)
49
+ return path.stat().st_size if path.is_file() else None
50
+
51
+ return await asyncio.to_thread(_size)
52
+
32
53
 
33
54
  class JobControl:
34
55
  """
@@ -137,14 +158,12 @@ class JobControl:
137
158
  Returns:
138
159
  True if the file upload (and optional print start) is successful, False otherwise.
139
160
  """
140
- file_path_obj = Path(file_path)
141
-
142
- if not file_path_obj.exists():
161
+ file_size = await _local_file_size(file_path)
162
+ if file_size is None:
143
163
  logger.warning("upload_file: file not found at %s", file_path)
144
164
  return False
145
165
 
146
- file_size = file_path_obj.stat().st_size
147
- file_name = file_path_obj.name
166
+ file_name = Path(file_path).name
148
167
 
149
168
  logger.debug(
150
169
  "Starting upload for %s (size=%s, start=%s, level=%s)",
@@ -179,8 +198,8 @@ class JobControl:
179
198
  logger.debug("Upload request headers: %s", redact_mapping(custom_headers))
180
199
 
181
200
  # Create multipart form data
182
- async with aiohttp.ClientSession() as session:
183
- with open(file_path, "rb") as f:
201
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
202
+ with await asyncio.to_thread(open, file_path, "rb") as f:
184
203
  data = aiohttp.FormData()
185
204
  data.add_field(
186
205
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -253,16 +272,17 @@ class JobControl:
253
272
 
254
273
  try:
255
274
  session = await self.client.get_http_session()
256
- async with session.post(
257
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
258
- json=payload,
259
- headers={"Content-Type": "application/json"},
260
- ) as response:
261
- if response.status != 200:
262
- return False
275
+ async with self.client.command_lock:
276
+ async with session.post(
277
+ self.client.get_endpoint(Endpoints.GCODE_PRINT),
278
+ json=payload,
279
+ headers={"Content-Type": "application/json"},
280
+ ) as response:
281
+ if response.status != 200:
282
+ return False
263
283
 
264
- result = await json_from_response(response)
265
- return NetworkUtils.is_ok(result)
284
+ result = await json_from_response(response)
285
+ return NetworkUtils.is_ok(result)
266
286
 
267
287
  except Exception as error:
268
288
  logger.warning("print_local_file error: %s", error)
@@ -289,13 +309,12 @@ class JobControl:
289
309
  return False
290
310
 
291
311
  # Validate file exists
292
- file_path_obj = Path(params.file_path)
293
- if not file_path_obj.exists():
312
+ file_size = await _local_file_size(params.file_path)
313
+ if file_size is None:
294
314
  logger.warning("upload_file_ad5x: file not found at %s", params.file_path)
295
315
  return False
296
316
 
297
- file_size = file_path_obj.stat().st_size
298
- file_name = file_path_obj.name
317
+ file_name = Path(params.file_path).name
299
318
 
300
319
  logger.debug(
301
320
  "Starting AD5X upload for %s (size=%s, start=%s, level=%s, tools=%s)",
@@ -331,8 +350,8 @@ class JobControl:
331
350
  logger.debug("AD5X upload request headers: %s", redact_mapping(custom_headers))
332
351
 
333
352
  # Create multipart form data
334
- async with aiohttp.ClientSession() as session:
335
- with open(params.file_path, "rb") as f:
353
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
354
+ with await asyncio.to_thread(open, params.file_path, "rb") as f:
336
355
  data = aiohttp.FormData()
337
356
  data.add_field(
338
357
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -422,16 +441,17 @@ class JobControl:
422
441
 
423
442
  try:
424
443
  session = await self.client.get_http_session()
425
- async with session.post(
426
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
427
- json=payload,
428
- headers={"Content-Type": "application/json"},
429
- ) as response:
430
- if response.status != 200:
431
- return False
444
+ async with self.client.command_lock:
445
+ async with session.post(
446
+ self.client.get_endpoint(Endpoints.GCODE_PRINT),
447
+ json=payload,
448
+ headers={"Content-Type": "application/json"},
449
+ ) as response:
450
+ if response.status != 200:
451
+ return False
432
452
 
433
- result = await json_from_response(response)
434
- return NetworkUtils.is_ok(result)
453
+ result = await json_from_response(response)
454
+ return NetworkUtils.is_ok(result)
435
455
 
436
456
  except Exception as error:
437
457
  logger.warning("AD5X multi-color job error: %s", error)
@@ -474,40 +494,59 @@ class JobControl:
474
494
 
475
495
  try:
476
496
  session = await self.client.get_http_session()
477
- async with session.post(
478
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
479
- json=payload,
480
- headers={"Content-Type": "application/json"},
481
- ) as response:
482
- if response.status != 200:
483
- return False
497
+ async with self.client.command_lock:
498
+ async with session.post(
499
+ self.client.get_endpoint(Endpoints.GCODE_PRINT),
500
+ json=payload,
501
+ headers={"Content-Type": "application/json"},
502
+ ) as response:
503
+ if response.status != 200:
504
+ return False
484
505
 
485
- result = await json_from_response(response)
486
- return NetworkUtils.is_ok(result)
506
+ result = await json_from_response(response)
507
+ return NetworkUtils.is_ok(result)
487
508
 
488
509
  except Exception as error:
489
510
  logger.warning("AD5X single-color job error: %s", error)
490
511
  raise error
491
512
 
492
513
  # --- Creator 5 / Creator 5 Pro ---
493
- # The Creator 5 splits the material-station workflow across two requests,
494
- # unlike the AD5X (which maps materials at upload time). On the C5:
495
- # 1. Upload the file (POST /uploadGcode). The firmware reads `useMatlStation`
496
- # and `gcodeToolCnt` here to register the file as a multi-tool job. There
497
- # is NO `firstLayerInspection` header (the field doesn't exist on the
498
- # C5), and the booleans are checked as the string "true"/"false".
499
- # 2. Start the print (POST /printGcode) with the per-tool
500
- # `materialMappings`. See start_creator5_job.
514
+ # The Creator 5 firmware applies material mappings in two places:
515
+ # - POST /printGcode reads `materialMappings` for any file already on the
516
+ # printer (see start_creator5_job). This is the recommended path: upload
517
+ # with start_print=False, then start with the mappings.
518
+ # - POST /uploadGcode also reads a base64 `materialMappings` header, the
519
+ # same format as the AD5X, and applies it when `printNow` is true.
520
+ # The firmware only logs `useMatlStation` and `gcodeToolCnt` on upload; they
521
+ # have no effect. There is NO `firstLayerInspection` header (the field doesn't
522
+ # exist on the C5), and the booleans are checked as the string "true"/"false".
523
+ #
524
+ # Mappings only take effect for a .3mf file. Without mappings, tool N prints
525
+ # from the slot with the slicer's filament number (filament 1 -> slot 1),
526
+ # whatever is loaded there. Send a mapping for every tool, including a
527
+ # single-tool print.
501
528
 
502
529
  async def upload_file_creator5(self, params: Creator5UploadParams) -> bool:
503
530
  """
504
531
  Uploads a file (.gcode or .3mf) to a Creator 5 / Creator 5 Pro via
505
532
  ``POST /uploadGcode``, with the C5-specific material-station headers.
506
533
 
507
- Unlike :meth:`upload_file_ad5x` this sends no ``firstLayerInspection``
508
- header (the C5 has no such field) and no ``materialMappings`` header (the
509
- C5 maps materials at print-start, not upload). Booleans are sent as the
510
- string "true"/"false".
534
+ Recommended flow: upload with ``start_print=False``, then call
535
+ :meth:`start_creator5_job` with a mapping for every tool. To start in one
536
+ request instead, pass ``material_mappings`` with ``start_print=True``: the
537
+ firmware reads them from a base64 ``materialMappings`` header, like the
538
+ AD5X.
539
+
540
+ ``material_mappings`` is sent only when ``start_print`` is true. The
541
+ firmware keeps upload mappings in memory until the next print ends, so
542
+ mappings on an upload that does not start would apply to a later,
543
+ unrelated print.
544
+
545
+ ``useMatlStation`` and ``gcodeToolCnt`` are sent for parity with
546
+ FlashForge's own clients; the firmware only logs them. Unlike
547
+ :meth:`upload_file_ad5x` this sends no ``firstLayerInspection`` header
548
+ (the C5 has no such field). Booleans are sent as the string
549
+ "true"/"false".
511
550
 
512
551
  Args:
513
552
  params: Creator 5 upload parameters.
@@ -515,14 +554,12 @@ class JobControl:
515
554
  Returns:
516
555
  True on success, False otherwise.
517
556
  """
518
- file_path_obj = Path(params.file_path)
519
-
520
- if not file_path_obj.exists():
557
+ file_size = await _local_file_size(params.file_path)
558
+ if file_size is None:
521
559
  logger.warning("upload_file_creator5: file not found at %s", params.file_path)
522
560
  return False
523
561
 
524
- file_size = file_path_obj.stat().st_size
525
- file_name = file_path_obj.name
562
+ file_name = Path(params.file_path).name
526
563
 
527
564
  logger.debug(
528
565
  "Starting Creator 5 upload for %s (size=%s, start=%s, level=%s, "
@@ -537,8 +574,7 @@ class JobControl:
537
574
 
538
575
  try:
539
576
  # C5 upload headers. No firstLayerInspection (absent on the C5);
540
- # booleans sent as "true"/"false" (firmware checks for "true"); no
541
- # materialMappings header (C5 maps at print-start, not upload).
577
+ # booleans sent as "true"/"false" (firmware checks for "true").
542
578
  custom_headers = {
543
579
  "serialNumber": self.client.serial_number,
544
580
  "checkCode": self.client.check_code,
@@ -552,11 +588,25 @@ class JobControl:
552
588
  "Expect": "100-continue",
553
589
  }
554
590
 
591
+ mappings = params.material_mappings or []
592
+ if mappings:
593
+ if not params.start_print:
594
+ logger.warning(
595
+ "upload_file_creator5: material_mappings ignored because start_print "
596
+ "is False; pass them to start_creator5_job instead."
597
+ )
598
+ else:
599
+ if not self._validate_creator5_material_mappings(mappings):
600
+ return False
601
+ custom_headers["materialMappings"] = self._encode_material_mappings_to_base64(
602
+ mappings
603
+ )
604
+
555
605
  logger.debug("Creator 5 upload request headers: %s", redact_mapping(custom_headers))
556
606
 
557
607
  # Create multipart form data
558
- async with aiohttp.ClientSession() as session:
559
- with open(params.file_path, "rb") as f:
608
+ async with aiohttp.ClientSession(timeout=UPLOAD_TIMEOUT) as session:
609
+ with await asyncio.to_thread(open, params.file_path, "rb") as f:
560
610
  data = aiohttp.FormData()
561
611
  data.add_field(
562
612
  "gcodeFile", f, filename=file_name, content_type="application/octet-stream"
@@ -600,13 +650,17 @@ class JobControl:
600
650
  """
601
651
  Starts a local print on a Creator 5 / Creator 5 Pro via ``POST /printGcode``.
602
652
 
603
- This is the Creator 5's print-start material-matching command (distinct
604
- from the AD5X, which maps materials at upload time). The file must already
605
- be on the printer. Provide ``material_mappings`` for a multi-tool print, or
606
- omit them for a single-tool print. Sends only the fields the Creator 5
607
- firmware reads: NO ``useMatlStation`` / ``gcodeToolCnt`` (those live on the
608
- upload) and NO ``firstLayerInspection`` (doesn't exist on the C5).
609
- ``flowCalibration`` and ``timeLapseVideo`` are always present (default False).
653
+ This is the Creator 5's print-start material-matching command. The file
654
+ must already be on the printer; it can be a file uploaded long before, not
655
+ only the last upload. Sends only the fields the Creator 5 firmware reads:
656
+ NO ``useMatlStation`` / ``gcodeToolCnt`` and NO ``firstLayerInspection``
657
+ (doesn't exist on the C5). ``flowCalibration`` and ``timeLapseVideo`` are
658
+ always present (default False).
659
+
660
+ Provide a mapping for every tool, including a single-tool print. Without
661
+ mappings the firmware prints each tool from the slot with the slicer's
662
+ filament number (filament 1 -> slot 1), whatever is loaded there.
663
+ Mappings take effect only for a .3mf file.
610
664
 
611
665
  Args:
612
666
  params: File name, leveling flag, and optional flags / material mappings.
@@ -653,16 +707,17 @@ class JobControl:
653
707
 
654
708
  try:
655
709
  session = await self.client.get_http_session()
656
- async with session.post(
657
- self.client.get_endpoint(Endpoints.GCODE_PRINT),
658
- json=payload,
659
- headers={"Content-Type": "application/json"},
660
- ) as response:
661
- if response.status != 200:
662
- return False
710
+ async with self.client.command_lock:
711
+ async with session.post(
712
+ self.client.get_endpoint(Endpoints.GCODE_PRINT),
713
+ json=payload,
714
+ headers={"Content-Type": "application/json"},
715
+ ) as response:
716
+ if response.status != 200:
717
+ return False
663
718
 
664
- result = await json_from_response(response)
665
- return NetworkUtils.is_ok(result)
719
+ result = await json_from_response(response)
720
+ return NetworkUtils.is_ok(result)
666
721
 
667
722
  except Exception as error:
668
723
  logger.warning("Creator 5 job error: %s", error)
@@ -27,12 +27,12 @@ TEMP_OFF = -100
27
27
  # Value that turns a tool/nozzle OFF inside the `nozzles` array. Unlike the scalar
28
28
  # heater fields (which accept TEMP_OFF = -100), the Creator 5 firmware's
29
29
  # per-nozzle parser only treats a literal 0 as "off" — it ignores -100 in the
30
- # `nozzles` array and the tool keeps heating. (Firmware-confirmed via tester
31
- # report; this is the v1.6.1 nozzle-off bugfix.)
30
+ # `nozzles` array and the tool keeps heating (observed on live hardware;
31
+ # this is the v1.6.1 nozzle-off bugfix).
32
32
  NOZZLE_OFF = 0
33
33
  # Number of tool/nozzle entries the Creator 5 firmware requires in the
34
34
  # `nozzles` array. The firmware ignores the array unless its length is exactly
35
- # this (confirmed via Ghidra: `size() == 4` check in the temp parser).
35
+ # this (verified in the firmware).
36
36
  NOZZLE_COUNT = 4
37
37
 
38
38
 
@@ -188,7 +188,7 @@ class TempControl:
188
188
  """
189
189
  if self.client.http_only:
190
190
  # Creator 5 tools are driven ONLY via the `nozzles` array — the
191
- # firmware's doTemperatureControl handler never reads
191
+ # firmware's temperature-control handler never reads
192
192
  # rightNozzle/leftNozzle. Target the primary tool (T0): the active
193
193
  # tool isn't reliably known over HTTP, so callers that need a
194
194
  # specific tool should use set_tool_temp(index, temp).
flashforge/client.py CHANGED
@@ -75,6 +75,15 @@ class FlashForgeClient:
75
75
  self._http_client_event = asyncio.Event()
76
76
  self._http_client_event.set() # Not busy initially
77
77
 
78
+ # FIFO mutex for command submission. asyncio.Lock hands the lock to
79
+ # waiters in the order they asked for it. So command POSTs run one at
80
+ # a time, in submission order. Scope: command POSTs only (/control,
81
+ # /product, /printGcode). File uploads (/uploadGcode) and read/poll
82
+ # POSTs (/detail, /gcodeList, /gcodeThumb) stay outside the lock. An
83
+ # upload can run for minutes; pause and stop must never queue behind
84
+ # one.
85
+ self._command_lock = asyncio.Lock()
86
+
78
87
  # TCP client setup
79
88
  tcp_options = None
80
89
  if options and options.tcp_port is not None:
@@ -202,6 +211,19 @@ class FlashForgeClient:
202
211
  self._http_session = aiohttp.ClientSession(timeout=timeout, headers={"Accept": "*/*"})
203
212
  return self._http_session
204
213
 
214
+ @property
215
+ def command_lock(self) -> asyncio.Lock:
216
+ """
217
+ The FIFO lock that serializes command-submission HTTP POSTs.
218
+
219
+ Command POSTs (/control, /product, /printGcode) hold this lock while
220
+ the request is in flight. asyncio.Lock serves waiters in arrival order,
221
+ so concurrent commands run one at a time, first come first served.
222
+ Uploads and read/poll requests never take this lock. So a long upload
223
+ cannot delay a pause or stop command.
224
+ """
225
+ return self._command_lock
226
+
205
227
  async def initialize(self) -> bool:
206
228
  """
207
229
  Initializes the FlashForgeClient and verifies the connection to the printer.
@@ -442,43 +464,42 @@ class FlashForgeClient:
442
464
  """
443
465
  Sends a product command to the printer to retrieve control states.
444
466
 
445
- This method sets the http_client_busy flag while the request is in progress.
467
+ This method holds the command lock while the request is in progress.
446
468
 
447
469
  Returns:
448
470
  True if the product command is sent successfully and valid data is received,
449
471
  False otherwise
450
472
  """
451
- self._http_client_busy = True
452
-
453
473
  payload = {"serialNumber": self.serial_number, "checkCode": self.check_code}
454
474
 
455
475
  try:
456
476
  session = await self._ensure_http_session()
457
- async with session.post(
458
- self.get_endpoint(Endpoints.PRODUCT),
459
- json=payload,
460
- headers={"Content-Type": "application/json"},
461
- ) as response:
462
- if response.status != 200:
463
- return False
464
-
465
- data = await json_from_response(response)
466
-
467
- # Validate response structure
468
- if not NetworkUtils.is_ok(data):
469
- return False
470
-
471
- # Parse product response and set control states
472
- product_response = ProductResponse(**data)
473
- if product_response and product_response.product:
474
- product = product_response.product
475
- self.product_info = product
476
- self._detected_led_control = product.lightCtrlState != 0
477
- self._detected_filtration_control = not (
478
- product.internalFanCtrlState == 0 or product.externalFanCtrlState == 0
479
- )
480
- self._apply_feature_overrides()
481
- return True
477
+ async with self._command_lock:
478
+ async with session.post(
479
+ self.get_endpoint(Endpoints.PRODUCT),
480
+ json=payload,
481
+ headers={"Content-Type": "application/json"},
482
+ ) as response:
483
+ if response.status != 200:
484
+ return False
485
+
486
+ data = await json_from_response(response)
487
+
488
+ # Validate response structure
489
+ if not NetworkUtils.is_ok(data):
490
+ return False
491
+
492
+ # Parse product response and set control states
493
+ product_response = ProductResponse(**data)
494
+ if product_response and product_response.product:
495
+ product = product_response.product
496
+ self.product_info = product
497
+ self._detected_led_control = product.lightCtrlState != 0
498
+ self._detected_filtration_control = not (
499
+ product.internalFanCtrlState == 0 or product.externalFanCtrlState == 0
500
+ )
501
+ self._apply_feature_overrides()
502
+ return True
482
503
 
483
504
  except ValidationError as error:
484
505
  # Distinct from a rejected check code, and it must not read as one:
@@ -496,8 +517,6 @@ class FlashForgeClient:
496
517
  except Exception as error:
497
518
  logger.warning("Error in send_product_command: %s", error)
498
519
  return False
499
- finally:
500
- self._http_client_busy = False
501
520
 
502
521
  return False
503
522
 
flashforge/exceptions.py CHANGED
@@ -15,7 +15,7 @@ class FlashForgeResponseError(FlashForgeError):
15
15
 
16
16
  This is deliberately distinct from a ``None`` return, which every HTTP
17
17
  control method uses for "could not reach the printer / the printer refused
18
- us". Collapsing the two is what made issue #18 take three releases to
18
+ us". Collapsing the two is what made ff-5mp-hass#18 take three releases to
19
19
  diagnose: a Creator 5 reporting ``chamberTemp: -108`` (the firmware's "no
20
20
  chamber sensor" sentinel) surfaced in Home Assistant as ``cannot_connect``,
21
21
  pointing the user at their network for a schema problem.