Coverage for abb_rws_client_python_rw6/core/client.py: 100%

162 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-13 22:17 +0000

1# abb_rws_client/core/client.py 

2""" 

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

4 

5Author: Clement RACINET 

6 

7Module responsibilities: 

8- Create and maintain an httpx.AsyncClient configured for RWS 

9- Handle ABB HTTP Digest authentication 

10- Maintain the ABBCX session cookie 

11- Expose low-level HTTP methods (get, put, post, delete, head, options) 

12 used by the rws/ and highlevel/ modules 

13- Implement the retry policy on transport errors 

14- Provide RWSClientSync, a synchronous wrapper with no logic duplication 

15 

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

17 

18 - Triggers: ConnectError, ConnectTimeout, ReadTimeout, PoolTimeout only. 

19 HTTP errors (4xx, 5xx) are never retried. 

20 - Attempts: 3 total (1 initial attempt + 2 retries) 

21 - Delay: exponential with ±10% jitter 

22 base * 2^attempt + jitter → ~0.5s, ~1s, ~2s 

23 

24ABBCX cookie management:: 

25 

26 httpx.AsyncClient maintains this cookie natively via its cookiejar. 

27 On expiry (ABB timeout ~10 min), the controller responds with 401 

28 and httpx.DigestAuth automatically restarts the handshake. 

29 

30RWSClientSync:: 

31 

32 Synchronous wrapper based on httpx.Client (httpx native sync). 

33 Same retry/auth logic, no anyio dependency at runtime. 

34 All methods are synchronous (no async def). 

35""" 

36 

37from __future__ import annotations 

38 

39import asyncio 

40import logging 

41import random 

42import time 

43from types import TracebackType 

44from typing import Any, Self, cast 

45 

46import httpx 

47 

48from abb_rws_client_python_rw6.core.env import ( 

49 get_env_float_or_none, 

50 get_env_int, 

51 get_env_str, 

52) 

53from abb_rws_client_python_rw6.core.exceptions import ( 

54 RWSAuthenticationError, 

55 RWSConnectionError, 

56 RWSHTTPError, 

57 RWSNotFoundError, 

58 RWSTimeoutError, 

59) 

60 

61logger = logging.getLogger(__name__) 

62 

63# --------------------------------------------------------------------------- 

64# Retry constants 

65# --------------------------------------------------------------------------- 

66 

67#: Total number of attempts (1 initial attempt + _RETRY_MAX_ATTEMPTS - 1 retries) 

68_RETRY_MAX_ATTEMPTS: int = 3 

69 

70#: Base delay in seconds: _RETRY_BASE_DELAY * 2^attempt → 0.5s, 1.0s, 2.0s 

71_RETRY_BASE_DELAY: float = 0.5 

72 

73#: Jitter amplitude (fraction of the computed delay) → ±10% 

74_RETRY_JITTER: float = 0.1 

75 

76#: httpx exception types that trigger a retry (transport errors only) 

77_RETRYABLE_EXCEPTIONS = ( 

78 httpx.ConnectError, 

79 httpx.ConnectTimeout, 

80 httpx.ReadTimeout, 

81 httpx.PoolTimeout, 

82) 

83 

84# --------------------------------------------------------------------------- 

85# Shared helpers (async/sync) 

86# --------------------------------------------------------------------------- 

87 

88 

89def _prepare_request_kwargs( 

90 method: str, 

91 kwargs: dict[str, object], 

92) -> dict[str, Any]: 

93 """Prepare kwargs before forwarding them to httpx. 

94 

95 Args: 

96 method: HTTP method. 

97 kwargs: Keyword arguments received by the public HTTP wrapper. 

98 

99 Returns: 

100 Mutable kwargs dictionary accepted by ``httpx.request``. 

101 

102 Raises: 

103 None. 

104 

105 Example: 

106 ```python 

107 >>> prepared = _prepare_request_kwargs("POST", {"data": {"action": "set"}}) 

108 >>> "headers" in prepared 

109 True 

110 ``` 

111 """ 

