Coverage for abb_rws_client_python_rw6/highlevel/execution.py: 98%
41 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
1# abb_rws_client/highlevel/execution.py
2"""High-level RAPID execution control for ABB RWS RobotWare 6.
4Author: Clement RACINET
6Composed operations built exclusively from atomic ``rws/`` functions.
7No HTTP calls are made directly in this module.
9All functions are async and require an open ``RWSClient`` instance.
10"""
12from __future__ import annotations
14import asyncio
15import re
17import httpx
19from abb_rws_client_python_rw6.core.client import RWSClient
20from abb_rws_client_python_rw6.core.logger import get_logger
21from abb_rws_client_python_rw6.rws.rapid.execution import (
22 get_rapid_execution_state,
23 reset_rapid_program_pointer_to_main,
24 start_rapid_execution,
25 stop_rapid_execution,
26)
28logger = get_logger(__name__)
30# ---------------------------------------------------------------------------
31# Internal helpers
32# ---------------------------------------------------------------------------
34_EXEC_STATE_KEY = "ctrlexecstate"
35_RUNNING_VALUE = "running"
38def _parse_exec_state(response: httpx.Response) -> str:
39 """Extract ``ctrlexecstate`` from a RAPID execution state response.
41 ABB RWS returns either XML/HTML (default) or JSON depending on the
42 ``Accept`` header sent by the client. Both formats are handled.
44 Args:
45 response: Raw HTTP response from ``get_rapid_execution_state``.
47 Returns:
48 The execution state string, e.g. ``"running"`` or ``"stopped"``.
50 Raises:
51 ValueError: If the state cannot be extracted from the response body.
53 Example:
54 ```python
55 resp = await get_rapid_execution_state(client)
56 state = _parse_exec_state(resp)
57 # state == "stopped"
58 ```
59 """
60 # JSON path: {"state": [{"ctrlexecstate": "stopped", ...}]}
61 try:
62 data = response.json()
63 states = data.get("state", [])
64 if states and _EXEC_STATE_KEY in states[0]: 64 ↛ 70line 64 didn't jump to line 70 because the condition on line 64 was always true
65 return str(states[0][_EXEC_STATE_KEY])
66 except Exception:
67 pass
69 # XML / HTML path: <span class="ctrlexecstate">stopped</span>
70 match = re.search(
71 r'class=["\']ctrlexecstate["\'][^>]*>([^<]+)<',
72 response.text,
73 )
74 if match:
75 return match.group(1).strip()
77 raise ValueError(f"Cannot parse ctrlexecstate from response: {response.text[:200]}")
80# ---------------------------------------------------------------------------
81# Execution state
82# ---------------------------------------------------------------------------
85async def is_running(client: RWSClient) -> bool:
86 """Check whether RAPID execution is currently running.
88 Wraps ``get_rapid_execution_state`` and parses the ``ctrlexecstate``
89 field from the response.
91 Route (delegated): ``GET /rw/rapid/execution``
93 Args:
94 client: Open ``RWSClient`` instance.
96 Returns:
97 ``True`` if the controller execution state is ``"running"``,
98 ``False`` otherwise (``"stopped"``, ``"idle"``, etc.).
100 Raises:
101 RWSAuthenticationError: On HTTP 401.
102 RWSNotFoundError: On HTTP 404.
103 RWSHTTPError: On any other HTTP >= 400.
104 ValueError: If the execution state cannot be parsed.
106 Example:
107 ```python
108 async with RWSClient(host="192.168.125.1") as client:
109 running = await is_running(client)
110 print("Running:", running)
111 ```
112 """
113 response = await get_rapid_execution_state(client)
114 return _parse_exec_state(response) == _RUNNING_VALUE
117# ---------------------------------------------------------------------------
118# Start / Stop
119# ---------------------------------------------------------------------------
122async def start_rapid(
123 client: RWSClient,
124 *,
125 regain: str = "continue",
126 execmode: str = "continue",
127 cycle: str = "forever",
128 condition: str = "none",
129 stopatbp: str = "disabled",
130 alltaskbytsp: str = "false",
131) -> None:
132 """Reset the program pointer to main and start RAPID execution.
134 Composes ``reset_rapid_program_pointer_to_main`` followed by
135 ``start_rapid_execution``. Mastership is not requested explicitly
136 because ABB handles it internally for both ``resetpp`` and ``start``
137 in RW6 AUTO mode.
139 Route (delegated):
140 - ``POST /rw/rapid/execution`` (action=resetpp)
141 - ``POST /rw/rapid/execution`` (action=start)
143 ABB constraints:
144 - Controller must be in AUTO mode with motors ON.
145 - ``resetpp`` requires mastership; ABB grants it implicitly.
147 Args:
148 client: Open ``RWSClient`` instance.
149 regain: Regain mode. One of ``continue | regain | clear``.
150 Defaults to ``"continue"``.
151 execmode: Execution mode. One of ``continue | stepin | stepover
152 | stepout | stepback | steplast | stepmotion``.
153 Defaults to ``"continue"``.
154 cycle: Cycle mode. One of ``forever | asis | once``.
155 Defaults to ``"forever"``.
156 condition: Condition. One of ``none | callchain``.
157 Defaults to ``"none"``.
158 stopatbp: Stop at breakpoint. One of ``disabled | enabled``.
159 Defaults to ``"disabled"``.
160 alltaskbytsp: All tasks by TSP. One of ``true | false``.
161 Defaults to ``"false"``.
163 Returns:
164 None. Both underlying calls expect HTTP 204.
166 Raises:
167 RWSAuthenticationError: On HTTP 401.
168 RWSNotFoundError: On HTTP 404.
169 RWSHTTPError: On any other HTTP >= 400.
171 Example:
172 ```python
173 async with RWSClient(host="192.168.125.1") as client:
174 await start_rapid(client, cycle="once")
175 ```
176 """
177 await reset_rapid_program_pointer_to_main(client, action="resetpp")
178 await start_rapid_execution(
179 client,
180 action="start",
181 regain=regain,
182 execmode=execmode,
183 cycle=cycle,
184 condition=condition,
185 stopatbp=stopatbp,
186 alltaskbytsp=alltaskbytsp,
187 )
188 logger.debug("RAPID execution started (cycle=%s)", cycle)
191async def stop_rapid(
192 client: RWSClient,
193 *,
194 stopmode: str = "stop",
195) -> None:
196 """Stop RAPID execution.
198 Wraps ``stop_rapid_execution`` with ``action="stop"``.
200 Route (delegated): ``POST /rw/rapid/execution`` (action=stop)
202 ABB constraints:
203 - No mastership required to stop.
205 Args:
206 client: Open ``RWSClient`` instance.
207 stopmode: Stop mode. One of ``stop | qstop | halt``.
208 Defaults to ``"stop"``.
210 Returns:
211 None. Expects HTTP 204.
213 Raises:
214 RWSAuthenticationError: On HTTP 401.
215 RWSNotFoundError: On HTTP 404.
216 RWSHTTPError: On any other HTTP >= 400.
218 Example:
219 ```python
220 async with RWSClient(host="192.168.125.1") as client:
221 await stop_rapid(client)
222 ```
223 """
224 await stop_rapid_execution(client, action="stop", stopmode=stopmode)
225 logger.debug("RAPID execution stopped (stopmode=%s)", stopmode)
228# ---------------------------------------------------------------------------
229# Polling
230# ---------------------------------------------------------------------------
233async def wait_until_stopped(
234 client: RWSClient,
235 *,
236 poll_interval: float = 0.2,
237 timeout: float | None = None,
238) -> None:
239 """Poll until RAPID execution is no longer running.
241 Repeatedly calls ``get_rapid_execution_state`` until
242 ``ctrlexecstate`` is no longer ``"running"``, or until the optional
243 timeout is exceeded.
245 Route (delegated): ``GET /rw/rapid/execution``
247 ABB constraints:
248 - Polling-based; no WebSocket/subscription used.
249 - ``poll_interval`` should be ≥ 0.1 s to avoid flooding the
250 controller.
252 Args:
253 client: Open ``RWSClient`` instance.
254 poll_interval: Seconds between each poll. Defaults to ``0.2``.
255 timeout: Maximum seconds to wait. ``None`` means wait forever.
256 Defaults to ``None``.
258 Returns:
259 None. Returns as soon as the controller is no longer running.
261 Raises:
262 RWSAuthenticationError: On HTTP 401.
263 RWSNotFoundError: On HTTP 404.
264 RWSHTTPError: On any other HTTP >= 400.
265 TimeoutError: If ``timeout`` is set and exceeded before the
266 controller stops.
267 ValueError: If the execution state cannot be parsed.
269 Example:
270 ```python
271 async with RWSClient(host="192.168.125.1") as client:
272 await start_rapid(client, cycle="once")
273 await wait_until_stopped(client, timeout=30.0)
274 print("Program finished.")
275 ```
276 """
277 elapsed = 0.0
278 while True:
279 if not await is_running(client):
280 return
281 if timeout is not None and elapsed >= timeout:
282 raise TimeoutError(
283 f"RAPID still running after {timeout}s (poll_interval={poll_interval}s)"
284 )
285 await asyncio.sleep(poll_interval)
286 elapsed += poll_interval