anycubic-cloud-api 0.4.35__tar.gz → 0.4.37__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {anycubic_cloud_api-0.4.35/src/anycubic_cloud_api.egg-info → anycubic_cloud_api-0.4.37}/PKG-INFO +1 -1
  2. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/pyproject.toml +1 -1
  3. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/__init__.py +2 -1
  4. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/api/functions.py +21 -8
  5. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/api/mqtt.py +6 -5
  6. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/consumable.py +24 -0
  7. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/orders.py +110 -0
  8. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/printer.py +104 -14
  9. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/printer_properties.py +18 -0
  10. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/project.py +10 -6
  11. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/helpers/helpers.py +28 -0
  12. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37/src/anycubic_cloud_api.egg-info}/PKG-INFO +1 -1
  13. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api.egg-info/SOURCES.txt +4 -1
  14. anycubic_cloud_api-0.4.37/tests/test_camera_kvs_0437.py +131 -0
  15. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_filament_change_0435.py +13 -5
  16. anycubic_cloud_api-0.4.37/tests/test_printer_slot_0436.py +149 -0
  17. anycubic_cloud_api-0.4.37/tests/test_slice_param_0437.py +98 -0
  18. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/COPYRIGHT +0 -0
  19. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/LICENSE +0 -0
  20. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/MANIFEST.in +0 -0
  21. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/README.md +0 -0
  22. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/setup.cfg +0 -0
  23. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/anycubic_api.py +0 -0
  24. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/api/base.py +0 -0
  25. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/api_endpoints.py +0 -0
  26. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/const.py +0 -0
  27. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/enums.py +0 -0
  28. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/error_codes.py +0 -0
  29. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/lan.py +0 -0
  30. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/mqtt.py +0 -0
  31. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/const/regions.py +0 -0
  32. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/files.py +0 -0
  33. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/gcode_file.py +0 -0
  34. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/print_response.py +0 -0
  35. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/print_speed_mode.py +0 -0
  36. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/data_models/printing_settings.py +0 -0
  37. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/exceptions/error_strings.py +0 -0
  38. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/exceptions/exceptions.py +0 -0
  39. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/lan/__init__.py +0 -0
  40. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/lan/client.py +0 -0
  41. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/lan/commands.py +0 -0
  42. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/lan/handshake.py +0 -0
  43. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/models/auth.py +0 -0
  44. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/models/cloud_upload.py +0 -0
  45. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/models/http.py +0 -0
  46. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/resources/anycubic_mqqt_tls_ca.crt +0 -0
  47. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/resources/anycubic_mqqt_tls_client.crt +0 -0
  48. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api/resources/anycubic_mqqt_tls_client.key +0 -0
  49. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api.egg-info/dependency_links.txt +0 -0
  50. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api.egg-info/requires.txt +0 -0
  51. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/src/anycubic_cloud_api.egg-info/top_level.txt +0 -0
  52. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_auth_mode_fallback.py +0 -0
  53. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_axis_position.py +0 -0
  54. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_endpoint_urls.py +0 -0
  55. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_exchange_rate_limit.py +0 -0
  56. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_lan_client.py +0 -0
  57. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_lan_commands.py +0 -0
  58. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_lan_handshake.py +0 -0
  59. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_lan_reports.py +0 -0
  60. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_null_tolerant_parsing.py +0 -0
  61. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_partial_reports.py +0 -0
  62. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_print_reports_0434.py +0 -0
  63. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_printer_error_codes.py +0 -0
  64. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_project_null_status.py +0 -0
  65. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_regions.py +0 -0
  66. {anycubic_cloud_api-0.4.35 → anycubic_cloud_api-0.4.37}/tests/test_secondary_ace.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: anycubic-cloud-api
3
- Version: 0.4.35
3
+ Version: 0.4.37
4
4
  Summary: Async client for the Anycubic Cloud API and its MQTT stream
5
5
  Author: WaresWichall, Nino Bondonno
6
6
  Maintainer: Nino Bondonno
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "anycubic-cloud-api"
7
- version = "0.4.35"
7
+ version = "0.4.37"
8
8
  description = "Async client for the Anycubic Cloud API and its MQTT stream"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -12,7 +12,7 @@ from .const.enums import (
12
12
  AnycubicPrinterMaterialType,
13
13
  AnycubicPrintStatus,
14
14
  )
15
- from .data_models.orders import AnycubicShengwangCredentials
15
+ from .data_models.orders import AnycubicKvsCredentials, AnycubicShengwangCredentials
16
16
  from .data_models.printer import AnycubicPrinter
17
17
  from .data_models.printer_properties import AnycubicAxisPosition
18
18
  from .data_models.project import AnycubicProject
@@ -63,6 +63,7 @@ __all__ = [
63
63
  "AnycubicPrinterMaterialType",
64
64
  "AnycubicProject",
65
65
  "AnycubicPropertiesNotLoaded",
66
+ "AnycubicKvsCredentials",
66
67
  "AnycubicShengwangCredentials",
67
68
  "__version__",
68
69
  ]
@@ -32,6 +32,7 @@ from ..data_models.orders import (
32
32
  AnycubicPrinterOrderRequest,
33
33
  AnycubicPrinterQueryOrderRequest,
34
34
  AnycubicProjectOrderRequest,
35
+ AnycubicKvsCredentials,
35
36
  AnycubicShengwangCredentials,
36
37
  AnycubicStartPrintRequestCloud,
37
38
  AnycubicStartPrintRequestLocal,
@@ -1066,8 +1067,13 @@ class AnycubicAPIFunctions(AnycubicAPIBase):
1066
1067
  self,
1067
1068
  printer: AnycubicPrinter,
1068
1069
  raw_data: bool = False,
1069
- ) -> AnycubicShengwangCredentials | None | dict[str, Any]:
1070
- """Open the cloud camera and return per-session Agora credentials.
1070
+ ) -> AnycubicShengwangCredentials | AnycubicKvsCredentials | None | dict[str, Any]:
1071
+ """Open the cloud camera and return per-session credentials.
1072
+
1073
+ Two transports exist. Most accounts get an Agora (``shengwang``)
1074
+ block; some get only ``data.token``, AWS credentials for a Kinesis
1075
+ Video WebRTC channel (#49). Agora wins when both are present, since
1076
+ that is what the slicer uses whenever the printer supports it.
1071
1077
 
1072
1078
  The credentials are short lived and ``client_uid`` is issued fresh on
1073
1079
  every call, so request them per viewing session rather than caching.
@@ -1094,9 +1100,7 @@ class AnycubicAPIFunctions(AnycubicAPIBase):
1094
1100
  if raw_data:
1095
1101
  return resp
1096
1102
 
1097
- credentials = AnycubicShengwangCredentials.from_order_response(
1098
- resp.get('data') or {}
1099
- )
1103
+ credentials = _camera_credentials(resp.get('data') or {}, printer)
1100
1104
 
1101
1105
  if credentials is not None:
1102
1106
  return credentials
@@ -1122,9 +1126,7 @@ class AnycubicAPIFunctions(AnycubicAPIBase):
1122
1126
  params=order_request.order_request_data
1123
1127
  )
