Coverage for abb_rws_client_python_rw6/core/serializers.py: 96%

96 statements  

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

1# abb_rws_client/core/serializers.py 

2""" 

3Serialization / deserialization of RAPID types ↔ RWS format. 

4 

5Author: Clement RACINET 

6 

7RWS format for a robtarget (compact string, no spaces):: 

8 

9 [[x,y,z],[q1,q2,q3,q4],[cf1,cf4,cf6,cfx],[eax_a,eax_b,eax_c,eax_d,eax_e,eax_f]] 

10 

11ABB quaternion convention : [w, x, y, z] (scalar first) 

12Inactive external axis : 9E+9 

13""" 

14 

15from __future__ import annotations 

16 

17from dataclasses import dataclass, field 

18import re 

19from typing import TypeAlias 

20 

21from abb_rws_client_python_rw6.core.exceptions import RWSValueError 

22 

23#: ABB sentinel value for an inactive external axis 

24_INACTIVE_AXIS = 9e9 

25_INACTIVE_AXIS_STR = "9E+9" 

26 

27_ROBTARGET_RE = re.compile( 

28 r"^\[\s*" 

29 r"\[([^\]]+)\]\s*,\s*" 

30 r"\[([^\]]+)\]\s*,\s*" 

31 r"\[([^\]]+)\]\s*,\s*" 

32 r"\[([^\]]+)\]\s*" 

33 r"\]\s*$" 

34) 

35 

36#: Set of RAPID types supported by the serialization layer 

37_RAPID_TYPES = frozenset({"num", "bool", "string", "robtarget"}) 

38 

39 

40@dataclass 

41class RobTarget: 

42 """Python representation of an ABB robtarget. 

43 

44 Attributes: 

45 x: Cartesian X position (mm). 

46 y: Cartesian Y position (mm). 

47 z: Cartesian Z position (mm). 

48 qw: Orientation quaternion — scalar component (ABB convention: scalar first). 

49 qx: Orientation quaternion — X component. 

50 qy: Orientation quaternion — Y component. 

51 qz: Orientation quaternion — Z component. 

52 cf1: Robot configuration — axis 1 quadrant. 

53 cf4: Robot configuration — axis 4 quadrant. 

54 cf6: Robot configuration — axis 6 quadrant. 

55 cfx: Robot configuration — extended quadrant. 

56 eax: External axes (exactly 6 values; use ``9E+9`` for inactive axes). 

57 

58 Raises: 

59 RWSValueError: If ``eax`` does not contain exactly 6 values. 

60 

61 Example: 

62 ```python 

63 >>> rt = RobTarget(x=100.0, y=200.0, z=300.0) 

64 >>> rt.eax 

65 [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0] 

66 ``` 

67 """ 

68 

69 x: float = 0.0 

70 y: float = 0.0 

71 z: float = 0.0 

72 qw: float = 1.0 

73 qx: float = 0.0 

74 qy: float = 0.0 

75 qz: float = 0.0 

76 cf1: float = 0.0 

77 cf4: float = 0.0 

78 cf6: float = 0.0 

79 cfx: float = 0.0 

80 eax: list[float] = field(default_factory=lambda: [_INACTIVE_AXIS] * 6) 

81 

82 def __post_init__(self) -> None: 

83 if len(self.eax) != 6: 

84 raise RWSValueError(f"eax must have exactly 6 values, got {len(self.eax)}") 

85 

86 

87RapidValue: TypeAlias = float | bool | str | RobTarget 

88 

89 

90def _fmt(value: float) -> str: 

91 """Format a float for RWS: integer string if possible, compact repr otherwise. 

92 

93 The inactive axis sentinel ``9E+9`` is always rendered as ``"9E+9"`` 

94 regardless of the integer-check branch. 

95 

96 Args: 

97 value: Float value to format. 

98 

99 Returns: 

100 Compact string representation suitable for a RWS payload. 

101 

102 Example: 

103 ```python 

104 >>> _fmt(100.0) 

105 '100' 

106 >>> _fmt(3.14) 

107 '3.14' 

108 >>> _fmt(9e9) 

109 '9E+9' 

110 ``` 

111 """ 

112 if value == _INACTIVE_AXIS: 

113 return _INACTIVE_AXIS_STR 

114 if value == int(value) and abs(value) < 1e15: 

115 return str(int(value)) 

116 return repr(value) 