112 request_kwargs: dict[str, Any] = dict(kwargs) 

113 

114 if method in ("POST", "PUT"): 

115 raw_headers = request_kwargs.pop("headers", None) 

116 headers: dict[str, str] = dict(cast(Any, raw_headers) or {}) 

117 

118 if "content-type" not in {key.lower() for key in headers}: 

119 headers["Content-Type"] = "application/x-www-form-urlencoded" 

120 

121 request_kwargs["headers"] = headers 

122 

123 return request_kwargs 

124 

125 

126def _build_auth(username: str, password: str) -> httpx.DigestAuth: 

127 """Build the httpx DigestAuth object. 

128 

129 Args: 

130 username: RWS username. 

131 password: RWS password. 

132 

133 Returns: 

134 Configured ``httpx.DigestAuth`` instance. 

135 

136 Example: 

137 ```python 

138 >>> auth = _build_auth("Default User", "robotics") 

139 ``` 

140 """ 

141 return httpx.DigestAuth(username, password) 

142 

143 

144def _raise_for_status(response: httpx.Response, path: str) -> None: 

145 """Raise the appropriate RWS exception based on the HTTP status code. 

146 

147 Args: 

148 response: The httpx response received. 

149 path: Request path, used in error messages. 

150 

151 Raises: 

152 RWSAuthenticationError: On HTTP 401. 

153 RWSNotFoundError: On HTTP 404. 

154 RWSHTTPError: On any other status >= 400. 

155 

156 Example: 

157 ```python 

158 >>> _raise_for_status(response, "rw/rapid/execution") 

159 ``` 

160 """ 

161 code = response.status_code 

162 if code == 401: 

163 raise RWSAuthenticationError() 

164 if code == 404: 

165 raise RWSNotFoundError(path) 

166 # ── _raise_for_status : 200 → 1000 ──────────────────────────────────────── 

167 if code >= 400: 

168 raise RWSHTTPError( 

169 f"HTTP {code} on {path}: {response.text[:1000]}", # était 200 

170 status_code=code, 

171 ) 

172 

173 

174def _retry_delay(attempt: int) -> float: 

175 """Compute the delay before the next retry, with exponential backoff and jitter. 

176 

177 Args: 

178 attempt: Index of the failed attempt (0-based). 

179 

180 Returns: 

181 Delay in seconds (float). 

182 

183 Example: 

184 ```python 

185 >>> delay = _retry_delay(0) # ~0.5s 

186 >>> delay = _retry_delay(1) # ~1.0s 

187 ``` 

188 """ 

189 base = _RETRY_BASE_DELAY * (2**attempt) 

190 jitter = base * _RETRY_JITTER * (2 * random.random() - 1) 

191 return base + jitter 

192 

193 

194# --------------------------------------------------------------------------- 

195# RWSClient — async 

196# --------------------------------------------------------------------------- 

197 

198 

199class RWSClient: 

200 """Async HTTP client for the ABB Robot Web Services (RWS) API — RobotWare 6. 

201 

202 Designed to be used as an async context manager, which guarantees 

203 proper HTTP session teardown in all cases. 

204 

205 Args: 

206 host: Controller IP address or hostname (e.g. ``"192.168.125.1"``). 

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

208 password: RWS password (ABB default: ``"robotics"``). 

209 port: Controller HTTP port (default: ``80``). 

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

211 

212 Example: 

213 ```python 

214 >>> async with RWSClient(host="192.168.125.1") as client: 

215 ... resp = await client.get("rw/rapid/execution") 

216 ``` 

217 """ 

218 

219 def __init__( 

220 self, 

221 host: str | None = None, 

222 username: str | None = None, 

223 password: str | None = None, 

224 port: int | None = None, 

225 timeout: float | None = None, 

226 ) -> None: 

227 self.host = host or get_env_str("RWS_HOST", "192.168.1.10") 

