-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot_client.py
349 lines (308 loc) · 12.6 KB
/
robot_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
from __future__ import annotations
import asyncio
import concurrent.futures
import contextlib
import json
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, List
import httpx
from httpx import Response
STARTUP_WAIT = 15
SHUTDOWN_WAIT = 15
class RobotClient:
"""Client for the robot's HTTP API.
This is mostly a thin wrapper, where most methods have a 1:1 correspondence
with HTTP endpoints. See the robot server's OpenAPI specification for
details on semantics and request/response shapes.
"""
def __init__(
self,
httpx_client: httpx.AsyncClient,
worker_executor: concurrent.futures.ThreadPoolExecutor,
host: str,
port: str,
) -> None:
"""Initialize the client."""
self.base_url: str = f"{host}:{port}"
self.httpx_client: httpx.AsyncClient = httpx_client
self.worker_executor: concurrent.futures.ThreadPoolExecutor = worker_executor
@staticmethod
@contextlib.asynccontextmanager
async def make(host: str, port: str, version: str) -> AsyncGenerator[RobotClient, None]:
with concurrent.futures.ThreadPoolExecutor() as worker_executor:
async with httpx.AsyncClient(headers={"opentrons-version": version}) as httpx_client:
yield RobotClient(
httpx_client=httpx_client,
worker_executor=worker_executor,
host=host,
port=port,
)
async def alive(self) -> bool:
"""Are /health and /openapi.json both reachable?"""
try:
await self.get_health()
await self.get_openapi()
return True
except (httpx.ConnectError, httpx.HTTPStatusError):
return False
async def dead(self) -> bool:
"""Are /health and /openapi.json both unreachable?"""
try:
await self.get_health()
return False
except httpx.HTTPStatusError:
return False
except httpx.ConnectError:
pass
try:
await self.get_openapi()
return False
except httpx.HTTPStatusError:
return False
except httpx.ConnectError:
# Now both /health and /openapi.json have returned ConnectError.
return True
async def _poll_for_alive(self) -> None:
"""Retry the /health and /openapi.json until both reachable."""
while not await self.alive():
# Avoid spamming the server in case a request immediately
# returns some kind of "not ready."
await asyncio.sleep(0.1)
async def _poll_for_dead(self) -> None:
"""Poll the /health and /openapi.json until both unreachable."""
while not await self.dead():
# Avoid spamming the server in case a request immediately
# returns some kind of "not ready."
await asyncio.sleep(0.1)
async def wait_until_alive(self, timeout_sec: float = STARTUP_WAIT) -> bool:
try:
await asyncio.wait_for(self._poll_for_alive(), timeout=timeout_sec)
return True
except asyncio.TimeoutError:
return False
async def wait_until_dead(self, timeout_sec: float = SHUTDOWN_WAIT) -> bool:
"""Retry the /health and /openapi.json until both unreachable."""
try:
await asyncio.wait_for(self._poll_for_dead(), timeout=timeout_sec)
return True
except asyncio.TimeoutError:
return False
async def get_health(self) -> Response:
"""GET /health."""
response = await self.httpx_client.get(url=f"{self.base_url}/health", timeout=60)
# response.raise_for_status()
return response
async def get_openapi(self) -> Response:
"""GET /openapi.json."""
response = await self.httpx_client.get(url=f"{self.base_url}/openapi.json")
response.raise_for_status()
return response
async def get_protocols(self) -> Response:
"""GET /protocols."""
response = await self.httpx_client.get(url=f"{self.base_url}/protocols", timeout=180)
response.raise_for_status()
return response
async def get_protocol(self, protocol_id: str) -> Response:
"""GET /protocols/{protocol_id}."""
response = await self.httpx_client.get(url=f"{self.base_url}/protocols/{protocol_id}", timeout=60)
return response
async def post_data_file(self, files: List[Path] | bytes) -> Response:
file_payload = []
if isinstance(files, bytes):
file_payload.append(("file", files))
else:
for file in files:
file_payload.append(("file", open(file, "rb")))
response = await self.httpx_client.post(url=f"{self.base_url}/dataFiles", files=file_payload, timeout=120)
return response
async def post_protocol(
self, files: List[Path] | bytes, labware_files=None, run_time_parameter_values=None, run_time_parameter_files=None
) -> Response:
"""POST /protocols."""
if run_time_parameter_files is None:
run_time_parameter_files = {}
if run_time_parameter_values is None:
run_time_parameter_values = {}
file_payload = []
if isinstance(files, bytes):
file_payload.append(("files", files))
else:
for file in files:
file_payload.append(("files", open(file, "rb")))
if labware_files is not None:
raise NotImplementedError("Labware files are not yet supported")
# Include the form fields (JSON data) as strings
file_payload.append(
(
"runTimeParameterValues",
(None, json.dumps(run_time_parameter_values), "application/json"),
)
)
file_payload.append(
(
"runTimeParameterFiles",
(None, json.dumps(run_time_parameter_files), "application/json"),
)
)
file_payload.append(("protocolKind", (None, "standard")))
response = await self.httpx_client.post(url=f"{self.base_url}/protocols", files=file_payload, timeout=120)
response.raise_for_status()
return response
async def post_simple_command(
self,
req_body: Dict[str, object],
params: Dict[str, Any],
timeout_sec: float = 30.0,
) -> Response:
"""POST /commands."""
response = await self.httpx_client.post(
url=f"{self.base_url}/commands",
json=req_body,
params=params,
timeout=timeout_sec,
)
# response.raise_for_status()
return response
async def get_runs(self) -> Response:
"""GET /runs."""
response = await self.httpx_client.get(url=f"{self.base_url}/runs")
response.raise_for_status()
return response
async def post_run(self, req_body: Dict[str, object]) -> Response:
"""POST /runs."""
response = await self.httpx_client.post(url=f"{self.base_url}/runs", json=req_body, timeout=15)
return response
async def patch_run(self, run_id: str, req_body: Dict[str, object]) -> Response:
"""POST /runs."""
response = await self.httpx_client.patch(url=f"{self.base_url}/runs/{run_id}", json=req_body, timeout=15)
response.raise_for_status()
return response
async def get_run(self, run_id: str) -> Response:
"""GET /runs/:run_id."""
response = await self.httpx_client.get(url=f"{self.base_url}/runs/{run_id}", timeout=15)
response.raise_for_status()
return response
async def post_run_command(
self,
run_id: str,
req_body: Dict[str, object],
params: Dict[str, Any],
timeout_sec: float = 30.0,
) -> Response:
"""POST /runs/:run_id/commands."""
response = await self.httpx_client.post(
url=f"{self.base_url}/runs/{run_id}/commands",
json=req_body,
params=params,
timeout=timeout_sec,
)
# response.raise_for_status()
return response
async def get_run_commands(self, run_id: str) -> Response:
"""GET /runs/:run_id/commands."""
response = await self.httpx_client.get(url=f"{self.base_url}/runs/{run_id}/commands", params={"pageLength": 300})
response.raise_for_status()
return response
async def get_run_command(self, run_id: str, command_id: str) -> Response:
"""GET /runs/:run_id/commands/:command_id."""
response = await self.httpx_client.get(url=f"{self.base_url}/runs/{run_id}/commands/{command_id}")
response.raise_for_status()
return response
async def post_labware_offset(
self,
run_id: str,
req_body: Dict[str, object],
) -> Response:
"""POST /runs/:run_id/labware_offsets."""
response = await self.httpx_client.post(
url=f"{self.base_url}/runs/{run_id}/labware_offsets",
json=req_body,
)
response.raise_for_status()
return response
async def post_run_action(
self,
run_id: str,
req_body: Dict[str, object],
) -> Response:
"""POST /runs/:run_id/commands."""
response = await self.httpx_client.post(url=f"{self.base_url}/runs/{run_id}/actions", json=req_body, timeout=15)
response.raise_for_status()
return response
async def get_analysis(self, protocol_id: str, analysis_id: str) -> Response:
"""GET /protocols/{protocol_id}/{analysis_id}."""
response = await self.httpx_client.get(url=f"{self.base_url}/protocols/{protocol_id}/analyses/{analysis_id}", timeout=6000)
response.raise_for_status()
return response
async def get_analysis_as_doc(self, protocol_id: str, analysis_id: str) -> Response:
"""GET /protocols/{protocol_id}/{analysis_id}."""
response = await self.httpx_client.get(
url=f"{self.base_url}/protocols/{protocol_id}/analyses/{analysis_id}/asDocument", timeout=6000
)
response.raise_for_status()
return response
async def get_analyses(self, protocol_id: str) -> Response:
"""GET /protocols/{protocol_id}/{analysis_id}."""
response = await self.httpx_client.get(url=f"{self.base_url}/protocols/{protocol_id}/analyses", timeout=60)
response.raise_for_status()
return response
async def delete_run(self, run_id: str) -> Response:
"""DELETE /runs/{run_id}."""
response = await self.httpx_client.delete(f"{self.base_url}/runs/{run_id}", timeout=15)
response.raise_for_status()
return response
async def post_setting_reset_options(
self,
req_body: Dict[str, bool],
) -> Response:
"""POST /settings/reset."""
response = await self.httpx_client.post(
url=f"{self.base_url}/settings/reset",
json=req_body,
)
response.raise_for_status()
return response
async def get_settings(
self,
) -> Response:
"""GET /settings"""
response = await self.httpx_client.get(
url=f"{self.base_url}/settings",
)
response.raise_for_status()
return response
async def post_setting(
self,
id: str,
value: bool | int | str,
) -> Response:
"""POST /settings/reset."""
response = await self.httpx_client.post(
url=f"{self.base_url}/settings",
json={"id": id, "value": value},
)
response.raise_for_status()
return response
async def get_modules(self) -> Response:
"""GET /modules."""
response = await self.httpx_client.get(url=f"{self.base_url}/modules", timeout=15)
response.raise_for_status()
return response
async def get_pipettes(self) -> Response:
"""GET /pipettes."""
response = await self.httpx_client.get(url=f"{self.base_url}/pipettes")
response.raise_for_status()
return response
async def get_instruments(self, refresh=False) -> Response:
"""GET /instruments.
If refresh=True, actively scan for attached pipettes. Note: this requires disabling the pipette motors
and should only be done when no protocol is running and you know it won't cause a problem.
"""
response = await self.httpx_client.get(url=f"{self.base_url}/instruments", params={"refresh": refresh})
response.raise_for_status()
return response
async def get_pipette_offset(self) -> Response:
"""GET /calibrations/pipette_offset"""
response = await self.httpx_client.get(url=f"{self.base_url}/calibration/status")
response.raise_for_status()
return response