117 

118 

119def _parse_floats(raw: str, expected: int, context: str) -> list[float]: 

120 """Parse a CSV string of floats with element count validation. 

121 

122 Args: 

123 raw: Comma-separated string of float values (e.g. ``"0,0,500"``). 

124 expected: Expected number of elements. 

125 context: Label used in error messages to identify the field 

126 (e.g. ``"trans"``, ``"rot"``). 

127 

128 Returns: 

129 List of parsed float values. 

130 

131 Raises: 

132 RWSValueError: If the element count does not match ``expected``, 

133 or if any element cannot be converted to float. 

134 

135 Example: 

136 ```python 

137 >>> _parse_floats("0,0,500", 3, "trans") 

138 [0.0, 0.0, 500.0] 

139 ``` 

140 """ 

141 parts = [p.strip() for p in raw.split(",")] 

142 if len(parts) != expected: 

143 raise RWSValueError(f"{context}: expected {expected} values, got {len(parts)} in {raw!r}") 

144 try: 

145 return [float(p) for p in parts] 

146 except ValueError as exc: 

147 raise RWSValueError(f"{context}: cannot parse float in {raw!r}") from exc 

148 

149 

150def robtarget_to_rws(rt: RobTarget) -> str: 

151 """Serialize a RobTarget into a compact RWS string. 

152 

153 Route: ``PUT /rw/rapid/symbol/data/RAPID/{task}/{module}/{symbol}`` 

154 

155 Args: 

156 rt: RobTarget instance to serialize. 

157 

158 Returns: 

159 Compact RWS string with no spaces, e.g.: 

160 ``"[[100,200,300],[1,0,0,0],[0,0,0,0],[9E+9,9E+9,9E+9,9E+9,9E+9,9E+9]]"`` 

161 

162 Example: 

163 ```python 

164 >>> robtarget_to_rws(RobTarget(x=100.0, y=200.0, z=300.0)) 

165 '[[100,200,300],[1,0,0,0],[0,0,0,0],[9E+9,9E+9,9E+9,9E+9,9E+9,9E+9]]' 

166 ``` 

167 """ 

168 trans = ",".join(_fmt(v) for v in (rt.x, rt.y, rt.z)) 

169 rot = ",".join(_fmt(v) for v in (rt.qw, rt.qx, rt.qy, rt.qz)) 

170 conf = ",".join(_fmt(v) for v in (rt.cf1, rt.cf4, rt.cf6, rt.cfx)) 

171 ext = ",".join(_fmt(v) for v in rt.eax) 

172 return f"[[{trans}],[{rot}],[{conf}],[{ext}]]" 

173 

174 

175def rws_to_robtarget(raw: str) -> RobTarget: 

176 """Deserialize a raw RWS string into a RobTarget instance. 

177 

178 Route: ``GET /rw/rapid/symbol/data/RAPID/{task}/{module}/{symbol}`` 

179 

180 Args: 

181 raw: Raw RWS string returned by the controller. 

182 

183 Returns: 

184 Populated RobTarget instance. 

185 

186 Raises: 

187 RWSValueError: If the string format is invalid or any value 

188 cannot be parsed as a float. 

189 

190 Example: 

191 ```python 

192 >>> rws_to_robtarget( 

193 ... "[[0,0,500],[1,0,0,0],[0,0,0,0],[9E+9,9E+9,9E+9,9E+9,9E+9,9E+9]]" 

194 ... ) 

195 RobTarget(x=0.0, y=0.0, z=500.0, ...) 

196 ``` 

197 """ 

198 m = _ROBTARGET_RE.match(raw.strip()) 

199 if not m: 

200 raise RWSValueError(f"Invalid robtarget string: {raw!r}") 

201 trans = _parse_floats(m.group(1), 3, "trans") 

202 rot = _parse_floats(m.group(2), 4, "rot") 

203 conf = _parse_floats(m.group(3), 4, "conf") 

204 ext = _parse_floats(m.group(4), 6, "eax") 

205 return RobTarget( 

206 x=trans[0], 

207 y=trans[1], 

208 z=trans[2], 

209 qw=rot[0], 

210 qx=rot[1], 

211 qy=rot[2], 

212 qz=rot[3], 

213 cf1=conf[0], 

214 cf4=conf[1], 

215 cf6=conf[2], 

216 cfx=conf[3], 

217 eax=ext, 

218 ) 

