Coverage for abb_rws_client_python_rw6/highlevel/symbol.py: 43%

50 statements  

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

1# abb_rws_client_python_rw6/highlevel/symbol.py 

2"""High-level RAPID symbol introspection 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 

14from dataclasses import dataclass 

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.symbol import get_rapid_symbol_properties 

22 

23logger = get_logger(__name__) 

24 

25# ABB RWS XML span pattern, consistent with the parsing style already used 

26# in highlevel/variables.py and highlevel/execution.py. 

27_SPAN_RE_TEMPLATE = r'class=["\']{field}["\'][^>]*>([^<]*)<' 

28 

29# FIXME (Clement RACINET): 

30# ABB doc ("Get RAPID symbol properties") only documents <span class="dim"> 

31# for ndim=0 (empty). The separator used for ndim>=1 is NOT documented and 

32# has not been confirmed on real hardware. This parser is intentionally 

33# tolerant: it extracts every integer found in the "dim" span, regardless 

34# of separator (space, comma, or ABB's real format). MUST be confirmed on 

35# real hardware against an array symbol (e.g. trajTools{N}) before being 

36# relied upon for production sizing decisions. If ABB's real format breaks 

37# this extraction, fix _parse_dim accordingly — do not patch around it 

38# blindly. 

39_INT_RE = re.compile(r"-?\d+") 

40 

41 

42@dataclass(frozen=True) 

43class SymbolProperties: 

44 """Parsed RAPID symbol properties from ``GET /rw/rapid/symbol/properties``. 

45 

46 Args: 

47 symbolurl: Symbol URL, e.g. ``"RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools"``. 

48 symtyp: Symbol type, e.g. ``"per"`` (persistent), ``"var"``, ``"con"``. 

49 dattyp: RAPID data type name, e.g. ``"trajCenterTool"``. 

50 ndim: Number of array dimensions. ``0`` means a scalar symbol. 

51 dim: Array dimension sizes, one entry per dimension. Empty when 

52 ``ndim == 0``. 

53 local: ``False`` for a global module persistent. 

54 readonly: ``True`` if the persistent is read-only. 

55 

56 Example: 

57 ```python 

58 >>> props = SymbolProperties( 

59 ... symbolurl="RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools", 

60 ... symtyp="per", 

61 ... dattyp="trajCenterTool", 

62 ... ndim=1, 

63 ... dim=(2,), 

64 ... local=False, 

65 ... readonly=False, 

66 ... ) 

67 >>> props.dim[0] 

68 2 

69 ``` 

70 """ 

71 

72 symbolurl: str 

73 symtyp: str 

74 dattyp: str 

75 ndim: int 

76 dim: tuple[int, ...] 

77 local: bool 

78 readonly: bool 

79 

80 

81def _extract_span(text: str, field: str) -> str | None: 

82 """Extract one ``<span class="{field}">...</span>`` value. 

83 

84 Args: 

85 text: Raw XML/XHTML response body. 

86 field: ABB span class name, e.g. ``"ndim"``. 

87 

88 Returns: 

89 The stripped span content, or ``None`` if not found. 

90 """ 

91 match = re.search(_SPAN_RE_TEMPLATE.format(field=field), text) 

92 return match.group(1).strip() if match else None 

93 

94 

95def _parse_bool_span(text: str, field: str, *, default: bool) -> bool: 

96 """Parse an ABB ``{True|False}`` span value. 

97 

98 Args: 

99 text: Raw XML/XHTML response body. 

100 field: ABB span class name. 

101 default: Value returned if the span is absent. 

102 

103 Returns: 

104 Parsed boolean. 

105 """ 

106 raw = _extract_span(text, field) 

107 if raw is None: 

108 return default 

109 return raw.strip().lower() == "true" 

110 

111 

112def _parse_dim(raw_dim: str) -> tuple[int, ...]: 

113 """Parse the ``dim`` span into a tuple of dimension sizes. 

114 

115 ABB constraints: 

116 The exact separator used by ABB for ``ndim >= 1`` is not 

117 documented (confirmed absent from ABB's official page, which only 

118 shows the ``ndim=0`` / empty ``dim`` case). This parser extracts 

119 every integer token found, regardless of separator, and is NOT 

120 confirmed on real hardware for ``ndim >= 1``. 

121 

122 Args: 

123 raw_dim: Raw ``dim`` span content, e.g. ``""`` or ``"2"`` or a 

124 multi-dimension form not yet observed on real hardware. 

125 

126 Returns: 

127 Tuple of dimension sizes, in declared order. Empty tuple if 

128 ``raw_dim`` is empty or contains no integer. 

129 

130 Example: 

131 ```python 

132 >>> _parse_dim("") 

133 () 

134 >>> _parse_dim("2") 

135 (2,) 

136 ``` 

137 """ 

138 return tuple(int(token) for token in _INT_RE.findall(raw_dim)) 

139 

140 

141def _parse_symbol_properties(response: httpx.Response, symbolurl: str) -> SymbolProperties: 

142 """Parse a ``GET /rw/rapid/symbol/properties/{symbolurl}`` response. 

143 

144 Args: 

145 response: Raw HTTP response from ``get_rapid_symbol_properties``. 

146 symbolurl: Requested symbol URL, used for error messages and as a 

147 fallback if ``symburl`` cannot be parsed from the body. 

