Subscription

abb_rws_client_python_rw6.highlevel.subscription

High-level RWS subscription management for ABB RobotWare 6.

Author: Clement RACINET

Wraps the ABB RWS Subscription Service (POST/PUT/DELETE /subscription) and the WebSocket event stream behind a resource-oriented API: the caller declares a list of SubscribedResource (name + RWS resource URI + ABB priority), and gets back logical (name, value) events instead of raw XML.

ABB RWS subscription flow (confirmed from official ABB doc, "Subscriptions" section): 1. POST /subscription with a form body: resources= 1=&1-p= 2=&2-p= ... Response: HTTP 201, body = initial events for each resource, plus a Location header = the WebSocket URL (ws://host:port/poll/<id>). 2. Open a WebSocket on that URL, subprotocol robapi2_subscription, reusing the RWS session cookies (-http-session-, ABBCX). 3. Each subscribed-resource change is pushed as an XML/XHTML event. 4. DELETE /subscription/{group-id} to tear down the group.

ABB priority semantics (confirmed, ABB doc "Subscriptions"): "0" = Low (delay <= 5s) "1" = Medium (delay <= 200ms) "2" = High (as soon as possible; PERS RAPID variables and IO signals only; max 64 High-priority resources across the controller)

SubscribedResource dataclass

One RWS resource to watch within a subscription group.

Parameters:
  • name (str) –

    Caller-chosen logical identifier for this resource. Used only client-side to route incoming events back to the caller; never sent to ABB.

  • resource_uri (str) –

    Full ABB RWS resource URI to subscribe on, e.g. /rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR;value.

  • priority (SubscriptionPriority, default: '1' ) –

    ABB subscription priority. "0"=Low, "1"=Medium, "2"=High (PERS RAPID variables and IO signals only).

Example
>>> SubscribedResource(
...     name="watched_value",
...     resource_uri="/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value",
...     priority="1",
... )
Source code in abb_rws_client_python_rw6/highlevel/subscription.py
 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
@dataclass(frozen=True)
class SubscribedResource:
    """One RWS resource to watch within a subscription group.

    Args:
        name: Caller-chosen logical identifier for this resource. Used only
            client-side to route incoming events back to the caller; never
            sent to ABB.
        resource_uri: Full ABB RWS resource URI to subscribe on, e.g.
            ``/rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR;value``.
        priority: ABB subscription priority. ``"0"``=Low, ``"1"``=Medium,
            ``"2"``=High (PERS RAPID variables and IO signals only).

    Example:
        ```python
        >>> SubscribedResource(
        ...     name="watched_value",
        ...     resource_uri="/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value",
        ...     priority="1",
        ... )
        ```
    """

    name: str
    resource_uri: str
    priority: SubscriptionPriority = "1"

SubscriptionHandle dataclass

Result of a successfully created ABB RWS subscription group.

Parameters:
  • group_id (str) –

    ABB subscription group identifier (from the WebSocket URL path, e.g. "9" in ws://host/poll/9).

  • ws_url (str) –

    WebSocket URL to open for this subscription group, normalized so that 127.0.0.1/localhost (as sometimes returned by ABB) is replaced by the actual controller host.

  • cookie_header (str) –

    Session cookie header to send during the WebSocket handshake (-http-session-=...; ABBCX=...).

  • resources (tuple[SubscribedResource, ...]) –

    The resources this group was created with, kept to resolve incoming events back to their logical name.

  • initial_values (dict[str, str]) –

    Values returned by ABB in the POST /subscription response body itself (one entry per resource whose initial state ABB included), keyed by SubscribedResource.name.

Source code in abb_rws_client_python_rw6/highlevel/subscription.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@dataclass(frozen=True)
class SubscriptionHandle:
    """Result of a successfully created ABB RWS subscription group.

    Args:
        group_id: ABB subscription group identifier (from the WebSocket
            URL path, e.g. ``"9"`` in ``ws://host/poll/9``).
        ws_url: WebSocket URL to open for this subscription group,
            normalized so that ``127.0.0.1``/``localhost`` (as sometimes
            returned by ABB) is replaced by the actual controller host.
        cookie_header: Session cookie header to send during the WebSocket
            handshake (``-http-session-=...; ABBCX=...``).
        resources: The resources this group was created with, kept to
            resolve incoming events back to their logical ``name``.
        initial_values: Values returned by ABB in the ``POST /subscription``
            response body itself (one entry per resource whose initial
            state ABB included), keyed by ``SubscribedResource.name``.
    """

    group_id: str
    ws_url: str
    cookie_header: str
    resources: tuple[SubscribedResource, ...]
    initial_values: dict[str, str]

build_rapid_pers_resource_uri(task, module, variable)

Build the ABB RWS subscription resource URI for a RAPID PERS variable.

Route: N/A — local string helper, no HTTP call performed.

The variable must be declared PERS in RAPID.

Subscriptions on non-persistent (VAR) data are not supported by ABB (confirmed by ABB doc: "Subscribe on RAPID persistent variable").

Parameters:
  • task (str) –

    RAPID task name, e.g. "T_ROB1".

  • module (str) –

    RAPID module name, e.g. "Subscription".

  • variable (str) –

    RAPID PERS variable name, e.g. "WatchedValue".

Returns:
  • str –

    Resource URI suitable for SubscribedResource.resource_uri.

Example
>>> build_rapid_pers_resource_uri("T_ROB1", "Subscription", "WatchedValue")
'/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value'
Source code in abb_rws_client_python_rw6/highlevel/subscription.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def build_rapid_pers_resource_uri(task: str, module: str, variable: str) -> str:
    """Build the ABB RWS subscription resource URI for a RAPID PERS variable.

    Route: N/A — local string helper, no HTTP call performed.

    ABB constraints: The variable must be declared ``PERS`` in RAPID.
        Subscriptions on non-persistent (``VAR``) data are not supported by
        ABB (confirmed by ABB doc: "Subscribe on RAPID persistent variable").

    Args:
        task: RAPID task name, e.g. ``"T_ROB1"``.
        module: RAPID module name, e.g. ``"Subscription"``.
        variable: RAPID PERS variable name, e.g. ``"WatchedValue"``.

    Returns:
        Resource URI suitable for ``SubscribedResource.resource_uri``.

    Example:
        ```python
        >>> build_rapid_pers_resource_uri("T_ROB1", "Subscription", "WatchedValue")
        '/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value'
        ```
    """
    return f"{_SYMBOL_DATA_PREFIX}RAPID/{task}/{module}/{variable};value"

create_subscription(client, resources) async

Create an ABB RWS subscription group for one or more resources.

Route: POST /subscription

ABB constraints
  • Max 1000 total resources per client (low/medium priority).
  • Max 64 resources at High priority ("2"), RAPID PERS variables and IO signals only.
  • Max 2 subscription groups per client.
  • The response body contains the initial event state for the subscribed resources (parsed here into initial_values); the Location header carries the WebSocket URL.
Parameters:
Returns:
Raises:
  • ValueError –

    If resources is empty, exceeds ABB's resource-count limits, or if ABB's response cannot be parsed (missing WebSocket URL / group id).

  • RWSAuthenticationError –

    On HTTP 401.

  • RWSHTTPError –

    On any other HTTP >= 400 (e.g. bad resource URI).

Example
>>> handle = await create_subscription(
...     client,
...     [SubscribedResource(
...         "watched",
...         "/rw/rapid/symbol/data/RAPID/T_ROB1/M/x;value",
...         "1",
...     )],
... )
Source code in abb_rws_client_python_rw6/highlevel/subscription.py
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
async def create_subscription(
    client: RWSClient,
    resources: Sequence[SubscribedResource],
) -> SubscriptionHandle:
    """Create an ABB RWS subscription group for one or more resources.

    Route: ``POST /subscription``

    ABB constraints:
        - Max 1000 total resources per client (low/medium priority).
        - Max 64 resources at High priority ("2"), RAPID PERS variables and
          IO signals only.
        - Max 2 subscription groups per client.
        - The response body contains the initial event state for the
          subscribed resources (parsed here into ``initial_values``); the
          ``Location`` header carries the WebSocket URL.

    Args:
        client: Open RWSClient instance.
        resources: Resources to subscribe to (1 to N).

    Returns:
        SubscriptionHandle with the group id, normalized WebSocket URL,
        session cookie header, and any initial values ABB returned inline.

    Raises:
        ValueError: If ``resources`` is empty, exceeds ABB's resource-count
            limits, or if ABB's response cannot be parsed (missing
            WebSocket URL / group id).
        RWSAuthenticationError: On HTTP 401.
        RWSHTTPError: On any other HTTP >= 400 (e.g. bad resource URI).

    Example:
        ```python
        >>> handle = await create_subscription(
        ...     client,
        ...     [SubscribedResource(
        ...         "watched",
        ...         "/rw/rapid/symbol/data/RAPID/T_ROB1/M/x;value",
        ...         "1",
        ...     )],
        ... )
        ```
    """
    # FIXME(Clement RACINET): The multi-resource POST payload built by
    # _build_subscription_payload (single "resources=<total>" key + per-index
    # "<i>"/"<i>-p" pairs) is inferred from ABB's documentation, which is
    # internally inconsistent on this exact point (its own 2-resource sample
    # repeats the "resources" key with two different values instead of
    # sending the total once). This has ONLY been confirmed on real RW6
    # hardware for N=1 resource (examples/06). MUST be re-tested on a real
    # controller with N>=2 resources (including mixed priorities) before
    # this is considered production-ready. If ABB rejects the payload, or
    # returns an unexpected initial-event XML shape for N>=2, fix
    # _build_subscription_payload and/or _parse_events accordingly — do not
    # patch around it blindly.
    _validate_resources(resources)
    payload = _build_subscription_payload(resources)
    lookup = _build_resource_lookup(resources)

    logger.info("Creating subscription on %d resource(s)", len(resources))
    response = await client.post("/subscription", data=payload)

    headers = dict(response.headers)
    ws_url_raw, group_id = _extract_ws_url_and_group_id(response.text, headers)
    ws_url = _normalize_ws_url(ws_url_raw, client)
    cookie_header = client.session_cookie_header()
    initial_values = _parse_events(response.text, lookup)

    logger.info("Subscription created: group_id=%s, ws_url=%s", group_id, ws_url)

    return SubscriptionHandle(
        group_id=group_id,
        ws_url=ws_url,
        cookie_header=cookie_header,
        resources=tuple(resources),
        initial_values=initial_values,
    )

delete_subscription(client, handle) async

Delete an ABB RWS subscription group.

Route: DELETE /subscription/{group-id}

ABB constraints: Not supported in bootserver mode.

Parameters:
Raises:
Example
>>> await delete_subscription(client, handle)
Source code in abb_rws_client_python_rw6/highlevel/subscription.py
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
async def delete_subscription(client: RWSClient, handle: SubscriptionHandle) -> None:
    """Delete an ABB RWS subscription group.

    Route: ``DELETE /subscription/{group-id}``

    ABB constraints: Not supported in bootserver mode.

    Args:
        client: Open RWSClient instance.
        handle: Handle returned by ``create_subscription``.

    Raises:
        RWSAuthenticationError: On HTTP 401.
        RWSNotFoundError: If the group was already removed (e.g. session
            expired server-side).
        RWSHTTPError: On any other HTTP >= 400.

    Example:
        ```python
        >>> await delete_subscription(client, handle)
        ```
    """
    logger.info("Deleting subscription group_id=%s", handle.group_id)
    await unsubscribe_or_remove_the_subscription_group_resources(client, handle.group_id)
    logger.info("Subscription group_id=%s deleted", handle.group_id)

watch_resources(client, resources, *, yield_initial_values=True) async

Subscribe to resources and yield (name, value) events as they occur.

Route: POST /subscription then WebSocket ws://.../poll/{group-id}, DELETE /subscription/{group-id} on exit.

ABB constraints
  • WebSocket subprotocol must be robapi2_subscription.
  • The WebSocket handshake must carry the same session cookies (-http-session-, ABBCX) as the HTTP session.
  • permessage-deflate must be disabled (compression=None): some RW6 controllers reject the negotiated extension with HTTP 400.
  • The subscription group is always deleted on exit (normal completion, exception, or generator close/cancellation), via try/finally.
Parameters:
  • client (RWSClient) –

    Open RWSClient instance.

  • resources (Sequence[SubscribedResource]) –

    Resources to subscribe to (1 to N). See SubscribedResource and build_rapid_pers_resource_uri.

  • yield_initial_values (bool, default: True ) –

    If True (default), yield the initial values ABB returns inline in the POST /subscription response body before entering the WebSocket loop. If False, only events received over the WebSocket are yielded.

Yields:
  • AsyncGenerator[tuple[str, str], None] –

    (name, value) tuples, where name is the

  • AsyncGenerator[tuple[str, str], None] –

    SubscribedResource.name the event belongs to, and value is

  • AsyncGenerator[tuple[str, str], None] –

    the raw string value as sent by ABB.

Raises:
  • ValueError –

    Invalid resource list, or ABB response could not be parsed (see create_subscription).

  • RWSAuthenticationError –

    On HTTP 401 during subscription setup.

  • RWSHTTPError –

    On any other HTTP >= 400 during subscription setup.

  • OSError –

    If the WebSocket connection cannot be established.

Example
>>> resources = [
...     SubscribedResource("a", build_rapid_pers_resource_uri("T_ROB1", "M", "X"), "1"),
...     SubscribedResource("b", build_rapid_pers_resource_uri("T_ROB1", "M", "Y"), "1"),
... ]
>>> async for name, value in watch_resources(client, resources):
...     print(name, value)
Source code in abb_rws_client_python_rw6/highlevel/subscription.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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
async def watch_resources(
    client: RWSClient,
    resources: Sequence[SubscribedResource],
    *,
    yield_initial_values: bool = True,
) -> AsyncGenerator[tuple[str, str], None]:
    """Subscribe to resources and yield ``(name, value)`` events as they occur.

    Route: ``POST /subscription`` then WebSocket ``ws://.../poll/{group-id}``,
    ``DELETE /subscription/{group-id}`` on exit.

    ABB constraints:
        - WebSocket subprotocol must be ``robapi2_subscription``.
        - The WebSocket handshake must carry the same session cookies
          (``-http-session-``, ``ABBCX``) as the HTTP session.
        - permessage-deflate must be disabled (``compression=None``): some
          RW6 controllers reject the negotiated extension with HTTP 400.
        - The subscription group is always deleted on exit (normal
          completion, exception, or generator close/cancellation), via
          ``try/finally``.

    Args:
        client: Open RWSClient instance.
        resources: Resources to subscribe to (1 to N). See
            ``SubscribedResource`` and ``build_rapid_pers_resource_uri``.
        yield_initial_values: If ``True`` (default), yield the initial
            values ABB returns inline in the ``POST /subscription``
            response body before entering the WebSocket loop. If ``False``,
            only events received over the WebSocket are yielded.

    Yields:
        ``(name, value)`` tuples, where ``name`` is the
        ``SubscribedResource.name`` the event belongs to, and ``value`` is
        the raw string value as sent by ABB.

    Raises:
        ValueError: Invalid resource list, or ABB response could not be
            parsed (see ``create_subscription``).
        RWSAuthenticationError: On HTTP 401 during subscription setup.
        RWSHTTPError: On any other HTTP >= 400 during subscription setup.
        OSError: If the WebSocket connection cannot be established.

    Example:
        ```python
        >>> resources = [
        ...     SubscribedResource("a", build_rapid_pers_resource_uri("T_ROB1", "M", "X"), "1"),
        ...     SubscribedResource("b", build_rapid_pers_resource_uri("T_ROB1", "M", "Y"), "1"),
        ... ]
        >>> async for name, value in watch_resources(client, resources):
        ...     print(name, value)
        ```
    """
    lookup = _build_resource_lookup(resources)
    handle = await create_subscription(client, resources)

    try:
        if yield_initial_values:
            for name, value in handle.initial_values.items():
                yield name, value

        # ABB RW6 WebSocket notes (confirmed on real hardware, examples/06):
        # - subprotocol MUST be "robapi2_subscription", NOT "rws_subscription"
        #   (some RW6 controllers reject the latter with
        #   "Unsupported Sec-WebSocket-Protocol").
        # - compression=None avoids Sec-WebSocket-Extensions negotiation,
        #   which some RW6 controllers reject with HTTP 400.
        # - ping_interval=None: ABB documents its own application-level
        #   ping/pong; the websockets library's built-in ping is disabled
        #   to avoid sending a frame ABB does not expect.
        async with websockets.asyncio.client.connect(
            handle.ws_url,
            additional_headers={"Cookie": handle.cookie_header},
            subprotocols=_RWS_SUBPROTOCOLS,
            open_timeout=10.0,
            ping_interval=None,
            compression=None,
        ) as websocket:
            logger.info("WebSocket connected: %s", handle.ws_url)

            async for message in websocket:
                text = str(message)
                logger.debug("WebSocket message: %s", text)

                for name, value in _parse_events(text, lookup).items():
                    yield name, value

    finally:
        try:
            await delete_subscription(client, handle)
        except Exception as exc:
            # Teardown must never raise: a failed DELETE here (e.g. session
            # already expired) must not mask the original error, if any.
            logger.warning("Could not delete subscription group_id=%s: %s", handle.group_id, exc)