Client

abb_rws_client_python_rw6.core.client

HTTP session management for an ABB RWS controller (RobotWare 6).

Author: Clement RACINET

Module responsibilities: - Create and maintain an httpx.AsyncClient configured for RWS - Handle ABB HTTP Digest authentication - Maintain the ABBCX session cookie - Expose low-level HTTP methods (get, put, post, delete, head, options) used by the rws/ and highlevel/ modules - Implement the retry policy on transport errors - Provide RWSClientSync, a synchronous wrapper with no logic duplication

Retry policy (documented here, implemented in _request)::

- Triggers: ConnectError, ConnectTimeout, ReadTimeout, PoolTimeout only.
  HTTP errors (4xx, 5xx) are never retried.
- Attempts: 3 total (1 initial attempt + 2 retries)
- Delay: exponential with ±10% jitter
  base * 2^attempt + jitter  →  ~0.5s, ~1s, ~2s

ABBCX cookie management::

httpx.AsyncClient maintains this cookie natively via its cookiejar.
On expiry (ABB timeout ~10 min), the controller responds with 401
and httpx.DigestAuth automatically restarts the handshake.

RWSClientSync::

Synchronous wrapper based on httpx.Client (httpx native sync).
Same retry/auth logic, no anyio dependency at runtime.
All methods are synchronous (no async def).

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.

Parameters:
  • host (str | None, default: None ) –

    Controller IP address or hostname (e.g. "192.168.125.1").

  • username (str | None, default: None ) –

    RWS username (ABB default: "Default User").

  • password (str | None, default: None ) –

    RWS password (ABB default: "robotics").

  • port (int | None, default: None ) –

    Controller HTTP port (default: 80).

  • timeout (float | None, default: None ) –

    HTTP timeout in seconds, or None for no timeout (default: None).

Example
>>> async with RWSClient(host="192.168.125.1") as client:
...     resp = await client.get("rw/rapid/execution")
Source code in abb_rws_client_python_rw6/core/client.py
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)

aclose() async

Close the HTTP session. Idempotent: no-op if already closed.

Example
>>> await client.aclose()
Source code in abb_rws_client_python_rw6/core/client.py
260
261
262
263
264
265
266
267
268
269
270
271
272
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)

aopen() async

Open the HTTP session. Idempotent: no-op if already open.

Raises:
Example
>>> await client.aopen()
Source code in abb_rws_client_python_rw6/core/client.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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)

delete(path, **kwargs) async

Send an HTTP DELETE request to the RWS controller.

Route: DELETE {path} — typically used for fileservice or elog resources.

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional httpx parameters.

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> await client.delete("fileservice/$HOME/old_backup.tar.gz")
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

get(path, **kwargs) async

Send an HTTP GET request to the RWS controller.

Route: GET {path}

