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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564 | class RWSClient:
"""Async HTTP client for the ABB Robot Web Services (RWS) API — RobotWare 6.
Designed to be used as an async context manager, which guarantees
proper HTTP session teardown in all cases.
Args:
host: Controller IP address or hostname (e.g. ``"192.168.125.1"``).
username: RWS username (ABB default: ``"Default User"``).
password: RWS password (ABB default: ``"robotics"``).
port: Controller HTTP port (default: ``80``).
timeout: HTTP timeout in seconds, or ``None`` for no timeout (default: ``None``).
Example:
```python
>>> async with RWSClient(host="192.168.125.1") as client:
... resp = await client.get("rw/rapid/execution")
```
"""
def __init__(
self,
host: str | None = None,
username: str | None = None,
password: str | None = None,
port: int | None = None,
timeout: float | None = None,
) -> None:
self.host = host or get_env_str("RWS_HOST", "192.168.1.10")
self.username = username or get_env_str("RWS_USER", "Default User")
self.password = password or get_env_str("RWS_PASSWORD", "robotics")
self.port = port or get_env_int("RWS_PORT", 80)
self.timeout = (
timeout if timeout is not None else get_env_float_or_none("RWS_TIMEOUT", None)
)
self.base_url = f"http://{self.host}:{self.port}/"
self._http: httpx.AsyncClient | None = None
# ── Lifecycle ───────────────────────────────────────────────────────────
async def aopen(self) -> None:
"""Open the HTTP session. Idempotent: no-op if already open.
Raises:
RWSConnectionError: If the initial connection fails.
Example:
```python
>>> await client.aopen()
```
"""
if self._http is not None:
return
self._http = httpx.AsyncClient(
base_url=self.base_url,
auth=_build_auth(self.username, self.password),
timeout=self.timeout,
follow_redirects=True,
)
logger.debug("RWSClient opened → %s", self.base_url)
async def aclose(self) -> None:
"""Close the HTTP session. Idempotent: no-op if already closed.
Example:
```python
>>> await client.aclose()
```
"""
if self._http is None:
return
await self._http.aclose()
self._http = None
logger.debug("RWSClient closed → %s", self.base_url)
async def __aenter__(self) -> Self:
await self.aopen()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self.aclose()
def __repr__(self) -> str:
state = "open" if self._http is not None else "closed"
return f"RWSClient(host={self.host!r}, timeout={self.timeout}, state={state!r})"
def session_cookie_header(self) -> str:
"""Return the current session cookies as a single ``Cookie`` header value.
ABB Route:
N/A — local session helper, no HTTP call performed.
ABB Constraints:
Meaningful only once the session is open and at least one
request has succeeded (ABBCX is set by the controller after
the first successful digest handshake).
Returns:
Semicolon-separated ``name=value`` cookie pairs, ready to be
used as the ``Cookie`` header of a WebSocket handshake.
Returns an empty string if the session is not open or has no
cookies yet.
Example:
```python
>>> async with RWSClient(host="192.168.125.1") as client:
... await client.get("rw/rapid/execution")
... header = client.session_cookie_header()
... # header == "-http-session-=...; ABBCX=..."
```
"""
if self._http is None:
return ""
return "; ".join(f"{cookie.name}={cookie.value}" for cookie in self._http.cookies.jar)
# ── Internal request with retry ─────────────────────────────────────────
async def _request(
self,
method: str,
path: str,
**kwargs: object,
) -> httpx.Response:
"""Execute an HTTP request with the transport-error retry policy.
Args:
method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, ``"DELETE"``).
path: Path relative to the base URL (e.g. ``"rw/rapid/execution"``).
**kwargs: Additional parameters forwarded to httpx
(``params``, ``data``, ``json``, …).
Returns:
httpx response (status not checked — call ``_raise_for_status``
if needed, though it is already called internally).
Raises:
RuntimeError: If the client is not open.
RWSConnectionError: After retries are exhausted on ConnectError.
RWSTimeoutError: After retries are exhausted on ReadTimeout/PoolTimeout.
RWSAuthenticationError: On HTTP 401.
RWSNotFoundError: On HTTP 404.
RWSHTTPError: On any other HTTP >= 400.
Example:
```python
>>> resp = await client._request(
... "GET",
... "rw/rapid/execution",
... params={"json": "1"},
... )
```
"""
if self._http is None:
raise RuntimeError(
"RWSClient is not open. Use 'async with RWSClient(...) as client' "
"or call await client.aopen() first."
)
# ABB RW6 requires Content-Type: application/x-www-form-urlencoded on
# every POST and PUT, even when the body is empty. httpx does not set
# this header automatically when data={} or no body is provided.
request_kwargs = _prepare_request_kwargs(method, kwargs)
last_exc: Exception | None = None
for attempt in range(_RETRY_MAX_ATTEMPTS):
try:
response = await self._http.request(method, path, **request_kwargs)
_raise_for_status(response, path)
return response
except _RETRYABLE_EXCEPTIONS as exc:
last_exc = exc
if attempt < _RETRY_MAX_ATTEMPTS - 1:
delay = _retry_delay(attempt)
logger.warning(
"RWSClient %s %s → %s (attempt %d/%d, retry in %.2fs)",
method,
path,
type(exc).__name__,
attempt + 1,
_RETRY_MAX_ATTEMPTS,
delay,
)
await asyncio.sleep(delay)
# All retries exhausted
assert last_exc is not None
if isinstance(last_exc, httpx.ConnectError):
raise RWSConnectionError(
f"Connection failed to {self.base_url}: {last_exc}"
) from last_exc
raise RWSTimeoutError(
f"Timeout on {method} {path} after {_RETRY_MAX_ATTEMPTS} attempts"
) from last_exc
# ── Public HTTP methods ──────────────────────────────────────────────────
async def get(self, path: str, **kwargs: object) -> httpx.Response:
"""Send an HTTP GET request to the RWS controller.
Route: ``GET {path}``
Args:
path: Path relative to the base URL (e.g. ``"rw/rapid/execution"``).
**kwargs: Additional httpx parameters (``params``, ``headers``, …).
Returns:
Validated httpx response (status < 400).
Raises:
RWSConnectionError: Network error after retries.
RWSTimeoutError: Timeout after retries.
RWSAuthenticationError: HTTP 401.
RWSNotFoundError: HTTP 404.
RWSHTTPError: Any other HTTP >= 400.
Example:
```python
>>> resp = await client.get("rw/rapid/execution", params={"json": "1"})
```
"""
return await self._request("GET", path, **kwargs)
async def post(self, path: str, **kwargs: object) -> httpx.Response:
"""Send an HTTP POST request to the RWS controller.
Route: ``POST {path}``
Args:
path: Path relative to the base URL (e.g. ``"rw/mastership"``).
**kwargs: Additional httpx parameters (``params``, ``data``, ``json``, …).
Returns:
Validated httpx response (status < 400).
Raises:
RWSConnectionError: Network error after retries.
RWSTimeoutError: Timeout after retries.
RWSAuthenticationError: HTTP 401.
RWSNotFoundError: HTTP 404.
RWSHTTPError: Any other HTTP >= 400.
Example:
```python
>>> await client.post("rw/mastership", params={"action": "request"})
```
"""
return await self._request("POST", path, **kwargs)
async def put(self, path: str, **kwargs: object) -> httpx.Response:
"""Send an HTTP PUT request to the RWS controller.
Route: ``PUT {path}`` — typically used to write a RAPID variable.
Args:
path: Path relative to the base URL.
**kwargs: Additional httpx parameters (``data``, …).
Returns:
Validated httpx response (status < 400).
Raises:
RWSConnectionError: Network error after retries.
RWSTimeoutError: Timeout after retries.
RWSAuthenticationError: HTTP 401.
RWSNotFoundError: HTTP 404.
RWSHTTPError: Any other HTTP >= 400.
Example:
```python
>>> await client.put(
... "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR",
... data={"value": "42"},
... )
```
"""
return await self._request("PUT", path, **kwargs)
async def delete(self, path: str, **kwargs: object) -> httpx.Response:
"""Send an HTTP DELETE request to the RWS controller.
Route: ``DELETE {path}`` — typically used for fileservice or elog resources.
Args:
path: Path relative to the base URL.
**kwargs: Additional httpx parameters.
Returns:
Validated httpx response (status < 400).
Raises:
RWSConnectionError: Network error after retries.
RWSTimeoutError: Timeout after retries.
RWSAuthenticationError: HTTP 401.
RWSNotFoundError: HTTP 404.
RWSHTTPError: Any other HTTP >= 400.
Example:
```python
>>> await client.delete("fileservice/$HOME/old_backup.tar.gz")
```
"""
return await self._request("DELETE", path, **kwargs)
async def head(
self,
path: str,
**kwargs: object,
) -> httpx.Response:
"""Send an HTTP HEAD request to the RWS controller.
Route: ``HEAD {path}``
Args:
path: Path relative to the base URL.
**kwargs: Additional parameters forwarded to httpx.
Returns:
Raw HTTP response (headers only, no body).
Raises:
RWSAuthenticationError: On HTTP 401.
RWSNotFoundError: On HTTP 404.
RWSHTTPError: On any other HTTP >= 400.
RWSConnectionError: If the controller is unreachable.
RWSTimeoutError: If the request exceeds the timeout.
Example:
```python
>>> resp = await client.head("fileservice/$HOME/myfile.txt")
```
"""
return await self._request("HEAD", path, **kwargs)
async def options(
self,
path: str,
**kwargs: object,
) -> httpx.Response:
"""Send an HTTP OPTIONS request to the RWS controller.
Route: ``OPTIONS {path}``
Args:
path: Path relative to the base URL.
**kwargs: Additional parameters forwarded to httpx.
Returns:
Raw HTTP response.
Raises:
RWSAuthenticationError: On HTTP 401.
RWSNotFoundError: On HTTP 404.
RWSHTTPError: On any other HTTP >= 400.
RWSConnectionError: If the controller is unreachable.
RWSTimeoutError: If the request exceeds the timeout.
Example:
```python
>>> resp = await client.options("ctrl/network/route/add")
```
"""
return await self._request("OPTIONS", path, **kwargs)
|