Coverage for abb_rws_client_python_rw6/highlevel/variables.py: 98%

36 statements  

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

1# abb_rws_client/highlevel/variables.py 

2"""High-level RAPID variable read/write 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 re 

15 

16import httpx 

17 

18from abb_rws_client_python_rw6.core.client import RWSClient 

19from abb_rws_client_python_rw6.core.logger import get_logger 

20from abb_rws_client_python_rw6.rws.mastership import ( 

21 post_mastership_domain_release, 

22 post_mastership_domain_request, 

23) 

24from abb_rws_client_python_rw6.rws.rapid.symbol import ( 

25 get_rapid_symbol_data, 

26 update_rapid_variable_current_value, 

27) 

28 

29logger = get_logger(__name__) 

30 

31 

32def _parse_symbol_value(response: httpx.Response) -> str: 

33 """Extract the ``value`` field from a RAPID symbol data response. 

34 

35 Args: 

36 response: Raw HTTP response from ``get_rapid_symbol_data``. 

37 

38 Returns: 

39 The symbol value as a string (as returned by the controller). 

40 

41 Raises: 

42 ValueError: If the value cannot be extracted from the response body. 

43 

44 Example: 

45 ```python 

46 resp = await get_rapid_symbol_data(client, symbolurl="RAPID/T_ROB1/M/x") 

47 val = _parse_symbol_value(resp) 

48 # val == "42" 

49 ``` 

50 """ 

51 # JSON path: {"state": [{"value": "...", ...}]} 

52 try: 

53 data = response.json() 

54 states = data.get("state", []) 

55 if states and "value" in states[0]: 55 ↛ 61line 55 didn't jump to line 61 because the condition on line 55 was always true

56 return str(states[0]["value"]) 

57 except Exception: 

58 pass 

59 

60 # XML / HTML path: <span class="value">...</span> 

61 match = re.search( 

62 r'class=["\']value["\'][^>]*>([^<]+)<', 

63 response.text, 

64 ) 

65 if match: 

66 return match.group(1).strip() 

67 

68 raise ValueError(f"Cannot parse symbol value from response: {response.text[:200]}") 

69 

70 

71# --------------------------------------------------------------------------- 

72# Mastership-guarded variable write 

73# --------------------------------------------------------------------------- 

74 

75 

76async def set_variable_with_mastership( 

77 client: RWSClient, 

78 *, 

79 symbolurl: str, 

80 value: str, 

81 domain: str = "rapid", 

82) -> None: 

83 """Write a RAPID variable value, acquiring and releasing mastership. 

84 

85 Composes: 

86 

87 1. ``post_mastership_domain_request(domain, action="request")`` 

88 2. ``update_rapid_variable_current_value(action="set", value=value)`` 

89 3. ``post_mastership_domain_release(domain, action="release")`` 

90 

91 Mastership is **always** released in a ``finally`` block, even if 

92 the write fails, to avoid leaving the controller locked. 

93 

94 Route (delegated): 

95 - ``POST /rw/mastership/{domain}`` (action=request) 

96 - ``POST /rw/rapid/symbol/data/{symbolurl}`` (action=set) 

97 - ``POST /rw/mastership/{domain}`` (action=release) 

98 

99 ABB constraints: 

100 - Requires AUTO mode for mastership. 

101 - ``symbolurl`` format: ``RAPID/T_ROB1/MainModule/my_var`` 

102 - ``domain`` must be one of: ``"rapid"``, ``"cfg"``, ``"motion"``. 

103 

104 Args: 

105 client: Open ``RWSClient`` instance. 

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

107 ``"RAPID/T_ROB1/MainModule/counter"``. 

108 value: New value as a string. Numeric types must be 

109 pre-converted: ``str(42)``, ``str(3.14)``. 

110 domain: Mastership domain. Defaults to ``"rapid"``. 

111 

112 Returns: 

113 None. Expects HTTP 204 on the write call. 

114 

115 Raises: 

116 RWSAuthenticationError: On HTTP 401. 

117 RWSNotFoundError: On HTTP 404. 

118 RWSHTTPError: On any other HTTP >= 400. 

119 

120 Example: 

121 ```python 

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

123 await set_variable_with_mastership( 

124 client, 

125 symbolurl="RAPID/T_ROB1/MainModule/target_x", 

126 value="250.0", 

127 ) 

128 ``` 