148 

149 Returns: 

150 Parsed symbol properties. 

151 

152 Raises: 

153 ValueError: If mandatory fields (``dattyp``, ``ndim``) cannot be 

154 extracted from the response body. 

155 

156 Example: 

157 ```python 

158 resp = await get_rapid_symbol_properties(client, "RAPID/T_ROB1/M/trajTools") 

159 props = _parse_symbol_properties(resp, "RAPID/T_ROB1/M/trajTools") 

160 ``` 

161 """ 

162 text = response.text 

163 

164 symtyp = _extract_span(text, "symtyp") 

165 dattyp = _extract_span(text, "dattyp") 

166 ndim_raw = _extract_span(text, "ndim") 

167 dim_raw = _extract_span(text, "dim") or "" 

168 

169 if dattyp is None or ndim_raw is None: 

170 raise ValueError( 

171 "Cannot parse RAPID symbol properties from response " 

172 f"(symbolurl={symbolurl!r}): {text[:300]!r}" 

173 ) 

174 

175 return SymbolProperties( 

176 symbolurl=_extract_span(text, "symburl") or symbolurl, 

177 symtyp=symtyp or "", 

178 dattyp=dattyp, 

179 ndim=int(ndim_raw), 

180 dim=_parse_dim(dim_raw), 

181 local=_parse_bool_span(text, "local", default=True), 

182 readonly=_parse_bool_span(text, "ro", default=False), 

183 ) 

184 

185 

186async def get_symbol_properties( 

187 client: RWSClient, 

188 *, 

189 symbolurl: str, 

190) -> SymbolProperties: 

191 """Read and parse the properties of a RAPID symbol. 

192 

193 Wraps ``get_rapid_symbol_properties`` and parses the ABB XML response 

194 into a typed ``SymbolProperties``. 

195 

196 Route (delegated): ``GET /rw/rapid/symbol/properties/{symbolurl}`` 

197 

198 ABB constraints: 

199 - Not supported in bootserver mode. 

200 - No mastership required for reads. 

201 

202 Args: 

203 client: Open ``RWSClient`` instance. 

204 symbolurl: Full RAPID symbol path, e.g. 

205 ``"RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools"``. 

206 

207 Returns: 

208 Parsed symbol properties, including array dimensions. 

209 

210 Raises: 

211 RWSAuthenticationError: On HTTP 401. 

212 RWSNotFoundError: On HTTP 404. 

213 RWSHTTPError: On any other HTTP >= 400. 

214 ValueError: If the response body cannot be parsed. 

215 

216 Example: 

217 ```python 

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

219 props = await get_symbol_properties( 

220 client, 

221 symbolurl="RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools", 

222 ) 

223 print(props.ndim, props.dim) 

224 ``` 

225 """ 

226 response = await get_rapid_symbol_properties(client, symbolurl=symbolurl) 

227 return _parse_symbol_properties(response, symbolurl) 

228 

229 

230async def get_array_length( 

231 client: RWSClient, 

232 *, 

233 symbolurl: str, 

234 dimension: int = 0, 

235) -> int: 

236 """Read the size of one dimension of a RAPID array symbol. 

237 

238 Convenience wrapper over ``get_symbol_properties`` for the common case 

239 of discovering a one-based array's usable upper bound at runtime 

240 (e.g. ``trajTools{N}`` where ``N`` is cell-dependent). 

241 

242 Route (delegated): ``GET /rw/rapid/symbol/properties/{symbolurl}`` 

243 

244 ABB constraints: 

245 - The symbol must be declared as an array (``ndim >= 1``). 

246 - RAPID arrays are one-based; the returned length is the number of 

247 valid indexes ``1..length``. 

248 

249 Args: 

250 client: Open ``RWSClient`` instance. 

251 symbolurl: Full RAPID symbol path of the array variable, e.g. 

252 ``"RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools"``. 

253 dimension: Zero-based index into ``SymbolProperties.dim`` for 

254 multi-dimensional arrays. Defaults to ``0`` (first dimension). 

255 

256 Returns: 

257 Size of the requested dimension. 

258 

259 Raises: 

260 RWSAuthenticationError: On HTTP 401. 

261 RWSNotFoundError: On HTTP 404. 

262 RWSHTTPError: On any other HTTP >= 400. 

263 ValueError: If the symbol is not an array (``ndim == 0``), or if 

264 ``dimension`` is out of range for the symbol's declared 

265 dimensions. 

266 

267 Example: 

268 ```python 

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

270 n = await get_array_length( 

271 client, 

272 symbolurl="RAPID/T_ROB1/TRAJCENTER_CellConfig/trajTools", 

273 ) 

274 print("trajTools has", n, "entries") 

275 ``` 

276 """ 

277 props = await get_symbol_properties(client, symbolurl=symbolurl) 

278 

279 if props.ndim == 0: 

280 raise ValueError(f"Symbol {symbolurl!r} is not an array (ndim=0)") 

281 

282 if dimension < 0 or dimension >= len(props.dim): 

283 raise ValueError( 

284 f"dimension={dimension} out of range for symbol {symbolurl!r} with dim={props.dim!r}" 

285 ) 

286 

287 length = props.dim[dimension] 

288 logger.debug("Array %s dimension %d length = %d", symbolurl, dimension, length) 

289 return length