228 self.username = username or get_env_str("RWS_USER", "Default User") 

229 self.password = password or get_env_str("RWS_PASSWORD", "robotics") 

230 self.port = port or get_env_int("RWS_PORT", 80) 

231 self.timeout = ( 

232 timeout if timeout is not None else get_env_float_or_none("RWS_TIMEOUT", None) 

233 ) 

234 self.base_url = f"http://{self.host}:{self.port}/" 

235 self._http: httpx.AsyncClient | None = None 

236 

237 # ── Lifecycle ─────────────────────────────────────────────────────────── 

238 

239 async def aopen(self) -> None: 

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

241 

242 Raises: 

243 RWSConnectionError: If the initial connection fails. 

244 

245 Example: 

246 ```python 

247 >>> await client.aopen() 

248 ``` 

249 """ 

250 if self._http is not None: 

251 return 

252 self._http = httpx.AsyncClient( 

253 base_url=self.base_url, 

254 auth=_build_auth(self.username, self.password), 

255 timeout=self.timeout, 

256 follow_redirects=True, 

257 ) 

258 logger.debug("RWSClient opened → %s", self.base_url) 

259 

260 async def aclose(self) -> None: 

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

262 

263 Example: 

264 ```python 

265 >>> await client.aclose() 

266 ``` 

267 """ 

268 if self._http is None: 

269 return 

270 await self._http.aclose() 

271 self._http = None 

272 logger.debug("RWSClient closed → %s", self.base_url) 

273 

274 async def __aenter__(self) -> Self: 

275 await self.aopen() 

276 return self 

277 

278 async def __aexit__( 

279 self, 

280 exc_type: type[BaseException] | None, 

281 exc_val: BaseException | None, 

282 exc_tb: TracebackType | None, 

283 ) -> None: 

284 await self.aclose() 

285 

286 def __repr__(self) -> str: 

287 state = "open" if self._http is not None else "closed" 

288 return f"RWSClient(host={self.host!r}, timeout={self.timeout}, state={state!r})" 

289 

290 def session_cookie_header(self) -> str: 

291 """Return the current session cookies as a single ``Cookie`` header value. 

292 

293 ABB Route: 

294 N/A — local session helper, no HTTP call performed. 

295 

296 ABB Constraints: 

297 Meaningful only once the session is open and at least one 

298 request has succeeded (ABBCX is set by the controller after 

299 the first successful digest handshake). 

300 

301 Returns: 

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

303 used as the ``Cookie`` header of a WebSocket handshake. 

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

305 cookies yet. 

306 

307 Example: 

308 ```python 

309 >>> async with RWSClient(host="192.168.125.1") as client: 

310 ... await client.get("rw/rapid/execution") 

311 ... header = client.session_cookie_header() 

312 ... # header == "-http-session-=...; ABBCX=..." 

313 ``` 

314 """ 

315 if self._http is None: 

316 return "" 

317 return "; ".join(f"{cookie.name}={cookie.value}" for cookie in self._http.cookies.jar) 

318 

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

320 

321 async def _request( 

322 self, 

323 method: str, 

324 path: str, 

325 **kwargs: object, 

326 ) -> httpx.Response: 

327 """Execute an HTTP request with the transport-error retry policy. 

328 

329 Args: 

330 method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, ``"DELETE"``). 

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

332 **kwargs: Additional parameters forwarded to httpx 

333 (``params``, ``data``, ``json``, …). 

334 

335 Returns: 

336 httpx response (status not checked — call ``_raise_for_status`` 

337 if needed, though it is already called internally). 

338 

339 Raises: 

340 RuntimeError: If the client is not open. 

341 RWSConnectionError: After retries are exhausted on ConnectError. 

342 RWSTimeoutError: After retries are exhausted on ReadTimeout/PoolTimeout. 

343 RWSAuthenticationError: On HTTP 401. 

344 RWSNotFoundError: On HTTP 404. 

345 RWSHTTPError: On any other HTTP >= 400. 

346 

347 Example: 

348 ```python 

349 >>> resp = await client._request( 

350 ... "GET", 

351 ... "rw/rapid/execution", 

352 ... params={"json": "1"}, 

353 ... ) 

354 ``` 

355 """ 

