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)
|