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

1# abb_rws_client/highlevel/execution.py 

2"""High-level RAPID execution control for ABB RWS RobotWare 6. 

3 

4Author: Clement RACINET 

5 

6Composed operations built exclusively from atomic ``rws/`` functions. 

7No HTTP calls are made directly in this module. 

8 

9All functions are async and require an open ``RWSClient`` instance. 

10""" 

11 

12from __future__ import annotations 

13 

14import asyncio 

15import re 

16 

17import httpx 

18 

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) 

27 

28logger = get_logger(__name__) 

29 

30# --------------------------------------------------------------------------- 

31# Internal helpers 

32# --------------------------------------------------------------------------- 

33 

34_EXEC_STATE_KEY = "ctrlexecstate" 

35_RUNNING_VALUE = "running" 

36 

37 

38def _parse_exec_state(response: httpx.Response) -> str: 

39 """Extract ``ctrlexecstate`` from a RAPID execution state response. 

40 

41 ABB RWS returns either XML/HTML (default) or JSON depending on the 

42 ``Accept`` header sent by the client. Both formats are handled. 

43 

44 Args: 

45 response: Raw HTTP response from ``get_rapid_execution_state``. 

46 

47 Returns: 

48 The execution state string, e.g. ``"running"`` or ``"stopped"``. 

49 

50 Raises: 

51 ValueError: If the state cannot be extracted from the response body. 

52 

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 

68 

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

76 

77 raise ValueError(f"Cannot parse ctrlexecstate from response: {response.text[:200]}") 

78 

79 

80# --------------------------------------------------------------------------- 

81# Execution state 

82# --------------------------------------------------------------------------- 

83 

84 

85async def is_running(client: RWSClient) -> bool: 

86 """Check whether RAPID execution is currently running. 

87 

88 Wraps ``get_rapid_execution_state`` and parses the ``ctrlexecstate`` 

89 field from the response. 

90 

91 Route (delegated): ``GET /rw/rapid/execution`` 

92 

93 Args: 

94 client: Open ``RWSClient`` instance. 

95 

96 Returns: 

97 ``True`` if the controller execution state is ``"running"``, 

98 ``False`` otherwise (``"stopped"``, ``"idle"``, etc.). 

99 

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. 

105 

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 

115 

116 

117# --------------------------------------------------------------------------- 

118# Start / Stop 

119# --------------------------------------------------------------------------- 

120 

121 

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. 

133 

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. 

138 

139 Route (delegated): 

140 - ``POST /rw/rapid/execution`` (action=resetpp) 

141 - ``POST /rw/rapid/execution`` (action=start) 

142 

143 ABB constraints: 

144 - Controller must be in AUTO mode with motors ON. 

145 - ``resetpp`` requires mastership; ABB grants it implicitly. 

146 

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"``. 

162 

163 Returns: 

164 None. Both underlying calls expect HTTP 204. 

165 

166 Raises: 

167 RWSAuthenticationError: On HTTP 401. 

168 RWSNotFoundError: On HTTP 404. 

169 RWSHTTPError: On any other HTTP >= 400. 

170 

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) 

189 

190 

191async def stop_rapid( 

192 client: RWSClient, 

193 *, 

194 stopmode: str = "stop", 

195) -> None: 

196 """Stop RAPID execution. 

197 

198 Wraps ``stop_rapid_execution`` with ``action="stop"``. 

199 

200 Route (delegated): ``POST /rw/rapid/execution`` (action=stop) 

201 

202 ABB constraints: 

203 - No mastership required to stop. 

204 

205 Args: 

206 client: Open ``RWSClient`` instance. 

207 stopmode: Stop mode. One of ``stop | qstop | halt``. 

208 Defaults to ``"stop"``. 

209 

210 Returns: 

211 None. Expects HTTP 204. 

212 

213 Raises: 

214 RWSAuthenticationError: On HTTP 401. 

215 RWSNotFoundError: On HTTP 404. 

216 RWSHTTPError: On any other HTTP >= 400. 

217 

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) 

226 

227 

228# --------------------------------------------------------------------------- 

229# Polling 

230# --------------------------------------------------------------------------- 

231 

232 

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. 

240 

241 Repeatedly calls ``get_rapid_execution_state`` until 

242 ``ctrlexecstate`` is no longer ``"running"``, or until the optional 

243 timeout is exceeded. 

244 

245 Route (delegated): ``GET /rw/rapid/execution`` 

246 

247 ABB constraints: 

248 - Polling-based; no WebSocket/subscription used. 

249 - ``poll_interval`` should be ≥ 0.1 s to avoid flooding the 

250 controller. 

251 

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``. 

257 

258 Returns: 

259 None. Returns as soon as the controller is no longer running. 

260 

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. 

268 

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