Parameters:
  • path (str) –

    Path relative to the base URL (e.g. "rw/rapid/execution").

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (params, headers, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> resp = await client.get("rw/rapid/execution", params={"json": "1"})
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

head(path, **kwargs) async

Send an HTTP HEAD request to the RWS controller.

Route: HEAD {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional parameters forwarded to httpx.

Returns:
  • Response –

    Raw HTTP response (headers only, no body).

Raises:
Example
>>> resp = await client.head("fileservice/$HOME/myfile.txt")
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

options(path, **kwargs) async

Send an HTTP OPTIONS request to the RWS controller.

Route: OPTIONS {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional parameters forwarded to httpx.

Returns:
  • Response –

    Raw HTTP response.

Raises:
Example
>>> resp = await client.options("ctrl/network/route/add")
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

post(path, **kwargs) async

Send an HTTP POST request to the RWS controller.

Route: POST {path}

Parameters:
  • path (str) –

    Path relative to the base URL (e.g. "rw/mastership").

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (params, data, json, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> await client.post("rw/mastership", params={"action": "request"})
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

put(path, **kwargs) async

Send an HTTP PUT request to the RWS controller.

Route: PUT {path} — typically used to write a RAPID variable.

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (data, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> await client.put(
...     "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR",
...     data={"value": "42"},
... )
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

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:
  • str –

    Semicolon-separated name=value cookie pairs, ready to be

  • str –

    used as the Cookie header of a WebSocket handshake.

  • str –

    Returns an empty string if the session is not open or has no

  • str –

    cookies yet.

Example
>>> 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=..."
Source code in abb_rws_client_python_rw6/core/client.py
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
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)

RWSClientSync

Synchronous HTTP client for the ABB RWS API — RobotWare 6.

Synchronous wrapper around RWSClient, based on httpx.Client natively. Same authentication policy (DigestAuth), same retry logic, same error handling. No anyio or asyncio dependency at runtime.

Designed to be used as a synchronous context manager.

Parameters:
  • host (str | None, default: None ) –

    Controller IP address or hostname (e.g. "192.168.125.1"). Reads RWS_HOST from environment if None.

  • username (str | None, default: None ) –

    RWS username (ABB default: "Default User"). Reads RWS_USER from environment if None.

  • password (str | None, default: None ) –

    RWS password (ABB default: "robotics"). Reads RWS_PASSWORD from environment if None.

  • port (int | None, default: None ) –

    HTTP port (default: 80). Reads RWS_PORT from environment if None.

  • timeout (float | None, default: None ) –

    HTTP timeout in seconds, or None for no timeout (default: None). Reads RWS_TIMEOUT from environment if not provided explicitly.

Example
>>> with RWSClientSync(host="192.168.125.1") as client:
...     resp = client.get("rw/rapid/execution")
Source code in abb_rws_client_python_rw6/core/client.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
class RWSClientSync:
    """Synchronous HTTP client for the ABB RWS API — RobotWare 6.

    Synchronous wrapper around ``RWSClient``, based on ``httpx.Client`` natively.
    Same authentication policy (DigestAuth), same retry logic, same error handling.
    No ``anyio`` or ``asyncio`` dependency at runtime.

    Designed to be used as a synchronous context manager.

    Args:
        host: Controller IP address or hostname (e.g. ``"192.168.125.1"``).
            Reads ``RWS_HOST`` from environment if ``None``.
        username: RWS username (ABB default: ``"Default User"``).
            Reads ``RWS_USER`` from environment if ``None``.
        password: RWS password (ABB default: ``"robotics"``).
            Reads ``RWS_PASSWORD`` from environment if ``None``.
        port: HTTP port (default: ``80``).
            Reads ``RWS_PORT`` from environment if ``None``.
        timeout: HTTP timeout in seconds, or ``None`` for no timeout
            (default: ``None``). Reads ``RWS_TIMEOUT`` from environment
            if not provided explicitly.

    Example:
        ```python
        >>> with RWSClientSync(host="192.168.125.1") as client:
        ...     resp = 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.125.1")
        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.Client | None = None

    # ── Lifecycle ───────────────────────────────────────────────────────────

    def open(self) -> None:
        """Open the HTTP session. Idempotent: no-op if already open.

        Example:
            ```python
            >>> client.open()
            ```
        """
        if self._http is not None:
            return
        self._http = httpx.Client(
            base_url=self.base_url,
            auth=_build_auth(self.username, self.password),
            timeout=self.timeout,
            follow_redirects=True,
        )
        logger.debug("RWSClientSync opened → %s", self.base_url)

    def close(self) -> None:
        """Close the HTTP session. Idempotent: no-op if already closed.

        Example:
            ```python
            >>> client.close()
            ```
        """
        if self._http is None:
            return
        self._http.close()
        self._http = None
        logger.debug("RWSClientSync closed → %s", self.base_url)

    def __enter__(self) -> Self:
        self.open()
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        self.close()

    def __repr__(self) -> str:
        state = "open" if self._http is not None else "closed"
        return f"RWSClientSync(host={self.host!r}, state={state!r})"

    # ── Internal request with retry ─────────────────────────────────────────

    def _request(self, method: str, path: str, **kwargs: object) -> httpx.Response:
        """Execute a synchronous HTTP request with the transport-error retry policy.

        Args:
            method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, ``"DELETE"``).
            path: Path relative to the base URL.
            **kwargs: Additional parameters forwarded to httpx.

        Returns:
            Validated httpx response (status < 400).

        Raises:
            RuntimeError: If the client is not open.
            RWSConnectionError: After retries are exhausted on ConnectError.
            RWSTimeoutError: After retries are exhausted on timeout errors.
            RWSAuthenticationError: On HTTP 401.
            RWSNotFoundError: On HTTP 404.
            RWSHTTPError: On any other HTTP >= 400.

        Example:
            ```python
            >>> resp = client._request(
            ...     "GET",
            ...     "rw/rapid/execution",
            ...     params={"json": "1"},
            ... )
            ```
        """
        if self._http is None:
            raise RuntimeError(
                "RWSClientSync is not open. Use 'with RWSClientSync(...) as client' "
                "or call client.open() 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 = 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(
                        "RWSClientSync %s %s → %s (attempt %d/%d, retry in %.2fs)",
                        method,
                        path,
                        type(exc).__name__,
                        attempt + 1,
                        _RETRY_MAX_ATTEMPTS,
                        delay,
                    )
                    time.sleep(delay)
        # All retries exhausted
        assert last_exc is not None
        if isinstance(last_exc, httpx.ConnectError):
            raise RWSConnectionError(f"Cannot connect 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 ──────────────────────────────────────────────────

    def get(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous 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``, …).

        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 = client.get("rw/rapid/execution", params={"json": "1"})
            ```
        """
        return self._request("GET", path, **kwargs)

    def post(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous HTTP POST request to the RWS controller.

        Route: ``POST {path}``

        Args:
            path: Path relative to the base URL.
            **kwargs: Additional httpx parameters (``params``, ``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
            >>> client.post("rw/mastership", params={"action": "request"})
            ```
        """
        return self._request("POST", path, **kwargs)

    def put(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous 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
            >>> client.put(
            ...     "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR",
            ...     data={"value": "42"},
            ... )
            ```
        """
        return self._request("PUT", path, **kwargs)

    def delete(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous HTTP DELETE request to the RWS controller.

        Route: ``DELETE {path}``

        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
            >>> client.delete("fileservice/$HOME/old_backup.tar.gz")
            ```
        """
        return self._request("DELETE", path, **kwargs)

    def head(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous 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 = client.head("fileservice/$HOME/myfile.txt")
            ```
        """
        return self._request("HEAD", path, **kwargs)

    def options(self, path: str, **kwargs: object) -> httpx.Response:
        """Send a synchronous 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 = client.options("ctrl/network/route/add")
            ```
        """
        return self._request("OPTIONS", path, **kwargs)

close()

Close the HTTP session. Idempotent: no-op if already closed.

Example
>>> client.close()
Source code in abb_rws_client_python_rw6/core/client.py
639
640
641
642
643
644
645
646
647
648
649
650
651
def close(self) -> None:
    """Close the HTTP session. Idempotent: no-op if already closed.

    Example:
        ```python
        >>> client.close()
        ```
    """
    if self._http is None:
        return
    self._http.close()
    self._http = None
    logger.debug("RWSClientSync closed → %s", self.base_url)

delete(path, **kwargs)

Send a synchronous HTTP DELETE request to the RWS controller.

Route: DELETE {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional httpx parameters.

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> client.delete("fileservice/$HOME/old_backup.tar.gz")
Source code in abb_rws_client_python_rw6/core/client.py
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def delete(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous HTTP DELETE request to the RWS controller.

    Route: ``DELETE {path}``

    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
        >>> client.delete("fileservice/$HOME/old_backup.tar.gz")
        ```
    """
    return self._request("DELETE", path, **kwargs)

get(path, **kwargs)

Send a synchronous HTTP GET request to the RWS controller.

Route: GET {path}

Parameters:
  • path (str) –

    Path relative to the base URL (e.g. "rw/rapid/execution").

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (params, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> resp = client.get("rw/rapid/execution", params={"json": "1"})
Source code in abb_rws_client_python_rw6/core/client.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def get(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous 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``, …).

    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 = client.get("rw/rapid/execution", params={"json": "1"})
        ```
    """
    return self._request("GET", path, **kwargs)

head(path, **kwargs)

Send a synchronous HTTP HEAD request to the RWS controller.

Route: HEAD {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional parameters forwarded to httpx.

Returns:
  • Response –

    Raw HTTP response (headers only, no body).

Raises:
Example
>>> resp = client.head("fileservice/$HOME/myfile.txt")
Source code in abb_rws_client_python_rw6/core/client.py
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def head(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous 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 = client.head("fileservice/$HOME/myfile.txt")
        ```
    """
    return self._request("HEAD", path, **kwargs)

open()

Open the HTTP session. Idempotent: no-op if already open.

Example
>>> client.open()
Source code in abb_rws_client_python_rw6/core/client.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def open(self) -> None:
    """Open the HTTP session. Idempotent: no-op if already open.

    Example:
        ```python
        >>> client.open()
        ```
    """
    if self._http is not None:
        return
    self._http = httpx.Client(
        base_url=self.base_url,
        auth=_build_auth(self.username, self.password),
        timeout=self.timeout,
        follow_redirects=True,
    )
    logger.debug("RWSClientSync opened → %s", self.base_url)

options(path, **kwargs)

Send a synchronous HTTP OPTIONS request to the RWS controller.

Route: OPTIONS {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional parameters forwarded to httpx.

Returns:
  • Response –

    Raw HTTP response.

Raises:
Example
>>> resp = client.options("ctrl/network/route/add")
Source code in abb_rws_client_python_rw6/core/client.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def options(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous 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 = client.options("ctrl/network/route/add")
        ```
    """
    return self._request("OPTIONS", path, **kwargs)

post(path, **kwargs)

Send a synchronous HTTP POST request to the RWS controller.

Route: POST {path}

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (params, data, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> client.post("rw/mastership", params={"action": "request"})
Source code in abb_rws_client_python_rw6/core/client.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def post(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous HTTP POST request to the RWS controller.

    Route: ``POST {path}``

    Args:
        path: Path relative to the base URL.
        **kwargs: Additional httpx parameters (``params``, ``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
        >>> client.post("rw/mastership", params={"action": "request"})
        ```
    """
    return self._request("POST", path, **kwargs)

put(path, **kwargs)

Send a synchronous HTTP PUT request to the RWS controller.

Route: PUT {path} — typically used to write a RAPID variable.

Parameters:
  • path (str) –

    Path relative to the base URL.

  • **kwargs (object, default: {} ) –

    Additional httpx parameters (data, …).

Returns:
  • Response –

    Validated httpx response (status < 400).

Raises:
Example
>>> client.put(
...     "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR",
...     data={"value": "42"},
... )
Source code in abb_rws_client_python_rw6/core/client.py
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def put(self, path: str, **kwargs: object) -> httpx.Response:
    """Send a synchronous 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
        >>> client.put(
        ...     "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR",
        ...     data={"value": "42"},
        ... )
        ```
    """
    return self._request("PUT", path, **kwargs)