356 if self._http is None: 

357 raise RuntimeError( 

358 "RWSClient is not open. Use 'async with RWSClient(...) as client' " 

359 "or call await client.aopen() first." 

360 ) 

361 

362 # ABB RW6 requires Content-Type: application/x-www-form-urlencoded on 

363 # every POST and PUT, even when the body is empty. httpx does not set 

364 # this header automatically when data={} or no body is provided. 

365 request_kwargs = _prepare_request_kwargs(method, kwargs) 

366 

367 last_exc: Exception | None = None 

368 for attempt in range(_RETRY_MAX_ATTEMPTS): 

369 try: 

370 response = await self._http.request(method, path, **request_kwargs) 

371 _raise_for_status(response, path) 

372 return response 

373 except _RETRYABLE_EXCEPTIONS as exc: 

374 last_exc = exc 

375 if attempt < _RETRY_MAX_ATTEMPTS - 1: 

376 delay = _retry_delay(attempt) 

377 logger.warning( 

378 "RWSClient %s %s → %s (attempt %d/%d, retry in %.2fs)", 

379 method, 

380 path, 

381 type(exc).__name__, 

382 attempt + 1, 

383 _RETRY_MAX_ATTEMPTS, 

384 delay, 

385 ) 

386 await asyncio.sleep(delay) 

387 # All retries exhausted 

388 assert last_exc is not None 

389 if isinstance(last_exc, httpx.ConnectError): 

390 raise RWSConnectionError( 

391 f"Connection failed to {self.base_url}: {last_exc}" 

392 ) from last_exc 

393 raise RWSTimeoutError( 

394 f"Timeout on {method} {path} after {_RETRY_MAX_ATTEMPTS} attempts" 

395 ) from last_exc 

396 

397 # ── Public HTTP methods ────────────────────────────────────────────────── 

398 

399 async def get(self, path: str, **kwargs: object) -> httpx.Response: 

400 """Send an HTTP GET request to the RWS controller. 

401 

402 Route: ``GET {path}`` 

403 

404 Args: 

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

406 **kwargs: Additional httpx parameters (``params``, ``headers``, …). 

407 

408 Returns: 

409 Validated httpx response (status < 400). 

410 

411 Raises: 

412 RWSConnectionError: Network error after retries. 

413 RWSTimeoutError: Timeout after retries. 

414 RWSAuthenticationError: HTTP 401. 

415 RWSNotFoundError: HTTP 404. 

416 RWSHTTPError: Any other HTTP >= 400. 

417 

418 Example: 

419 ```python 

420 >>> resp = await client.get("rw/rapid/execution", params={"json": "1"}) 

421 ``` 

422 """ 

423 return await self._request("GET", path, **kwargs) 

424 

425 async def post(self, path: str, **kwargs: object) -> httpx.Response: 

426 """Send an HTTP POST request to the RWS controller. 

427 

428 Route: ``POST {path}`` 

429 

430 Args: 

431 path: Path relative to the base URL (e.g. ``"rw/mastership"``). 

432 **kwargs: Additional httpx parameters (``params``, ``data``, ``json``, …). 

433 

434 Returns: 

435 Validated httpx response (status < 400). 

436 

437 Raises: 

438 RWSConnectionError: Network error after retries. 

439 RWSTimeoutError: Timeout after retries. 

440 RWSAuthenticationError: HTTP 401. 

441 RWSNotFoundError: HTTP 404. 

442 RWSHTTPError: Any other HTTP >= 400. 

443 

444 Example: 

445 ```python 

446 >>> await client.post("rw/mastership", params={"action": "request"}) 

447 ``` 

448 """ 

449 return await self._request("POST", path, **kwargs) 