219 

220 

221def python_to_rapid_value(value: float | bool | str | RobTarget, rapid_type: str) -> str: 

222 """Convert a Python value to a RAPID string for the RWS API. 

223 

224 Args: 

225 value: Python value to convert. 

226 rapid_type: Target RAPID type: ``"num"``, ``"bool"``, 

227 ``"string"``, or ``"robtarget"``. 

228 

229 Returns: 

230 String in the format expected by RWS. 

231 

232 Raises: 

233 RWSValueError: Unknown RAPID type, or value incompatible 

234 with the requested type. 

235 

236 Example: 

237 ```python 

238 >>> python_to_rapid_value(3.14, "num") 

239 '3.14' 

240 >>> python_to_rapid_value(True, "bool") 

241 'TRUE' 

242 >>> python_to_rapid_value("hello", "string") 

243 'hello' 

244 ``` 

245 """ 

246 if rapid_type not in _RAPID_TYPES: 

247 raise RWSValueError( 

248 f"Unknown RAPID type: {rapid_type!r}. Expected one of {sorted(_RAPID_TYPES)}" 

249 ) 

250 if rapid_type == "num": 

251 # bool is a subclass of int — must be rejected explicitly 

252 if isinstance(value, bool) or not isinstance(value, int | float): 

253 raise RWSValueError(f"Expected int or float for 'num', got {type(value).__name__!r}") 

254 return str(int(value)) if float(value) == int(value) else repr(float(value)) 

255 if rapid_type == "bool": 

256 if not isinstance(value, bool): 

257 raise RWSValueError(f"Expected bool for 'bool', got {type(value).__name__!r}") 

258 return "TRUE" if value else "FALSE" 

259 if rapid_type == "string": 

260 if not isinstance(value, str): 260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true

261 raise RWSValueError(f"Expected str for 'string', got {type(value).__name__!r}") 

262 return value # no quotes: RWS handles encoding on the form-data side 

263 if rapid_type == "robtarget": 263 ↛ 267line 263 didn't jump to line 267 because the condition on line 263 was always true

264 if not isinstance(value, RobTarget): 

265 raise RWSValueError(f"Expected RobTarget for 'robtarget', got {type(value).__name__!r}") 

266 return robtarget_to_rws(value) 

267 raise RWSValueError(f"Unknown RAPID type: {rapid_type!r}") # unreachable — mypy guard 

268 

269 

270def rapid_value_to_python(raw: str, rapid_type: str) -> float | bool | str | RobTarget: 

271 """Convert a raw RWS string to a Python value according to the RAPID type. 

272 

273 Args: 

274 raw: Raw string returned by the RWS controller. 

275 rapid_type: RAPID type: ``"num"``, ``"bool"``, 

276 ``"string"``, or ``"robtarget"``. 

277 

278 Returns: 

279 Typed Python value. 

280 

281 Raises: 

282 RWSValueError: Conversion failed or unknown RAPID type. 

283 

284 Example: 

285 ```python 

286 >>> rapid_value_to_python("3.14", "num") 

287 3.14 

288 >>> rapid_value_to_python("TRUE", "bool") 

289 True 

290 >>> rapid_value_to_python("hello", "string") 

291 'hello' 

292 ``` 

293 """ 

294 if rapid_type not in _RAPID_TYPES: 

295 raise RWSValueError( 

296 f"Unknown RAPID type: {rapid_type!r}. Expected one of {sorted(_RAPID_TYPES)}" 

297 ) 

298 if rapid_type == "num": 

299 try: 

300 return float(raw) 

301 except ValueError as exc: 

302 raise RWSValueError(f"Cannot convert {raw!r} to num") from exc 

303 if rapid_type == "bool": 

304 normalized = raw.strip().lower() 

305 if normalized in {"true", "1", "yes"}: 

306 return True 

307 if normalized in {"false", "0", "no"}: 

308 return False 

309 raise RWSValueError(f"Cannot convert {raw!r} to bool") 

310 if rapid_type == "string": 

311 return raw # raw passthrough, no quote stripping 

312 if rapid_type == "robtarget": 312 ↛ 314line 312 didn't jump to line 314 because the condition on line 312 was always true

313 return rws_to_robtarget(raw) 

314 raise RWSValueError(f"Unknown RAPID type: {rapid_type!r}") # unreachable — mypy guard