1124
1128
 
1125
- credentials = AnycubicShengwangCredentials.from_order_response(
1126
- resp.get('data') or {}
1127
- )
1129
+ credentials = _camera_credentials(resp.get('data') or {}, printer)
1128
1130
 
1129
1131
  if credentials is None:
1130
1132
  # Genuinely nothing to stream: no camera on this printer.
@@ -2347,3 +2349,14 @@ class AnycubicAPIFunctions(AnycubicAPIBase):
2347
2349
  light_on=light_on,
2348
2350
  brightness=brightness,
2349
2351
  )
2352
+
2353
+
2354
+ def _camera_credentials(
2355
+ data: dict[str, Any],
2356
+ printer: AnycubicPrinter,
2357
+ ) -> AnycubicShengwangCredentials | AnycubicKvsCredentials | None:
2358
+ """Whichever camera transport the cloud offered, Agora first."""
2359
+ return (
2360
+ AnycubicShengwangCredentials.from_order_response(data)
2361
+ or AnycubicKvsCredentials.from_order_response(data, printer.key)
2362
+ )
@@ -42,6 +42,7 @@ from ..helpers.helpers import (
42
42
  get_mqtt_ssl_path_key,
43
43
  get_part_from_mqtt_topic,
44
44
  get_ssl_cert_directory,
45
+ redact_for_log,
45
46
  redact_part_from_mqtt_topic,
46
47
  )
47
48
  from .functions import AnycubicAPIFunctions
@@ -151,7 +152,7 @@ class AnycubicMQTTAPI(AnycubicAPIFunctions):
151
152
  if self._mqtt_topic_is_user_topic(topic):
152
153
  self._log_to_debug(
153
154
  f"Anycubic MQTT USER Msg Received on `{topic}`:\n"
154
- f" {payload}"
155
+ f" {redact_for_log(payload)}"
155
156
  )
156
157
 
157
158
  else:
@@ -182,7 +183,7 @@ class AnycubicMQTTAPI(AnycubicAPIFunctions):
182
183
  f" with type: {e.unhandled_mqtt_type}, "
183
184
  f"action: {e.unhandled_mqtt_action}, "
184
185
  f"state: {e.unhandled_mqtt_state}\n"
185
- f" unhandled data: {e.unhandled_mqtt_data}"
186
+ f" unhandled data: {redact_for_log(e.unhandled_mqtt_data)}"
186
187
  )
187
188
 
188
189
  except AnycubicMQTTUnknownUpdate as e:
@@ -193,7 +194,7 @@ class AnycubicMQTTAPI(AnycubicAPIFunctions):
193
194
  self._log_to_debug(
194
195
  f"Anycubic MQTT Message not understood: {e}\n"
195
196
  f" on MQTT topic: {redacted_topic}\n"
196
- f" {payload}"
197
+ f" {redact_for_log(payload)}"
197
198
  )
198
199
 
199
200
  except Exception as e:
@@ -203,7 +204,7 @@ class AnycubicMQTTAPI(AnycubicAPIFunctions):
203
204
  self._log_to_error(
204
205
  f"Anycubic MQTT Message error: {error_type}: {e}\n"
205
206
  f" on MQTT topic: {redacted_topic}\n"
206
- f" {payload}\n"
207
+ f" {redact_for_log(payload)}\n"
207
208
  f"{tb}"
208
209
  )
209
210
 
@@ -230,7 +231,7 @@ class AnycubicMQTTAPI(AnycubicAPIFunctions):
230
231
  self._log_to_debug(
231
232
  f"Anycubic MQTT Message processed on topic: "
232
233
  f"{redact_part_from_mqtt_topic(topic, 6)}\n"
233
- f" {payload}"
234
+ f" {redact_for_log(payload)}"
234
235
  )
235
236
 
236
237
  def _mqtt_publish_on_topic(
@@ -114,3 +114,27 @@ class AnycubicConsumableData(UserDict[Any, Any]):
114
114
  return self[key]
115
115
  except KeyError:
116
116
  return default
117
+
118
+
119
+ def plain_data(value: Any) -> Any:
120
+ """Unwrap AnycubicConsumableData into plain dicts and lists, all the way down.
121
+
122
+ MQTT payloads arrive wrapped, and every nested dict becomes another
123
+ AnycubicConsumableData -- a ``UserDict``, which ``isinstance(x, dict)``
124
+ rejects. Anything stored for later (slice parameters, settings) should be
125
+ unwrapped first. Reading through the wrapper also marks every key as
126
+ handled, so the copy doesn't leave the payload looking unread.
127
+ """
128
+ if isinstance(value, AnycubicConsumableData):
129
+ unwrapped: dict[Any, Any] = {}
130
+ for key in list(value.data.keys()):
131
+ unwrapped[key] = plain_data(value.get(key))
132
+ # A nested block only counts as read once it is empty and is read
133
+ # again -- the same rule _drain() in printer.py follows.
134
+ value.get(key)
135
+ return unwrapped
136
+ if isinstance(value, dict):
137
+ return {key: plain_data(item) for key, item in value.items()}
138
+ if isinstance(value, list):
139
+ return [plain_data(item) for item in value]
140
+ return value
@@ -638,3 +638,113 @@ class AnycubicShengwangCredentials:
638
638
  f"device_uid={self._device_uid}, "
639
639
  f"encryption_mode={self._encryption_mode})"
640
640
  )