450 

451 async def put(self, path: str, **kwargs: object) -> httpx.Response: 

452 """Send an HTTP PUT request to the RWS controller. 

453 

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

455 

456 Args: 

457 path: Path relative to the base URL. 

458 **kwargs: Additional httpx parameters (``data``, …). 

459 

460 Returns: 

461 Validated httpx response (status < 400). 

462 

463 Raises: 

464 RWSConnectionError: Network error after retries. 

465 RWSTimeoutError: Timeout after retries. 

466 RWSAuthenticationError: HTTP 401. 

467 RWSNotFoundError: HTTP 404. 

468 RWSHTTPError: Any other HTTP >= 400. 

469 

470 Example: 

471 ```python 

472 >>> await client.put( 

473 ... "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR", 

474 ... data={"value": "42"}, 

475 ... ) 

476 ``` 

477 """ 

478 return await self._request("PUT", path, **kwargs) 

479 

480 async def delete(self, path: str, **kwargs: object) -> httpx.Response: 

481 """Send an HTTP DELETE request to the RWS controller. 

482 

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

484 

485 Args: 

486 path: Path relative to the base URL. 

487 **kwargs: Additional httpx parameters. 

488 

489 Returns: 

490 Validated httpx response (status < 400). 

491 

492 Raises: 

493 RWSConnectionError: Network error after retries. 

494 RWSTimeoutError: Timeout after retries. 

495 RWSAuthenticationError: HTTP 401. 

496 RWSNotFoundError: HTTP 404. 

497 RWSHTTPError: Any other HTTP >= 400. 

498 

499 Example: 

500 ```python 

501 >>> await client.delete("fileservice/$HOME/old_backup.tar.gz") 

502 ``` 

503 """ 

504 return await self._request("DELETE", path, **kwargs) 

505 

506 async def head( 

507 self, 

508 path: str, 

509 **kwargs: object, 

510 ) -> httpx.Response: 

511 """Send an HTTP HEAD request to the RWS controller. 

512 

513 Route: ``HEAD {path}`` 

514 

515 Args: 

516 path: Path relative to the base URL. 

517 **kwargs: Additional parameters forwarded to httpx. 

518 

519 Returns: 

520 Raw HTTP response (headers only, no body). 

521 

522 Raises: 

523 RWSAuthenticationError: On HTTP 401. 

524 RWSNotFoundError: On HTTP 404. 

525 RWSHTTPError: On any other HTTP >= 400. 

526 RWSConnectionError: If the controller is unreachable. 

527 RWSTimeoutError: If the request exceeds the timeout. 

528 

529 Example: 

530 ```python 

531 >>> resp = await client.head("fileservice/$HOME/myfile.txt") 

532 ``` 

533 """ 

534 return await self._request("HEAD", path, **kwargs) 

535 

536 async def options( 

537 self, 

538 path: str, 

539 **kwargs: object, 

540 ) -> httpx.Response: 

541 """Send an HTTP OPTIONS request to the RWS controller. 

542 

543 Route: ``OPTIONS {path}`` 

544 

545 Args: 

546 path: Path relative to the base URL. 

547 **kwargs: Additional parameters forwarded to httpx. 

548 

549 Returns: 

550 Raw HTTP response. 

551 

552 Raises: 

553 RWSAuthenticationError: On HTTP 401. 

554 RWSNotFoundError: On HTTP 404. 

555 RWSHTTPError: On any other HTTP >= 400. 

556 RWSConnectionError: If the controller is unreachable. 

557 RWSTimeoutError: If the request exceeds the timeout. 

558 

559 Example: 

560 ```python 

561 >>> resp = await client.options("ctrl/network/route/add") 

562 ``` 

563 """ 

564 return await self._request("OPTIONS", path, **kwargs) 

565 

566 

567# --------------------------------------------------------------------------- 

568# RWSClientSync — synchronous wrapper 

569# --------------------------------------------------------------------------- 

570 

571 

