cloudsprite 0.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,282 @@
1
+ """Publish self-contained Plotly JSON as dataset or notebook views.
2
+
3
+ Plotly is optional: install ``cloudsprite[plotly]`` for ``go.Figure`` input.
4
+ Raw dictionaries work with the base SDK. Only declarative JSON is uploaded.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import builtins
10
+ import json
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any, cast
13
+
14
+ from cloudsprite._exceptions import ValidationError, validate_id
15
+ from cloudsprite._figure_models import (
16
+ FigureRevisionSchema,
17
+ FigureRevisionSummarySchema,
18
+ FigureSchema,
19
+ FigureSupportMatrixSchema,
20
+ )
21
+ from cloudsprite._figure_validation import _scan, preflight, serialize_figure
22
+ from cloudsprite.resources._base import Resource
23
+ from cloudsprite.resources.datasets import Dataset
24
+ from cloudsprite.resources.notebooks import Notebook
25
+
26
+ if TYPE_CHECKING:
27
+ from plotly.graph_objects import Figure as PlotlyFigure
28
+
29
+ from cloudsprite._client import HTTPClient
30
+
31
+
32
+ def _object(value: Any) -> dict[str, Any]:
33
+ if not isinstance(value, dict):
34
+ raise ValidationError("Unexpected figure API response; expected an object")
35
+ return value
36
+
37
+
38
+ def _items(value: Any) -> list[dict[str, Any]]:
39
+ if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
40
+ raise ValidationError("Unexpected figure API response; expected an array of objects")
41
+ return value
42
+
43
+
44
+ def _target_path(target: Dataset | Notebook) -> str:
45
+ if not isinstance(target, (Dataset, Notebook)):
46
+ raise ValidationError("target must be a Dataset or Notebook resource")
47
+ target_id = validate_id(target.id, "target.id")
48
+ if isinstance(target, Dataset):
49
+ return f"/api/datasets/{target_id}"
50
+ return f"/api/notebooks/{target_id}"
51
+
52
+
53
+ def _title(title: str) -> str:
54
+ if not isinstance(title, str) or not title.strip() or len(title) > 255:
55
+ raise ValidationError("title must contain 1–255 characters")
56
+ _scan(title)
57
+ return title
58
+
59
+
60
+ def _revision(revision: int) -> int:
61
+ if type(revision) is not int or revision < 1:
62
+ raise ValidationError("revision must be a positive integer")
63
+ return revision
64
+
65
+
66
+ class Figure(Resource):
67
+ """A saved figure and its current validation result (the server is authoritative)."""
68
+
69
+ @property
70
+ def revision(self) -> int:
71
+ """Current monotonic revision number."""
72
+ return int(self._data["revision"])
73
+
74
+ @property
75
+ def validation_status(self) -> str:
76
+ """Server status, including ``valid``, ``unsupported`` or ``rejected``."""
77
+ return str(self._data["validation_status"])
78
+
79
+ @property
80
+ def validation_reasons(self) -> list[str]:
81
+ """Verbatim server validation reasons."""
82
+ return cast(list[str], self._data.get("validation_reasons", []))
83
+
84
+ @property
85
+ def support_report(self) -> dict[str, Any]:
86
+ """Verbatim server support report; unsupported traces are not filtered out."""
87
+ return cast(dict[str, Any], self._data.get("support_report", {}))
88
+
89
+ @property
90
+ def payload(self) -> FigureSchema:
91
+ """Complete response with wire fields generated from development OpenAPI."""
92
+ return cast(FigureSchema, self._data)
93
+
94
+
95
+ class FigureCollection:
96
+ """Saved figure operations, scoped explicitly to a dataset or notebook."""
97
+
98
+ def __init__(self, client: HTTPClient) -> None:
99
+ self._client = client
100
+
101
+ def support_matrix(self) -> FigureSupportMatrixSchema:
102
+ """Fetch the current renderer support matrix and preflight limits."""
103
+ return cast(FigureSupportMatrixSchema, _object(self._client.get("/api/figures/support-matrix/")))
104
+
105
+ def _prepare(self, figure: PlotlyFigure | dict[str, Any], config: dict[str, Any] | None) -> dict[str, Any]:
106
+ payload, version = serialize_figure(figure, config)
107
+ preflight(payload, dict(self.support_matrix()))
108
+ if version:
109
+ payload["plotly_version"] = version
110
+ payload["producer"] = "cloudsprite-py"
111
+ return payload
112
+
113
+ def _target_params(self, target: Dataset | Notebook) -> dict[str, str]:
114
+ path = _target_path(target)
115
+ data = target._data
116
+ if not data.get("project_id"):
117
+ data = _object(self._client.get(path))
118
+ project_id = data.get("project_id")
119
+ if not isinstance(project_id, str) or not project_id:
120
+ raise ValidationError("Figure target must have a project_id")
121
+ key = "dataset_id" if isinstance(target, Dataset) else "notebook_id"
122
+ return {"project_id": validate_id(project_id, "project_id"), key: target.id}
123
+
124
+ def publish(
125
+ self,
126
+ *,
127
+ target: Dataset | Notebook,
128
+ figure: PlotlyFigure | dict[str, Any],
129
+ title: str,
130
+ config: dict[str, Any] | None = None,
131
+ set_preferred: bool = False,
132
+ ) -> Figure:
133
+ """Publish a figure after local safety and live-limit preflight.
134
+
135
+ Returns the server's id, revision, validation status and support report.
136
+ The backend automatically selects the first valid figure when no preferred
137
+ view exists. ``set_preferred=True`` explicitly selects this upload with a
138
+ second permission-checked request. If that request fails, the figure remains
139
+ saved and the original SDK exception includes its response as ``published_figure``.
140
+ Unsupported traces/frames are uploaded so the server report is preserved.
141
+ """
142
+ _title(title)
143
+ _target_path(target)
144
+ payload = self._prepare(figure, config)
145
+ payload.update(self._target_params(target), name=title, title=title, source="sdk")
146
+ result = Figure(self._client, _object(self._client.post("/api/figures/upload-json/", json=payload)))
147
+ if set_preferred:
148
+ from cloudsprite._exceptions import CloudSpriteError
149
+
150
+ try:
151
+ self.set_preferred(target, result.id)
152
+ except CloudSpriteError as exc:
153
+ # Preserve exception type/status/body while identifying the completed write.
154
+ exc.published_figure = result # type: ignore[attr-defined]
155
+ raise
156
+ return result
157
+
158
+ def create(
159
+ self,
160
+ *,
161
+ target: Dataset | Notebook,
162
+ figure: PlotlyFigure | dict[str, Any],
163
+ title: str,
164
+ config: dict[str, Any] | None = None,
165
+ ) -> Figure:
166
+ """Create through createFigure with the same safety checks as publish."""
167
+ _title(title)
168
+ _target_path(target)
169
+ payload = self._prepare(figure, config)
170
+ payload.update(self._target_params(target), name=title, title=title, source="sdk")
171
+ return Figure(self._client, _object(self._client.post("/api/figures/", json=payload)))
172
+
173
+ def list(self, target: Dataset | Notebook) -> list[Figure]:
174
+ """List all figures attached to a target, following offset pagination."""
175
+ params: dict[str, Any] = self._target_params(target)
176
+ params.update(offset=0, limit=200)
177
+ result: builtins.list[Figure] = []
178
+ while True:
179
+ page = _items(self._client.get("/api/figures/", params=params))
180
+ result.extend(Figure(self._client, item) for item in page)
181
+ if len(page) < 200:
182
+ return result
183
+ params["offset"] += len(page)
184
+
185
+ def get(self, figure_id: str) -> Figure:
186
+ """Fetch a saved figure including its JSON and validation report."""
187
+ figure_id = validate_id(figure_id, "figure_id")
188
+ return Figure(self._client, _object(self._client.get(f"/api/figures/{figure_id}/")))
189
+
190
+ def replace(
191
+ self,
192
+ figure_id: str,
193
+ *,
194
+ figure: PlotlyFigure | dict[str, Any],
195
+ title: str | None = None,
196
+ config: dict[str, Any] | None = None,
197
+ ) -> Figure:
198
+ """Replace content after preflight, returning the new immutable revision.
199
+
200
+ This is a full content replacement: omitted config/frames become empty.
201
+ Prior revisions remain available via ``get_revision``.
202
+ """
203
+ figure_id = validate_id(figure_id, "figure_id")
204
+ if title is not None:
205
+ _title(title)
206
+ payload = self._prepare(figure, config)
207
+ if title is not None:
208
+ payload["title"] = title
209
+ return Figure(self._client, _object(self._client.post(f"/api/figures/{figure_id}/replace/", json=payload)))
210
+
211
+ def update(self, figure_id: str, *, title: str) -> Figure:
212
+ """Update the title in place; use replace for content changes."""
213
+ figure_id = validate_id(figure_id, "figure_id")
214
+ return Figure(
215
+ self._client, _object(self._client.patch(f"/api/figures/{figure_id}/", json={"title": _title(title)}))
216
+ )
217
+
218
+ def delete(self, figure_id: str) -> None:
219
+ """Soft-delete a figure and clear its preferred-view pointers."""
220
+ figure_id = validate_id(figure_id, "figure_id")
221
+ self._client.delete(f"/api/figures/{figure_id}/")
222
+
223
+ def list_revisions(self, figure_id: str) -> builtins.list[FigureRevisionSummarySchema]:
224
+ """List immutable revision summaries for a figure."""
225
+ figure_id = validate_id(figure_id, "figure_id")
226
+ return cast(
227
+ builtins.list[FigureRevisionSummarySchema], _items(self._client.get(f"/api/figures/{figure_id}/revisions/"))
228
+ )
229
+
230
+ def get_revision(self, figure_id: str, revision: int) -> FigureRevisionSchema:
231
+ """Fetch one immutable revision including its original content."""
232
+ figure_id = validate_id(figure_id, "figure_id")
233
+ revision = _revision(revision)
234
+ return cast(FigureRevisionSchema, _object(self._client.get(f"/api/figures/{figure_id}/revisions/{revision}/")))
235
+
236
+ def set_preferred(self, target: Dataset | Notebook, figure_id: str) -> Dataset | Notebook:
237
+ """Select an attached valid figure; requires dataset:update or notebook:update.
238
+
239
+ Dispatches to the target's preferred-figure PUT endpoint. For a single
240
+ REST catalog operation use ``Dataset.set_preferred_figure`` or
241
+ ``Notebook.set_preferred_figure``.
242
+ """
243
+ path = _target_path(target)
244
+ figure_id = validate_id(figure_id, "figure_id")
245
+ data = _object(self._client.put(f"{path}/preferred-figure", json={"figure_id": figure_id}))
246
+ target._data.update(data)
247
+ return target
248
+
249
+ def clear_preferred(self, target: Dataset | Notebook) -> Dataset | Notebook:
250
+ """Clear the selected figure, restoring the target's normal graph view.
251
+
252
+ Requires dataset:update or notebook:update. Single-endpoint catalog
253
+ methods are ``Dataset.clear_preferred_figure`` and ``Notebook.clear_preferred_figure``.
254
+ """
255
+ path = _target_path(target)
256
+ data = _object(self._client.delete(f"{path}/preferred-figure"))
257
+ target._data.update(data)
258
+ return target
259
+
260
+ def download_original(
261
+ self, figure_id: str, *, revision: int | None = None, path: str | Path | None = None
262
+ ) -> bytes:
263
+ """Download original stored figure content as JSON, optionally writing to path.
264
+
265
+ The API has no dedicated download endpoint. Fetch the current figure or a
266
+ revision and serialize its stored data/layout/frames/config JSON. This
267
+ preserves the original content, including unsupported traces. It is not
268
+ a byte-for-byte S3 download: JSON storage can reorder nested object keys,
269
+ so these bytes cannot be checked against ``original_upload_hash``.
270
+ Never renders HTML or executes code.
271
+ """
272
+ data = dict(self.get(figure_id).payload) if revision is None else dict(self.get_revision(figure_id, revision))
273
+ figure = _object(data["figure"])
274
+ document = {"data": figure.get("data"), "layout": figure.get("layout")}
275
+ if data.get("frames") is not None:
276
+ document["frames"] = data["frames"]
277
+ if data.get("config"):
278
+ document["config"] = data["config"]
279
+ content = json.dumps(document, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
280
+ if path is not None:
281
+ Path(path).write_bytes(content)
282
+ return content
@@ -0,0 +1,295 @@
1
+ """Instrument resource — scientific test & measurement equipment.
2
+
3
+ Instruments are physical devices (oscilloscopes, VNAs, spectrum analyzers)
4
+ connected to orbs. The SDK can query status, read live state, issue control
5
+ commands, and trigger captures.
6
+
7
+ Example:
8
+ >>> scope = cs.instruments["MSOX3104G"]
9
+ >>> print(scope.status) # "connected"
10
+ >>> result = scope.capture(dataset_id=ds.id)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from collections.abc import Callable, Sequence
17
+ from typing import Any
18
+
19
+ from cloudsprite._exceptions import CloudSpriteError, ValidationError, validate_id
20
+ from cloudsprite.resources._base import Resource
21
+
22
+
23
+ def _state_error(result: dict[str, Any]) -> str:
24
+ """Readable error from a failed state or control reply (``error`` may be a string or ``{"message"}``)."""
25
+ err = result.get("error")
26
+ if isinstance(err, dict):
27
+ err = err.get("message")
28
+ code = result.get("error_code")
29
+ text = str(err) if err else "unknown error"
30
+ return f"{text} ({code})" if code else text
31
+
32
+
33
+ class Instrument(Resource):
34
+ """A scientific instrument instance connected to an orb.
35
+
36
+ Attributes:
37
+ id: Unique identifier (UUID).
38
+ name: Display name.
39
+ model_number: Instrument model (e.g. "MSOX3104G").
40
+ visa_address: VISA resource string for instrument communication.
41
+ serial_number: Manufacturer serial number.
42
+ status: Connection status ("connected", "disconnected", "unknown").
43
+ orb_id: UUID of the orb this instrument is connected to.
44
+ mode: Operating mode ("auto", "real", "simulated").
45
+ """
46
+
47
+ @property
48
+ def model_number(self) -> str:
49
+ """Instrument model number (e.g. 'MSOX3104G', 'N9042B')."""
50
+ return str(self._data.get("instrument_model", ""))
51
+
52
+ @property
53
+ def visa_address(self) -> str:
54
+ """VISA address string (e.g. 'TCPIP::192.168.1.100::INSTR')."""
55
+ return str(self._data.get("visa_address", ""))
56
+
57
+ @property
58
+ def serial_number(self) -> str:
59
+ """Hardware serial number."""
60
+ return str(self._data.get("serial_number", ""))
61
+
62
+ @property
63
+ def status(self) -> str:
64
+ """Connection status: 'connected', 'disconnected', or 'unknown'."""
65
+ return str(self._data.get("connection_status", "unknown"))
66
+
67
+ @property
68
+ def orb_id(self) -> str | None:
69
+ """UUID of the orb this instrument is associated with, or None."""
70
+ value = self._data.get("orb_id")
71
+ return None if value is None else str(value)
72
+
73
+ @property
74
+ def mode(self) -> str:
75
+ """Operating mode: 'auto', 'real', or 'simulated'."""
76
+ return str(self._data.get("mode", "auto"))
77
+
78
+ def update(self, **kwargs: Any) -> None:
79
+ """Update instrument fields (name, visa_address, mode, etc.).
80
+
81
+ Args:
82
+ **kwargs: Fields to update.
83
+
84
+ Example:
85
+ >>> scope.update(name="Lab Scope #2", mode="simulated")
86
+ """
87
+ data = self._client.patch(f"/api/instruments/{self.id}/", json=kwargs)
88
+ if isinstance(data, dict):
89
+ self._data.update(data)
90
+
91
+ def delete(self) -> None:
92
+ """Delete this instrument registration.
93
+
94
+ Removes the instrument from the platform. Does not affect the
95
+ physical device.
96
+
97
+ Server: ``DELETE /api/instruments/{id}/`` (trailing slash required).
98
+ """
99
+ self._client.delete(f"/api/instruments/{self.id}/")
100
+
101
+ def capture(self, dataset_id: str, timeout: float = 60.0, **kwargs: Any) -> dict[str, Any]:
102
+ """Trigger a capture on this instrument and wait for completion.
103
+
104
+ Sends a capture_all command to the orb via WebSocket. The orb
105
+ executes the instrument driver's full capture sequence (waveform,
106
+ screenshot, measurements) and uploads results to the specified dataset.
107
+
108
+ Args:
109
+ dataset_id: UUID of the dataset to store captured data.
110
+ timeout: Maximum seconds to wait for completion (default: 60).
111
+ **kwargs: Capture options:
112
+ - simulation_mode (bool): Use simulated data generation.
113
+ - noise_level (float): Noise multiplier (0=clean, 1=realistic, 10=extreme).
114
+ - sim_scenario (str): Scenario name ("composite_signal", "square_wave", etc.).
115
+ - channel (int): Oscilloscope channel number (default: 1).
116
+ - target_orb_id (str): Specific orb UUID (default: any with this instrument).
117
+
118
+ Returns:
119
+ dict with keys:
120
+ - success (bool): Whether capture completed successfully.
121
+ - completed (int): Number of sub-commands that succeeded.
122
+ - total (int): Total sub-commands in the capture sequence.
123
+ - error (str, optional): Error description if failed.
124
+
125
+ Example:
126
+ >>> result = scope.capture(dataset_id=ds.id, timeout=30)
127
+ >>> if result["success"]:
128
+ ... print(f"Captured {result['completed']}/{result['total']} commands")
129
+ """
130
+ validate_id(dataset_id, "dataset_id")
131
+ from cloudsprite._ws import capture_all
132
+
133
+ return capture_all(
134
+ client=self._client,
135
+ instrument_id=self.id,
136
+ dataset_id=dataset_id,
137
+ timeout=timeout,
138
+ **kwargs,
139
+ )
140
+
141
+ def state(
142
+ self,
143
+ sections: list[str] | None = None,
144
+ timeout: float = 15.0,
145
+ **kwargs: Any,
146
+ ) -> dict[str, Any]:
147
+ """Fetch live instrument state via WebSocket.
148
+
149
+ Sends ``get_instrument_state`` to the orb and waits for
150
+ ``instrument_state``.
151
+
152
+ Args:
153
+ sections: Optional list of state section names to return
154
+ (e.g. ``["channel", "timebase"]``). ``None`` asks for the
155
+ driver's default/full state.
156
+ timeout: Maximum seconds to wait for completion (default: 15).
157
+ **kwargs: Optional ``target_orb_id`` to pin a specific orb.
158
+
159
+ Returns:
160
+ dict with keys:
161
+ - success (bool): Whether the state query succeeded.
162
+ - state (dict, optional): Sectioned instrument state on success.
163
+ - error (str, optional): Error description if failed.
164
+
165
+ Example:
166
+ >>> result = scope.state(sections=["timebase", "trigger"])
167
+ >>> if result["success"]:
168
+ ... print(result["state"]["timebase"])
169
+ """
170
+ from cloudsprite._ws import get_instrument_state
171
+
172
+ return get_instrument_state(
173
+ client=self._client,
174
+ instrument_id=self.id,
175
+ sections=sections,
176
+ timeout=timeout,
177
+ **kwargs,
178
+ )
179
+
180
+ def wait_settled(
181
+ self,
182
+ timeout: float = 60.0,
183
+ poll: float = 0.5,
184
+ *,
185
+ sections: Sequence[str] | None = ("position", "moving"),
186
+ until: Callable[[dict[str, Any]], bool] | None = None,
187
+ state_timeout: float = 15.0,
188
+ **kwargs: Any,
189
+ ) -> dict[str, Any]:
190
+ """Poll :meth:`state` until the instrument has settled, or raise.
191
+
192
+ Built for actuators: a positioner ``seek`` returns at once, and the state's
193
+ ``moving`` section stays true until the move ends. By default this waits for
194
+ ``moving`` to be false. Pass ``until`` to wait on something else (it receives
195
+ the ``state`` dict and returns True when settled).
196
+
197
+ Each poll is a full state round trip (about a second of connection setup),
198
+ so ``poll`` is the pause *between* polls, not the whole cycle. The call
199
+ never reports "settled" on a failed or partial answer: a failed state query
200
+ raises, and a state without ``moving``, or with a ``moving`` that is not true or false, raises
201
+ (unless ``until`` is given).
202
+
203
+ Args:
204
+ timeout: Maximum seconds to wait for the instrument to settle (default: 60).
205
+ poll: Seconds to sleep between polls (default: 0.5).
206
+ sections: State sections to request on each poll. ``None`` asks for the
207
+ driver's full state. The default is ``position`` and ``moving``.
208
+ until: Optional settle predicate over the ``state`` dict.
209
+ state_timeout: Seconds to wait for each single state query (default: 15).
210
+ **kwargs: Passed to :meth:`state` (for example ``target_orb_id``).
211
+
212
+ Returns:
213
+ The ``state`` dict from the poll that found the instrument settled, for
214
+ example ``{"moving": False, "position": {"azimuth_deg": 90.0, ...}}``.
215
+
216
+ Raises:
217
+ TimeoutError: The instrument had not settled within ``timeout``.
218
+ CloudSpriteError: A state query failed (not reachable, reserved, driver error), or
219
+ ``moving`` was neither true nor false.
220
+ ValidationError: The state has no ``moving`` section and no ``until`` was given.
221
+
222
+ Example:
223
+ >>> turntable.control("seek", azimuth_deg=90.0, height_cm=150.0)
224
+ >>> state = turntable.wait_settled(timeout=120)
225
+ >>> state["position"]["azimuth_deg"]
226
+ 90.0
227
+ """
228
+ if timeout <= 0 or poll < 0:
229
+ raise ValidationError("wait_settled needs timeout > 0 and poll >= 0")
230
+ requested = None if sections is None else list(sections)
231
+ deadline = time.monotonic() + timeout
232
+ while True:
233
+ result = self.state(sections=requested, timeout=state_timeout, **kwargs)
234
+ if not result.get("success"):
235
+ raise CloudSpriteError(f"state query failed while waiting for {self.name!r}: {_state_error(result)}")
236
+ state = result.get("state")
237
+ if not isinstance(state, dict):
238
+ raise CloudSpriteError(f"state query for {self.name!r} returned no state")
239
+ if until is not None:
240
+ settled = bool(until(state))
241
+ elif "moving" not in state:
242
+ raise ValidationError(
243
+ f"{self.name!r} reports no 'moving' state section; pass until=... to say what settled means"
244
+ )
245
+ elif state["moving"] is True:
246
+ settled = False
247
+ elif state["moving"] is False:
248
+ settled = True
249
+ else:
250
+ raise CloudSpriteError(
251
+ f"{self.name!r} reported moving={state['moving']!r}, not true or false; cannot tell if it settled"
252
+ )
253
+ if settled:
254
+ return state
255
+ if time.monotonic() + poll >= deadline:
256
+ raise TimeoutError(f"{self.name!r} had not settled after {timeout:g} s")
257
+ time.sleep(poll)
258
+
259
+ def control(self, method: str, timeout: float = 15.0, **args: Any) -> dict[str, Any]:
260
+ """Invoke a driver control method via WebSocket.
261
+
262
+ Sends ``instrument_control`` to the orb and waits for
263
+ ``instrument_control_response``. Extra kwargs besides
264
+ ``target_orb_id`` are placed in the WS ``args`` object.
265
+
266
+ Args:
267
+ method: Driver control method name (e.g. ``set_timebase``).
268
+ timeout: Maximum seconds to wait for completion (default: 15).
269
+ **args: Control arguments forwarded in the WS ``args`` object.
270
+ Pass ``target_orb_id`` to pin a specific orb (top-level field,
271
+ not inside ``args``).
272
+
273
+ Returns:
274
+ dict with keys:
275
+ - success (bool): Whether the control call succeeded.
276
+ - result (Any, optional): Driver result payload on success.
277
+ - error (str, optional): Error description if failed.
278
+
279
+ Example:
280
+ >>> result = scope.control("set_timebase", scale=1e-6)
281
+ >>> if result["success"]:
282
+ ... print(result.get("result"))
283
+ """
284
+ from cloudsprite._ws import instrument_control
285
+
286
+ return instrument_control(
287
+ client=self._client,
288
+ instrument_id=self.id,
289
+ method=method,
290
+ timeout=timeout,
291
+ **args,
292
+ )
293
+
294
+ def __repr__(self) -> str:
295
+ return f"Instrument('{self.name}', model='{self.model_number}')"