129 """ 

130 # Acquire mastership on the specified domain 

131 await post_mastership_domain_request(client, domain=domain, action="request") 

132 try: 

133 await update_rapid_variable_current_value( 

134 client, 

135 symbolurl=symbolurl, 

136 action="set", 

137 value=value, 

138 ) 

139 logger.debug("Variable %s set to %r", symbolurl, value) 

140 finally: 

141 # Always release — even on exception — to avoid locking the controller 

142 await post_mastership_domain_release(client, domain=domain, action="release") 

143 

144 

145async def set_variables_with_mastership( 

146 client: RWSClient, 

147 *, 

148 values: dict[str, str], 

149 domain: str = "rapid", 

150) -> None: 

151 """Write multiple RAPID variables while holding mastership once. 

152 

153 Requests mastership a single time, writes every ``symbolurl -> value`` 

154 pair sequentially, then releases mastership in a ``finally`` block. 

155 More efficient than calling ``set_variable_with_mastership`` in a 

156 loop, which would request/release mastership once per variable. 

157 

158 Route (delegated): 

159 - ``POST /rw/mastership/{domain}`` (action=request) 

160 - ``POST /rw/rapid/symbol/data/{symbolurl}`` (action=set), once per entry 

161 - ``POST /rw/mastership/{domain}`` (action=release) 

162 

163 ABB constraints: 

164 - Requires AUTO mode for mastership. 

165 - ``domain`` must be one of: ``"rapid"``, ``"cfg"``, ``"motion"``. 

166 

167 Args: 

168 client: Open ``RWSClient`` instance. 

169 values: Mapping of ``symbolurl -> value``. Values must already 

170 be pre-converted to strings. 

171 domain: Mastership domain. Defaults to ``"rapid"``. 

172 

173 Returns: 

174 None. Expects HTTP 204 on each write call. 

175 

176 Raises: 

177 RWSAuthenticationError: On HTTP 401. 

178 RWSNotFoundError: On HTTP 404. 

179 RWSHTTPError: On any other HTTP >= 400 — mastership is still 

180 released before the exception propagates. 

181 

182 Example: 

183 ```python 

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

185 await set_variables_with_mastership( 

186 client, 

187 values={ 

188 "RAPID/T_ROB1/M/x": "1", 

189 "RAPID/T_ROB1/M/y": "2", 

190 }, 

191 ) 

192 ``` 

193 """ 

194 await post_mastership_domain_request(client, domain=domain, action="request") 

195 try: 

196 for symbolurl, value in values.items(): 

197 await update_rapid_variable_current_value( 

198 client, 

199 symbolurl=symbolurl, 

200 action="set", 

201 value=value, 

202 ) 

203 logger.debug("Variable %s set to %r", symbolurl, value) 

204 finally: 

205 await post_mastership_domain_release(client, domain=domain, action="release") 

206 

207 

208async def get_variable( 

209 client: RWSClient, 

210 *, 

211 symbolurl: str, 

212) -> str: 

213 """Read a RAPID variable value. 

214 

215 Wraps ``get_rapid_symbol_data`` and extracts the ``value`` field 

216 from the response body. 

217 

218 Route (delegated): ``GET /rw/rapid/symbol/data/{symbolurl}`` 

219 

220 ABB constraints: 

221 - No mastership required for reads. 

222 - ``symbolurl`` format: ``RAPID/T_ROB1/MainModule/my_var`` 

223 

224 Args: 

225 client: Open ``RWSClient`` instance. 

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

227 ``"RAPID/T_ROB1/MainModule/counter"``. 

228 

229 Returns: 

230 The variable value as a string, exactly as returned by the 

231 controller (e.g. ``"42"``, ``"TRUE"``, 

232 ``"[[250,0,300],[1,0,0,0],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]]"``). 

233 

234 Raises: 

235 RWSAuthenticationError: On HTTP 401. 

236 RWSNotFoundError: On HTTP 404. 

237 RWSHTTPError: On any other HTTP >= 400. 

238 ValueError: If the value cannot be parsed from the response. 

239 

240 Example: 

241 ```python 

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

243 val = await get_variable( 

244 client, 

245 symbolurl="RAPID/T_ROB1/MainModule/counter", 

246 ) 

247 print("counter =", val) 

248 ``` 

249 """ 

250 response = await get_rapid_symbol_data(client, symbolurl=symbolurl) 

251 return _parse_symbol_value(response)