572class RWSClientSync: 

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

574 

575 Synchronous wrapper around ``RWSClient``, based on ``httpx.Client`` natively. 

576 Same authentication policy (DigestAuth), same retry logic, same error handling. 

577 No ``anyio`` or ``asyncio`` dependency at runtime. 

578 

579 Designed to be used as a synchronous context manager. 

580 

581 Args: 

582 host: Controller IP address or hostname (e.g. ``"192.168.125.1"``). 

583 Reads ``RWS_HOST`` from environment if ``None``. 

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

585 Reads ``RWS_USER`` from environment if ``None``. 

586 password: RWS password (ABB default: ``"robotics"``). 

587 Reads ``RWS_PASSWORD`` from environment if ``None``. 

588 port: HTTP port (default: ``80``). 

589 Reads ``RWS_PORT`` from environment if ``None``. 

590 timeout: HTTP timeout in seconds, or ``None`` for no timeout 

591 (default: ``None``). Reads ``RWS_TIMEOUT`` from environment 

592 if not provided explicitly. 

593 

594 Example: 

595 ```python 

596 >>> with RWSClientSync(host="192.168.125.1") as client: 

597 ... resp = client.get("rw/rapid/execution") 

598 ``` 

599 """ 

600 

601 def __init__( 

602 self, 

603 host: str | None = None, 

604 username: str | None = None, 

605 password: str | None = None, 

606 port: int | None = None, 

607 timeout: float | None = None, 

608 ) -> None: 

609 self.host = host or get_env_str("RWS_HOST", "192.168.125.1") 

610 self.username = username or get_env_str("RWS_USER", "Default User") 

611 self.password = password or get_env_str("RWS_PASSWORD", "robotics") 

612 self.port = port or get_env_int("RWS_PORT", 80) 

613 self.timeout = ( 

614 timeout if timeout is not None else get_env_float_or_none("RWS_TIMEOUT", None) 

615 ) 

616 self.base_url = f"http://{self.host}:{self.port}/" 

617 self._http: httpx.Client | None = None 

618 

619 # ── Lifecycle ─────────────────────────────────────────────────────────── 

620 

621 def open(self) -> None: 

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

623 

624 Example: 

625 ```python 

626 >>> client.open() 

627 ``` 

628 """ 

629 if self._http is not None: 

630 return 

631 self._http = httpx.Client( 

632 base_url=self.base_url, 

633 auth=_build_auth(self.username, self.password), 

634 timeout=self.timeout, 

635 follow_redirects=True, 

636 ) 

637 logger.debug("RWSClientSync opened → %s", self.base_url) 

638 

639 def close(self) -> None: 

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

641 

642 Example: 

643 ```python 

644 >>> client.close() 

645 ``` 

646 """ 

647 if self._http is None: 

648 return 

649 self._http.close() 

650 self._http = None 

651 logger.debug("RWSClientSync closed → %s", self.base_url) 

652 

653 def __enter__(self) -> Self: 

654 self.open() 

655 return self 

656 

657 def __exit__( 

658 self, 

659 exc_type: type[BaseException] | None, 

660 exc_val: BaseException | None, 

661 exc_tb: TracebackType | None, 

662 ) -> None: 

663 self.close() 

664 

665 def __repr__(self) -> str: 

666 state = "open" if self._http is not None else "closed" 

667 return f"RWSClientSync(host={self.host!r}, state={state!r})" 

668 

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

670 

671 def _request(self, method: str, path: str, **kwargs: object) -> httpx.Response: 

672 """Execute a synchronous HTTP request with the transport-error retry policy. 

673 

674 Args: 

675 method: HTTP method (``"GET"``, ``"POST"``, ``"PUT"``, ``"DELETE"``). 

676 path: Path relative to the base URL. 

677 **kwargs: Additional parameters forwarded to httpx. 

678 

679 Returns: 

680 Validated httpx response (status < 400). 

681 

682 Raises: 

683 RuntimeError: If the client is not open. 