641
+
642
+
643
+ class AnycubicKvsCredentials:
644
+ """Temporary AWS credentials for the camera's Kinesis Video WebRTC channel.
645
+
646
+ The other cloud camera transport. Some accounts get no Agora
647
+ (``shengwang``) block from CAMERA_OPEN at all, only ``data.token`` -- an
648
+ AWS STS triple plus a region (#49). Anycubic Slicer Next views those with
649
+ the Kinesis Video Streams WebRTC SDK as a VIEWER on the signalling channel
650
+ named after the printer's ``key``, so that is what ``channel_name`` holds.
651
+
652
+ Short lived; request per viewing session, never cache.
653
+ """
654
+
655
+ __slots__ = (
656
+ "_region",
657
+ "_access_key_id",
658
+ "_secret_access_key",
659
+ "_session_token",
660
+ "_expiration",
661
+ "_channel_name",
662
+ "_msg_id",
663
+ )
664
+
665
+ def __init__(
666
+ self,
667
+ region: str,
668
+ access_key_id: str,
669
+ secret_access_key: str,
670
+ session_token: str,
671
+ channel_name: str,
672
+ expiration: int | None = None,
673
+ msg_id: str | None = None,
674
+ ) -> None:
675
+ self._region = region
676
+ self._access_key_id = access_key_id
677
+ self._secret_access_key = secret_access_key
678
+ self._session_token = session_token
679
+ self._channel_name = channel_name
680
+ self._expiration = expiration
681
+ self._msg_id = msg_id
682
+
683
+ @classmethod
684
+ def from_order_response(
685
+ cls,
686
+ data: dict[str, Any],
687
+ channel_name: str | None,
688
+ ) -> AnycubicKvsCredentials | None:
689
+ block = data.get('token')
690
+
691
+ if not isinstance(block, dict) or not channel_name:
692
+ return None
693
+
694
+ region = block.get('region')
695
+ access_key_id = block.get('tmpSecretId')
696
+ secret_access_key = block.get('tmpSecretKey')
697
+ session_token = block.get('sessionToken')
698
+
699
+ # The slicer refuses an incomplete set too ("AWS令牌信息不完整").
700
+ if not (region and access_key_id and secret_access_key and session_token):
701
+ return None
702
+
703
+ expiration = block.get('expiration')
704
+
705
+ return cls(
706
+ region=str(region),
707
+ access_key_id=str(access_key_id),
708
+ secret_access_key=str(secret_access_key),
709
+ session_token=str(session_token),
710
+ channel_name=str(channel_name),
711
+ expiration=int(expiration) if isinstance(expiration, (int, float)) else None,
712
+ msg_id=data.get('msgid'),
713
+ )
714
+
715
+ @property
716
+ def region(self) -> str:
717
+ return self._region
718
+
719
+ @property
720
+ def access_key_id(self) -> str:
721
+ return self._access_key_id
722
+
723
+ @property
724
+ def secret_access_key(self) -> str:
725
+ return self._secret_access_key
726
+
727
+ @property
728
+ def session_token(self) -> str:
729
+ return self._session_token
730
+
731
+ @property
732
+ def channel_name(self) -> str:
733
+ return self._channel_name
734
+
735
+ @property
736
+ def expiration(self) -> int | None:
737
+ """As sent; the unit is not documented."""
738
+ return self._expiration
739
+
740
+ @property
741
+ def msg_id(self) -> str | None:
742
+ return self._msg_id
743
+
744
+ def __repr__(self) -> str:
745
+ # Never render any part of the credentials.
746
+ return (
747
+ f"AnycubicKvsCredentials("
748
+ f"region={self._region}, "
749
+ f"channel_name={self._channel_name})"
750
+ )
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
+ from collections.abc import Mapping
4
5
  from typing import TYPE_CHECKING, Any
5
6
 
6
7
  from ..const.enums import (
@@ -30,7 +31,7 @@ from ..helpers.helpers import (
30
31
  timedelta_to_dhm_string,
31
32
  timedelta_to_total_hours,
32
33
  )
33
- from .consumable import AnycubicConsumableData
34
+ from .consumable import AnycubicConsumableData, plain_data
34
35
  from .files import AnycubicFile
35
36
  from .printer_properties import (
36
37
  AnycubicAxisPosition,
@@ -130,6 +131,9 @@ class AnycubicPrinter:
130
131
  "_latest_error_code",
131
132
  "_latest_error_message",
132
133
  "_camera_stream_url",
134
+ # What the printer last said about pushing video to the cloud camera:
135
+ # initSuccess, pushStarted, pushStopped, pushFailed or initFailed.
136
+ "_camera_push_state",
133
137
  "_file_upload_url",
134
138
  "_features",
135
139
  "_ai_settings",
@@ -452,6 +456,12 @@ class AnycubicPrinter:
452
456
  updated.get(box.box_id, box) for box in known_boxes
453
457
  ])
454
458
 
459
+ if known_boxes:
460
+ previous = {box.box_id: box for box in known_boxes}
461
+ for box in self._multi_color_box:
462
+ if (known := previous.get(box.box_id)) is not None and known is not box:
463
+ box.keep_printer_slot_from(known)
464
+
455
465
  except Exception as e:
456
466
  self._initialisation_error = True
457
467
  # Swallowing this leaves the ACE list empty, which presents as
@@ -1144,9 +1154,8 @@ class AnycubicPrinter:
1144
1154
  # if a firmware ever does send some -- unread keys raise at the
1145
1155
  # end of dispatch.
1146
1156
  data = payload['data']
1147
- if isinstance(data, dict):
1148
- for nested in list(data):
1149
- data.get(nested)
1157
+ if isinstance(data, Mapping):
1158
+ plain_data(data)
1150
1159
 
1151
1160
  return
1152
1161
 
@@ -1293,11 +1302,14 @@ class AnycubicPrinter:
1293
1302
  )
1294
1303
  return
1295
1304
  elif action == 'getSliceParam' and state == 'done':
1296
- data = payload['data']['slice_param']
1305
+ data = payload['data']
1297
1306
  self._update_latest_project_slice_param(
1298
1307
  project_id,
1299
- data,
1308
+ plain_data(data['slice_param']),
1300
1309
  )
1310
+ # The rest of the reply (file_key, ams_settings) isn't used, and
1311
+ # isn't an unknown update either.
1312
+ plain_data(data)
1301
1313
  return
1302
1314
  elif action in ['start', 'update'] and state == 'updated':
1303
1315
  data = payload['data']
@@ -1346,7 +1358,13 @@ class AnycubicPrinter:
1346
1358
  # reported as unhandled.
1347
1359
  channel_no, unit_no = data.get('channel_no'), data.get('unit_no')
1348
1360
  if state.endswith('_filament_feeding'):
1349
- self._apply_active_channel(channel_no, unit_no)
1361
+ # The step names its source: extfilbox_* is the printer's own
1362
+ # feeder, ace_* an ACE. Only here is "no unit" a statement.
1363
+ self._apply_active_channel(
1364
+ channel_no,
1365
+ unit_no,
1366
+ own_feeder=state.startswith('extfilbox_'),
1367
+ )
1350
1368
  return