684 RWSConnectionError: After retries are exhausted on ConnectError. 

685 RWSTimeoutError: After retries are exhausted on timeout errors. 

686 RWSAuthenticationError: On HTTP 401. 

687 RWSNotFoundError: On HTTP 404. 

688 RWSHTTPError: On any other HTTP >= 400. 

689 

690 Example: 

691 ```python 

692 >>> resp = client._request( 

693 ... "GET", 

694 ... "rw/rapid/execution", 

695 ... params={"json": "1"}, 

696 ... ) 

697 ``` 

698 """ 

699 if self._http is None: 

700 raise RuntimeError( 

701 "RWSClientSync is not open. Use 'with RWSClientSync(...) as client' " 

702 "or call client.open() first." 

703 ) 

704 

705 # ABB RW6 requires Content-Type: application/x-www-form-urlencoded on 

706 # every POST and PUT, even when the body is empty. httpx does not set 

707 # this header automatically when data={} or no body is provided. 

708 request_kwargs = _prepare_request_kwargs(method, kwargs) 

709 

710 last_exc: Exception | None = None 

711 for attempt in range(_RETRY_MAX_ATTEMPTS): 

712 try: 

713 response = self._http.request(method, path, **request_kwargs) 

714 _raise_for_status(response, path) 

715 return response 

716 except _RETRYABLE_EXCEPTIONS as exc: 

717 last_exc = exc 

718 if attempt < _RETRY_MAX_ATTEMPTS - 1: 

719 delay = _retry_delay(attempt) 

720 logger.warning( 

721 "RWSClientSync %s %s → %s (attempt %d/%d, retry in %.2fs)", 

722 method, 

723 path, 

724 type(exc).__name__, 

725 attempt + 1, 

726 _RETRY_MAX_ATTEMPTS, 

727 delay, 

728 ) 

729 time.sleep(delay) 

730 # All retries exhausted 

731 assert last_exc is not None 

732 if isinstance(last_exc, httpx.ConnectError): 

733 raise RWSConnectionError(f"Cannot connect to {self.base_url}: {last_exc}") from last_exc 

734 raise RWSTimeoutError( 

735 f"Timeout on {method} {path} after {_RETRY_MAX_ATTEMPTS} attempts" 

736 ) from last_exc 

737 

738 # ── Public HTTP methods ────────────────────────────────────────────────── 

739 

740 def get(self, path: str, **kwargs: object) -> httpx.Response: 

741 """Send a synchronous HTTP GET request to the RWS controller. 

742 

743 Route: ``GET {path}`` 

744 

745 Args: 

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

747 **kwargs: Additional httpx parameters (``params``, …). 

748 

749 Returns: 

750 Validated httpx response (status < 400). 

751 

752 Raises: 

753 RWSConnectionError: Network error after retries. 

754 RWSTimeoutError: Timeout after retries. 

755 RWSAuthenticationError: HTTP 401. 

756 RWSNotFoundError: HTTP 404. 

757 RWSHTTPError: Any other HTTP >= 400. 

758 

759 Example: 

760 ```python 

761 >>> resp = client.get("rw/rapid/execution", params={"json": "1"}) 

762 ``` 

763 """ 

764 return self._request("GET", path, **kwargs) 

765 

766 def post(self, path: str, **kwargs: object) -> httpx.Response: 

767 """Send a synchronous HTTP POST request to the RWS controller. 

768 

769 Route: ``POST {path}`` 

770 

771 Args: 

772 path: Path relative to the base URL. 

773 **kwargs: Additional httpx parameters (``params``, ``data``, …). 

774 

775 Returns: 

776 Validated httpx response (status < 400). 

777 

778 Raises: 

779 RWSConnectionError: Network error after retries. 

780 RWSTimeoutError: Timeout after retries. 

781 RWSAuthenticationError: HTTP 401. 

782 RWSNotFoundError: HTTP 404. 

783 RWSHTTPError: Any other HTTP >= 400. 

784 

785 Example: 

786 ```python 

787 >>> client.post("rw/mastership", params={"action": "request"}) 

788 ``` 

789 """ 

790 return self._request("POST", path, **kwargs) 

791 

792 def put(self, path: str, **kwargs: object) -> httpx.Response: 

793 """Send a synchronous HTTP PUT request to the RWS controller. 

794 

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

796 

797 Args: 

798 path: Path relative to the base URL. 

799 **kwargs: Additional httpx parameters (``data``, …). 

800 

801 Returns: 

802 Validated httpx response (status < 400). 

803 

804 Raises: 

805 RWSConnectionError: Network error after retries. 

806 RWSTimeoutError: Timeout after retries. 

807 RWSAuthenticationError: HTTP 401. 

808 RWSNotFoundError: HTTP 404. 

809 RWSHTTPError: Any other HTTP >= 400. 

810 

811 Example: 

812 ```python 

813 >>> client.put( 

814 ... "rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR", 

815 ... data={"value": "42"}, 

816 ... ) 

817 ``` 

818 """ 

819 return self._request("PUT", path, **kwargs) 

820 

821 def delete(self, path: str, **kwargs: object) -> httpx.Response: 

822 """Send a synchronous HTTP DELETE request to the RWS controller. 

823 

824 Route: ``DELETE {path}`` 

825 

826 Args: 

827 path: Path relative to the base URL. 

828 **kwargs: Additional httpx parameters. 

829 

830 Returns: 

831 Validated httpx response (status < 400). 

832 

833 Raises: 

834 RWSConnectionError: Network error after retries. 

835 RWSTimeoutError: Timeout after retries. 

836 RWSAuthenticationError: HTTP 401. 

837 RWSNotFoundError: HTTP 404. 

838 RWSHTTPError: Any other HTTP >= 400. 

839 

840 Example: 

841 ```python 

842 >>> client.delete("fileservice/$HOME/old_backup.tar.gz") 

843 ``` 

844 """ 

845 return self._request("DELETE", path, **kwargs) 

846 

847 def head(self, path: str, **kwargs: object) -> httpx.Response: 

848 """Send a synchronous HTTP HEAD request to the RWS controller. 

849 

850 Route: ``HEAD {path}`` 

851 

852 Args: 

853 path: Path relative to the base URL. 

854 **kwargs: Additional parameters forwarded to httpx. 

855 

856 Returns: 

857 Raw HTTP response (headers only, no body). 

858 

859 Raises: 

860 RWSAuthenticationError: On HTTP 401. 

861 RWSNotFoundError: On HTTP 404. 

862 RWSHTTPError: On any other HTTP >= 400. 

863 RWSConnectionError: If the controller is unreachable. 

864 RWSTimeoutError: If the request exceeds the timeout. 

865 

866 Example: 

867 ```python 

868 >>> resp = client.head("fileservice/$HOME/myfile.txt") 

869 ``` 

870 """ 

871 return self._request("HEAD", path, **kwargs) 

872 

873 def options(self, path: str, **kwargs: object) -> httpx.Response: 

874 """Send a synchronous HTTP OPTIONS request to the RWS controller. 

875 

876 Route: ``OPTIONS {path}`` 

877 

878 Args: 

879 path: Path relative to the base URL. 

880 **kwargs: Additional parameters forwarded to httpx. 

881 

882 Returns: 

883 Raw HTTP response. 

884 

885 Raises: 

886 RWSAuthenticationError: On HTTP 401. 

887 RWSNotFoundError: On HTTP 404. 

888 RWSHTTPError: On any other HTTP >= 400. 

889 RWSConnectionError: If the controller is unreachable. 

890 RWSTimeoutError: If the request exceeds the timeout. 

891 

892 Example: 

893 ```python 

894 >>> resp = client.options("ctrl/network/route/add") 

895 ``` 

896 """ 

897 return self._request("OPTIONS", path, **kwargs)