1351
1369
  elif action in ['start', 'stop'] and state in ['failed']:
1352
1370
  err_msg = payload.get('msg')
@@ -1360,7 +1378,12 @@ class AnycubicPrinter:
1360
1378
  else:
1361
1379
  raise AnycubicMQTTUnknownUpdate(ErrorsMQTTUpdate.job_status)
1362
1380
 
1363
- def _apply_active_channel(self, channel_no: Any, unit_no: Any = None) -> None:
1381
+ def _apply_active_channel(
1382
+ self,
1383
+ channel_no: Any,
1384
+ unit_no: Any = None,
1385
+ own_feeder: bool = False,
1386
+ ) -> None:
1364
1387
  """Follow the filament channel the printer says it is printing from.
1365
1388
 
1366
1389
  A Kobra X reports each filament change as a print update carrying
@@ -1371,9 +1394,11 @@ class AnycubicPrinter:
1371
1394
 
1372
1395
  With one box the channel can only mean that box. With several, an
1373
1396
  ACE's ``unit_no`` picks it on a printer whose boxes are all ACEs.
1374
- On a Kobra X with an ACE, which list entry is the printer's own
1375
- feeder is not yet confirmed, so nothing is guessed there: a wrong
1376
- slot is worse than a stale one.
1397
+ A Kobra X lists its own feeder first, then its ACEs: confirmed on
1398
+ #33, where the panel's top row (box 0) is the Kobra X and the bottom
1399
+ row the ACE 2 Pro. So ACE unit N is box N there, and box 0 is used
1400
+ only when the step says it fed from the printer's own feeder
1401
+ (``own_feeder``) -- a progress update without a unit doesn't say.
1377
1402
  """
1378
1403
  channel = as_int(channel_no, 0)
1379
1404
  boxes = self._multi_color_box
@@ -1381,11 +1406,19 @@ class AnycubicPrinter:
1381
1406
  if channel < 1 or not boxes:
1382
1407
  return
1383
1408
 
1384
- if len(boxes) == 1:
1409
+ unit = as_int(unit_no, 0)
1410
+
1411
+ if self._machine_type in _PRINTERS_WITH_OWN_FEEDER and len(boxes) > 1:
1412
+ if own_feeder:
1413
+ box = boxes[0]
1414
+ elif 1 <= unit < len(boxes):
1415
+ box = boxes[unit]
1416
+ else:
1417
+ return
1418
+ elif len(boxes) == 1:
1385
1419
  box = boxes[0]
1386
1420
  else:
1387
- unit = as_int(unit_no, 0)
1388
- if unit < 1 or unit > len(boxes) or self._machine_type in _PRINTERS_WITH_OWN_FEEDER:
1421
+ if unit < 1 or unit > len(boxes):
1389
1422
  return
1390
1423
  box = boxes[unit - 1]
1391
1424
 
@@ -1542,9 +1575,32 @@ class AnycubicPrinter:
1542
1575
  if self.external_shelves:
1543
1576
  self.external_shelves.update_with_mqtt_data(data)
1544
1577
  return
1578
+ elif action == 'auto' and state == 'done':
1579
+ # Sent as a filament change completes, naming the feeding slot as
1580
+ # "<box>-<slot>", both counted from 0 ("0-3" while the screen shows
1581
+ # slot 4 on a Kobra X, #34); empty while the filament is retracted.
1582
+ data = payload.get('data') or {}
1583
+ self._apply_current_filament(data.get('current_filament'))
1584
+ return
1545
1585
  else:
1546
1586
  raise AnycubicMQTTUnknownUpdate(ErrorsMQTTUpdate.shelves)
1547
1587
 
1588
+ def _apply_current_filament(self, current_filament: Any) -> None:
1589
+ """Follow the printer's own "<box>-<slot>" reading, where the box is certain.
1590
+
1591
+ Only with a single box: which list entry the printer's box number
1592
+ means beside an ACE is not confirmed (#33). An empty reading is a
1593
+ retract for calibration or wiping, not a change of slot, so the last
1594
+ slot is kept.
1595
+ """
1596
+ boxes = self._multi_color_box
1597
+ if not isinstance(current_filament, str) or not boxes or len(boxes) != 1:
1598
+ return
1599
+ box_no, _, slot_no = current_filament.partition('-')
1600
+ box_index, slot_index = as_int(box_no, -1), as_int(slot_no, -1)
1601
+ if box_index == 0 and 0 <= slot_index < len(boxes[0].slots):
1602
+ boxes[0].set_slot_loaded(slot_index)
1603
+
1548
1604
  def _process_mqtt_update_file(
1549
1605
  self,
1550
1606
  action: str,
@@ -1594,6 +1650,37 @@ class AnycubicPrinter:
1594
1650
  else:
1595
1651
  raise AnycubicMQTTUnknownUpdate(ErrorsMQTTUpdate.peripherals)
1596
1652
 
1653
+ def _process_mqtt_update_video(
1654
+ self,
1655
+ action: str,
1656
+ state: str | None,
1657
+ payload: AnycubicConsumableData,
1658
+ ) -> None:
1659
+ """The printer reporting on the cloud camera push (#49).
1660
+
1661
+ After a camera-open order the printer answers ``startCapture`` with
1662
+ ``initSuccess`` and then ``pushStarted`` once video is going out, or
1663
+ ``initFailed`` / ``pushFailed``. These used to be logged as an unknown
1664
+ update, which hid the one fact that matters when the picture never
1665
+ arrives: whether the printer actually started sending it.
1666
+ """
1667
+ if state:
1668
+ self._camera_push_state = str(state)
1669
+
1670
+ data = payload.get('data')
1671
+
1672
+ if isinstance(data, Mapping):
1673
+ plain_data(data)
1674
+
1675
+ @property
1676
+ def camera_push_state(self) -> str | None:
1677
+ """The printer's last cloud-camera push state, if it has sent one."""
1678
+ return getattr(self, '_camera_push_state', None)
1679
+
1680
+ def clear_camera_push_state(self) -> None:
1681
+ """Forget the last push state, so a new viewing session waits for its own."""
1682
+ self._camera_push_state = None
1683
+
1597
1684
  def _process_mqtt_update_light(
1598
1685
  self,
1599
1686
  action: str,
@@ -1890,6 +1977,9 @@ class AnycubicPrinter:
1890
1977
  elif msg_type in ('event', 'printerevent', 'printer_event'):
1891
1978
  self._process_mqtt_update_event(action, state, payload)
1892
1979
 
1980
+ elif msg_type == 'video':
1981
+ self._process_mqtt_update_video(action, state, payload)
1982
+
1893
1983
  else:
1894
1984
  raise AnycubicMQTTUnknownUpdate(ErrorsMQTTUpdate.unknown.format(msg_type))
1895
1985
 
@@ -702,6 +702,7 @@ class AnycubicMultiColorBox:
702
702
  "_model_id",
703
703
  "_auto_feed",
704
704
  "_loaded_slot",
705
+ "_slot_from_printer",
705
706
  "_feed_status",
706
707
  "_temp",
707
708
  "_humidity",
@@ -734,6 +735,9 @@ class AnycubicMultiColorBox:
734
735
  self._model_id: int = as_int(model_id)
735
736
  self._auto_feed: int = as_int(auto_feed)
736
737
  self._loaded_slot: int = as_int(loaded_slot, -1)
738
+ # Whether the printer itself has reported the loaded slot, as opposed
739
+ # to a cloud record that only knew it at some earlier point.
740
+ self._slot_from_printer = False
737
741
  self.set_feed_status(feed_status)
738
742
  self.set_current_temperature(temp)
739
743
  self._humidity: float | None = (
@@ -759,7 +763,21 @@ class AnycubicMultiColorBox:
759
763
  self._feed_status = AnycubicFeedStatus.from_json(feed_status)
760
764
 
761
765
  def set_slot_loaded(self, slot_num: int) -> None:
766
+ """A loaded slot reported by the printer (MQTT or LAN)."""
762
767
  self._loaded_slot = as_int(slot_num, -1)
768
+ self._slot_from_printer = True
769
+
770
+ def keep_printer_slot_from(self, previous: AnycubicMultiColorBox) -> None:
771
+ """Carry over a slot the printer reported, past a cloud refresh.
772
+
773
+ The cloud's record of the loaded slot goes stale during a print: a
774
+ Kobra X kept reporting slot 4 while each cloud poll said slot 2, and
775
+ the sensor flipped to 2 mid-print (#34). What the printer said last
776
+ wins until it says something else.
777
+ """
778
+ if previous._slot_from_printer:
779
+ self._loaded_slot = previous._loaded_slot
780
+ self._slot_from_printer = True
763
781
 
764
782
  def set_current_temperature(self, temp: int) -> None:
765
783
  # Reached from the constructor as well as from MQTT, so a null
@@ -17,6 +17,7 @@ from ..exceptions.exceptions import (
17
17
  AnycubicInvalidValue,
18
18
  AnycubicPropertiesNotLoaded,
19
19
  )
20
+ from .consumable import plain_data
20
21
  from ..helpers.helpers import (
21
22
  time_duration_string_to_delta,
22
23
  timedelta_to_dhm_string,
@@ -770,8 +771,9 @@ class AnycubicProject:
770
771
  ErrorsDataParsing.project_settings_json.format(e, new_settings)
771
772
  )
772
773
 
773
- elif new_settings and isinstance(new_settings, dict):
774
- self._settings.update(new_settings)
774
+ elif new_settings and isinstance(new_settings, Mapping):
775
+ # Mapping, not dict: from MQTT this is a UserDict wrapper (#48).
776
+ self._settings.update(plain_data(new_settings))
775
777
 
776
778
  elif new_settings:
777
779
  raise AnycubicDataParsingError(
@@ -792,8 +794,9 @@ class AnycubicProject:
792
794
  ErrorsDataParsing.project_slice_param_json.format(e, new_slice_param)
793
795
  )
794
796
 
795
- elif new_slice_param and isinstance(new_slice_param, dict):
796
- self._slice_param.update(new_slice_param)
797
+ elif new_slice_param and isinstance(new_slice_param, Mapping):
798
+ # Mapping, not dict: from MQTT this is a UserDict wrapper (#48).
799
+ self._slice_param.update(plain_data(new_slice_param))
797
800
 
798
801
  elif new_slice_param:
799
802
  raise AnycubicDataParsingError(
@@ -814,8 +817,9 @@ class AnycubicProject:
814
817
  ErrorsDataParsing.project_slice_result_json.format(e, new_slice_result)
815
818
  )
816
819
 
817
- elif new_slice_result and isinstance(new_slice_result, dict):
818
- self._slice_result.update(new_slice_result)
820
+ elif new_slice_result and isinstance(new_slice_result, Mapping):
821
+ # Mapping, not dict: from MQTT this is a UserDict wrapper (#48).
822
+ self._slice_result.update(plain_data(new_slice_result))
819
823
 
820
824
  elif new_slice_result:
821
825
  raise AnycubicDataParsingError(
@@ -164,6 +164,34 @@ def get_part_from_mqtt_topic(topic: str, part: int) -> str | None:
164
164
  return split_topic[part]
165
165
 
166
166
 
167
+ # Identifiers a printer puts in its own reports. A debug log gets pasted into
168
+ # public issues, and only the topic's printer key was being redacted: a
169
+ # Kobra X's PrintStart report carried its cn_code in the clear (#34).
170
+ _LOG_REDACT_KEYS = frozenset({
171
+ 'cn_code', 'cn', 'sn', 'serial', 'machine_sn', 'mac', 'machine_mac',
172
+ 'ip', 'key', 'printer_key', 'device_id', 'deviceId', 'user_id', 'email',
173
+ })
174
+ _LOG_REDACT_PARTS = ('token', 'secret', 'password')
175
+
176
+
177
+ def redact_for_log(data: Any) -> Any:
178
+ """A copy of an MQTT payload that is safe to put in a log."""
179
+ if isinstance(data, dict):
180
+ return {
181
+ key: (
182
+ "**REDACTED**"
183
+ if isinstance(key, str)
184
+ and data[key] not in (None, '')
185
+ and (key in _LOG_REDACT_KEYS or any(part in key.lower() for part in _LOG_REDACT_PARTS))
186
+ else redact_for_log(data[key])
187
+ )
188
+ for key in data
189
+ }
190
+ if isinstance(data, list):
191
+ return [redact_for_log(item) for item in data]
192
+ return data
193
+
194
+
167
195
  def redact_part_from_mqtt_topic(topic: str, part: int) -> str:
168
196
  split_topic = topic.split("/")
169
197
  new_chunk = list()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: anycubic-cloud-api
3
- Version: 0.4.35
3
+ Version: 0.4.37
4
4
  Summary: Async client for the Anycubic Cloud API and its MQTT stream
5
5
  Author: WaresWichall, Nino Bondonno
6
6
  Maintainer: Nino Bondonno
@@ -45,6 +45,7 @@ src/anycubic_cloud_api/resources/anycubic_mqqt_tls_client.crt
45
45
  src/anycubic_cloud_api/resources/anycubic_mqqt_tls_client.key
46
46
  tests/test_auth_mode_fallback.py
47
47
  tests/test_axis_position.py
48
+ tests/test_camera_kvs_0437.py
48
49
  tests/test_endpoint_urls.py
49
50
  tests/test_exchange_rate_limit.py
50
51
  tests/test_filament_change_0435.py
@@ -56,6 +57,8 @@ tests/test_null_tolerant_parsing.py
56
57
  tests/test_partial_reports.py
57
58
  tests/test_print_reports_0434.py
58
59
  tests/test_printer_error_codes.py
60
+ tests/test_printer_slot_0436.py
59
61
  tests/test_project_null_status.py
60
62
  tests/test_regions.py
61
- tests/test_secondary_ace.py
63
+ tests/test_secondary_ace.py
64
+ tests/test_slice_param_0437.py
@@ -0,0 +1,131 @@
1
+ """The AWS camera transport and the printer's video reports (#49).
2
+
3
+ Some accounts get no Agora block from CAMERA_OPEN, only ``data.token``:
4
+ temporary AWS credentials for a Kinesis Video WebRTC channel named after the
5
+ printer's key. Those were treated as "no credentials" and retried behind a
6
+ fresh login, and the printer's ``video`` reports were logged as unknown.
7
+ """
8
+
9
+ from unittest.mock import AsyncMock, MagicMock
10
+
11
+ import pytest
12
+
13
+ from anycubic_cloud_api.api.functions import AnycubicAPIFunctions
14
+ from anycubic_cloud_api.data_models.consumable import AnycubicConsumableData
15
+ from anycubic_cloud_api.data_models.orders import (
16
+ AnycubicKvsCredentials,
17
+ AnycubicShengwangCredentials,
18
+ )
19
+ from anycubic_cloud_api.data_models.printer import AnycubicPrinter
20
+
21
+ TOKEN = {
22
+ "expiration": 17943490680000000,
23
+ "region": "eu-west-3",
24
+ "sessionToken": "session",
25
+ "tmpSecretId": "ASIAEXAMPLE",
26
+ "tmpSecretKey": "secret",
27
+ }
28
+ SHENGWANG = {
29
+ "appid": "app",
30
+ "channel": "chan",
31
+ "rtc_token": "rtc",
32
+ "client_uid": 5,
33
+ }
34
+
35
+
36
+ class TestKvsCredentials:
37
+ def test_parsed_from_the_token_block(self):
38
+ creds = AnycubicKvsCredentials.from_order_response(
39
+ {"msgid": "m", "token": TOKEN}, "printer-key"
40
+ )
41
+ assert creds is not None
42
+ assert creds.region == "eu-west-3"
43
+ assert creds.access_key_id == "ASIAEXAMPLE"
44
+ assert creds.secret_access_key == "secret"
45
+ assert creds.session_token == "session"
46
+ assert creds.channel_name == "printer-key"
47
+ assert creds.msg_id == "m"
48
+
49
+ @pytest.mark.parametrize("missing", ["region", "sessionToken", "tmpSecretId", "tmpSecretKey"])
50
+ def test_an_incomplete_block_is_no_credentials(self, missing):
51
+ token = {k: v for k, v in TOKEN.items() if k != missing}
52
+ assert AnycubicKvsCredentials.from_order_response({"token": token}, "k") is None
53
+
54
+ def test_no_channel_name_is_no_credentials(self):
55
+ assert AnycubicKvsCredentials.from_order_response({"token": TOKEN}, None) is None
56
+
57
+ def test_repr_never_shows_secrets(self):
58
+ creds = AnycubicKvsCredentials.from_order_response({"token": TOKEN}, "k")
59
+ text = repr(creds)
60
+ for secret in ("session", "ASIAEXAMPLE", "secret"):
61
+ assert secret not in text
62
+
63
+
64
+ def _api(responses):
65
+ api = AnycubicAPIFunctions.__new__(AnycubicAPIFunctions)
66
+ api._fetch_api_resp = AsyncMock(side_effect=responses)
67
+ api._debug_logger = None
68
+ api._anycubic_auth = MagicMock()
69
+ api._check_can_access_api = AsyncMock(return_value=True)
70
+ api._tokens_changed = False
71
+ return api
72
+
73
+
74
+ def _printer():
75
+ printer = MagicMock()
76
+ printer.id = 7
77
+ printer.key = "printer-key"
78
+ return printer
79
+
80
+
81
+ class TestCameraOpen:
82
+ async def test_aws_only_account_gets_kvs_without_a_relogin(self):
83
+ api = _api([{"code": 1, "data": {"msgid": "m", "token": TOKEN}}])
84
+ creds = await api.send_anycubic_camera_open_order(printer=_printer())
85
+ assert isinstance(creds, AnycubicKvsCredentials)
86
+ assert creds.channel_name == "printer-key"
87
+ assert api._fetch_api_resp.await_count == 1
88
+ api._anycubic_auth.clear_cached_access_user_token.assert_not_called()
89
+
90
+ async def test_agora_wins_when_both_are_offered(self):
91
+ api = _api([{"code": 1, "data": {"token": TOKEN, "shengwang": SHENGWANG}}])
92
+ creds = await api.send_anycubic_camera_open_order(printer=_printer())
93
+ assert isinstance(creds, AnycubicShengwangCredentials)
94
+
95
+ async def test_neither_still_retries_behind_a_fresh_login(self):
96
+ api = _api([{"code": 1, "data": {}}, {"code": 1, "data": {"token": TOKEN}}])
97
+ creds = await api.send_anycubic_camera_open_order(printer=_printer())
98
+ assert isinstance(creds, AnycubicKvsCredentials)
99
+ assert api._fetch_api_resp.await_count == 2
100
+
101
+
102
+ def _video(state):
103
+ return AnycubicConsumableData({
104
+ "type": "video",
105
+ "action": "startCapture",
106
+ "state": state,
107
+ "code": 200,
108
+ "msgid": "m",
109
+ "timestamp": 1,
110
+ "data": None,
111
+ })
112
+
113
+
114
+ class TestVideoReports:
115
+ def test_push_state_is_recorded(self):
116
+ printer = AnycubicPrinter(
117
+ api_parent=MagicMock(),
118
+ machine_type=20025,
119
+ machine_name="Kobra S1",
120
+ id=1,
121
+ ignore_init_errors=True,
122
+ )
123
+ assert printer.camera_push_state is None
124
+
125
+ topic = "anycubic/anycubicCloud/v1/printer/public/20025/key/video/report"
126
+ printer.process_mqtt_update(topic, _video("initSuccess"))
127
+ assert printer.camera_push_state == "initSuccess"
128
+ printer.process_mqtt_update(topic, _video("pushStarted"))
129
+ assert printer.camera_push_state == "pushStarted"
130
+ printer.clear_camera_push_state()
131
+ assert printer.camera_push_state is None
@@ -92,16 +92,24 @@ class TestFilamentChange:
92
92
 
93
93
  assert loaded(printer) == expected
94
94
 
95
- @pytest.mark.parametrize(("state", "unit_no"), [
96
- ("extfilbox_filament_feeding", None),
97
- ("ace_filament_feeding", 1),
95
+ @pytest.mark.parametrize(("state", "unit_no", "expected"), [
96
+ # The printer's own feeder sends no unit and is box 0, the top row.
97
+ ("extfilbox_filament_feeding", None, [0, -1]),
98
+ # ACE unit 1 is box 1, the bottom row (#33, confirmed on hardware).
99
+ ("ace_filament_feeding", 1, [-1, 0]),
98
100
  ])
99
- def test_a_kobra_x_with_an_ace_guesses_nothing(self, state, unit_no):
100
- """Which list entry is the Kobra X's own feeder is unconfirmed (#33)."""
101
+ def test_a_kobra_x_with_an_ace_lights_the_right_row(self, state, unit_no, expected):
101
102
  printer = make_printer([box(0), box(1)])
102
103
 
103
104
  feed(printer, state, 1, unit_no)
104
105
 
106
+ assert loaded(printer) == expected
107
+
108
+ def test_a_kobra_x_ace_unit_beyond_its_boxes_changes_nothing(self):
109
+ printer = make_printer([box(0), box(1)])
110
+
111
+ feed(printer, "ace_filament_feeding", 1, 2)
112
+
105
113
  assert loaded(printer) == [-1, -1]
106
114
 
107
115
  @pytest.mark.parametrize(("channel_no", "unit_no"), [(5, 1), (0, 1), (2, 3), ("x", 1), (2, None)])
@@ -0,0 +1,149 @@
1
+ """The printer's own loaded slot, and logs safe to paste (0.4.36).
2
+
3
+ From a Kobra X printing from slot 4 (#34): the sensor flipped to 2 mid-print
4
+ with no message from the printer. Each cloud poll rebuilt the box from the
5
+ cloud's record, whose loaded slot was stale. The printer also names the
6
+ feeding slot itself in its extfilbox report, and its PrintStart report put
7
+ the printer's cn_code into the debug log.
8
+ """
9
+
10
+ import pytest
11
+ from test_filament_change_0435 import (
12
+ KOBRA_S1,
13
+ KOBRA_X,
14
+ box,
15
+ make_printer,
16
+ message,
17
+ topic,
18
+ )
19
+
20
+ from anycubic_cloud_api.helpers.helpers import redact_for_log
21
+
22
+
23
+ def cloud_info(boxes, machine_type=KOBRA_X):
24
+ return {
25
+ "id": 1, "name": "Printer", "key": "k", "machine_type": machine_type, "model": "Printer",
26
+ "img": "", "device_status": 1, "is_printing": 2, "type_function_ids": [], "version": None,
27
+ "multi_color_box": boxes,
28
+ }
29
+
30
+
31
+ def stale_box(box_id, loaded_slot):
32
+ b = box(box_id)
33
+ b["loaded_slot"] = loaded_slot
34
+ return b
35
+
36
+
37
+ def loaded(printer):
38
+ return [b.loaded_slot for b in printer.multi_color_box]
39
+
40
+
41
+ class TestCloudPollKeepsThePrintersSlot:
42
+ def test_a_slot_the_printer_reported_survives_a_cloud_poll(self):
43
+ printer = make_printer([box(0)])
44
+ printer.multi_color_box[0].set_slot_loaded(3)
45
+
46
+ printer.update_from_info_json(cloud_info([stale_box(0, 1)]))
47
+
48
+ assert loaded(printer) == [3]
49
+
50
+ def test_without_a_printer_report_the_cloud_value_is_used(self):
51
+ printer = make_printer([box(0)])
52
+
53
+ printer.update_from_info_json(cloud_info([stale_box(0, 1)]))
54
+
55
+ assert loaded(printer) == [1]
56
+
57
+ def test_the_next_printer_report_still_wins(self):
58
+ printer = make_printer([box(0)])
59
+ printer.multi_color_box[0].set_slot_loaded(3)
60
+ printer.update_from_info_json(cloud_info([stale_box(0, 1)]))
61
+
62
+ printer.multi_color_box[0].set_slot_loaded(0)
63
+
64
+ assert loaded(printer) == [0]
65
+
66
+ def test_each_box_keeps_its_own(self):
67
+ printer = make_printer([box(0), box(1)], machine_type=KOBRA_S1)
68
+ printer.multi_color_box[1].set_slot_loaded(2)
69
+
70
+ printer.update_from_info_json(cloud_info([stale_box(0, 1), stale_box(1, 0)], machine_type=KOBRA_S1))
71
+
72
+ assert loaded(printer) == [1, 2]
73
+
74
+ def test_other_cloud_fields_still_update(self):
75
+ printer = make_printer([box(0)])
76
+ printer.multi_color_box[0].set_slot_loaded(3)
77
+ refreshed = stale_box(0, 1)
78
+ refreshed["temp"] = 33
79
+
80
+ printer.update_from_info_json(cloud_info([refreshed]))
81
+
82
+ assert printer.multi_color_box[0].current_temperature == 33
83
+
84
+
85
+ def extfilbox(printer, current_filament, machine_type=KOBRA_X):
86
+ printer.process_mqtt_update(
87
+ topic(machine_type, "extfilbox"),
88
+ message("extfilbox", "auto", "done", {"current_filament": current_filament}),
89
+ )
90
+
91
+
92
+ class TestCurrentFilament:
93
+ @pytest.mark.parametrize(("reading", "slot"), [("0-3", 3), ("0-0", 0)])
94
+ def test_one_box_follows_the_printer(self, reading, slot):
95
+ printer = make_printer([box(0)])
96
+
97
+ extfilbox(printer, reading)
98
+
99
+ assert loaded(printer) == [slot]
100
+
101
+ @pytest.mark.parametrize("reading", ["", None, "0-9", "1-2", "x", "0-", "-1"])
102
+ def test_a_retract_or_unknown_reading_keeps_the_slot(self, reading):
103
+ printer = make_printer([box(0)])
104
+ printer.multi_color_box[0].set_slot_loaded(3)
105
+
106
+ extfilbox(printer, reading)
107
+
108
+ assert loaded(printer) == [3]
109
+
110
+ def test_with_two_boxes_nothing_is_guessed(self):
111
+ printer = make_printer([box(0), box(1)])
112
+
113
+ extfilbox(printer, "0-3")
114
+
115
+ assert loaded(printer) == [-1, -1]
116
+
117
+ def test_it_survives_the_next_cloud_poll(self):
118
+ printer = make_printer([box(0)])
119
+ extfilbox(printer, "0-3")
120
+
121
+ printer.update_from_info_json(cloud_info([stale_box(0, 1)]))
122
+
123
+ assert loaded(printer) == [3]
124
+
125
+
126
+ class TestRedactForLog:
127
+ def test_printer_identifiers_are_redacted_wherever_they_are(self):
128
+ payload = {"type": "buried", "data": {"cn_code": "CN123", "nested": [{"machine_mac": "AA:BB"}], "ip": "10.0.0.2"}}
129
+
130
+ assert redact_for_log(payload) == {
131
+ "type": "buried",
132
+ "data": {"cn_code": "**REDACTED**", "nested": [{"machine_mac": "**REDACTED**"}], "ip": "**REDACTED**"},
133
+ }
134
+
135
+ @pytest.mark.parametrize("key", ["token", "casdoor_user_token", "rtc_token", "app_secret", "password"])
136
+ def test_credentials_are_redacted(self, key):
137
+ assert redact_for_log({key: "secret-value"}) == {key: "**REDACTED**"}
138
+
139
+ def test_ordinary_fields_and_empty_values_pass_through(self):
140
+ payload = {"progress": 42, "taskid": "131448158", "cn_code": "", "state": "printing", "slots": [1, 2]}
141
+
142
+ assert redact_for_log(payload) == payload
143
+
144
+ def test_the_input_is_not_changed(self):
145
+ payload = {"data": {"cn_code": "CN123"}}
146
+
147
+ redact_for_log(payload)
148
+
149
+ assert payload == {"data": {"cn_code": "CN123"}}
@@ -0,0 +1,98 @@
1
+ """getSliceParam replies were rejected on every printer (#48).
2
+
3
+ MQTT payloads are wrapped in AnycubicConsumableData, which turns every nested
4
+ dict into another AnycubicConsumableData -- a UserDict, not a dict. The
5
+ project setters only accepted ``dict``, so a perfectly normal slice_param
6
+ raised "Unexpected data for project slice_param" with the dict in the message.
7
+ """
8
+
9
+ from unittest.mock import MagicMock
10
+
11
+ import pytest
12
+
13
+ from anycubic_cloud_api.data_models.consumable import (
14
+ AnycubicConsumableData,
15
+ plain_data,
16
+ )
17
+ from anycubic_cloud_api.data_models.printer import AnycubicPrinter
18
+ from anycubic_cloud_api.data_models.project import AnycubicProject
19
+
20
+ TOPIC = "anycubic/anycubicCloud/v1/printer/public/20030/key/print/report"
21
+
22
+ SLICE_PARAM = {
23
+ "bed_temperature": 60,
24
+ "brim_type": "outer_only",
25
+ "filament_retract_length": 0.8,
26
+ "filament_type": ";PLA",
27
+ "fill_density": 15.0,
28
+ "layer_height": 0.2,
29
+ "paint_infos": [
30
+ {
31
+ "filament_used": 7.5,
32
+ "material_type": "PLA",
33
+ "paint_color": [0, 53, 148],
34
+ "paint_index": 1,
35
+ }
36
+ ],
37
+ "printer_settings_id": "Anycubic Kobra 3",
38
+ "remain_time": 23,
39
+ "size_x": 41.14,
40
+ }
41
+
42
+
43
+ def make_printer():
44
+ printer = AnycubicPrinter(
45
+ api_parent=MagicMock(),
46
+ machine_type=20030,
47
+ machine_name="Kobra 3",
48
+ id=1,
49
+ ignore_init_errors=True,
50
+ )
51
+ project = AnycubicProject.from_lan_project(
52
+ MagicMock(), 1, {"task_id": 135980792, "filename": "cube.gcode.3mf", "print_status": 1}
53
+ )
54
+ assert project is not None
55
+ printer._latest_project = project
56
+ return printer, project
57
+
58
+
59
+ def test_slice_param_from_mqtt_is_accepted():
60
+ printer, project = make_printer()
61
+ printer.process_mqtt_update(
62
+ TOPIC,
63
+ AnycubicConsumableData({
64
+ "type": "print",
65
+ "action": "getSliceParam",
66
+ "state": "done",
67
+ "code": 200,
68
+ "msgid": "m",
69
+ "timestamp": 1,
70
+ "data": {
71
+ "ams_settings": {"use_ams": True},
72
+ "file_key": "25b94c6277dd27eebdf1d48631212ab5",
73
+ "slice_param": SLICE_PARAM,
74
+ "taskid": "135980792",
75
+ },
76
+ }),
77
+ )
78
+
79
+ assert project._slice_param["layer_height"] == 0.2
80
+ # Unwrapped all the way down, so later code can rely on plain types.
81
+ assert type(project._slice_param) is dict
82
+ assert type(project._slice_param["paint_infos"][0]) is dict
83
+
84
+
85
+ @pytest.mark.parametrize("setter", ["set_slice_param", "set_slice_result"])
86
+ def test_setters_accept_any_mapping(setter):
87
+ _, project = make_printer()
88
+ getattr(project, setter)(AnycubicConsumableData({"a": {"b": 1}}))
89
+ stored = project._slice_param if setter == "set_slice_param" else project._slice_result
90
+ assert stored == {"a": {"b": 1}}
91
+ assert type(stored["a"]) is dict
92
+
93
+
94
+ def test_plain_data_unwraps_and_consumes():
95
+ wrapped = AnycubicConsumableData({"x": {"y": [{"z": 1}]}, "n": 2})
96
+ assert plain_data(wrapped) == {"x": {"y": [{"z": 1}]}, "n": 2}
97
+ # Everything was read, so nothing is left to be reported as unhandled.
98
+ assert wrapped.is_empty