Skip to content

Commit

Permalink
Merge pull request #9 from johnwason:remove_assert
Browse files Browse the repository at this point in the history
Raise exceptions with error messages instead of using assert and bump version to 0.3.1
  • Loading branch information
johnwason authored Apr 10, 2024
2 parents ad89855 + d080d81 commit 09778da
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 29 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setuptools.setup(
name='abb_robot_client',
version='0.3.0',
version='0.3.1',
description='Python client library to access ABB robots using RWS and EGM',
url='https://github.com/johnwason/abb_robot_client',
packages=setuptools.find_packages("src"),
Expand Down
41 changes: 27 additions & 14 deletions src/abb_robot_client/rws.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,8 @@ def start(self, cycle: Optional[str]='asis',tasks: Optional[List[str]]=['T_ROB1'

rob_tasks = self.get_tasks()
for t in tasks:
assert t in rob_tasks, f"Cannot start unknown task {t}"
if not t in rob_tasks:
raise Exception(f"Cannot start unknown task {t}")

for rob_task in rob_tasks.values():
if not rob_task.motiontask:
Expand Down Expand Up @@ -483,7 +484,8 @@ def read_file(self, filename: str) -> bytes:
"""
url="/".join([self.base_url, "fileservice", filename])
res=self._session.get(url, auth=self.auth)
assert res.ok, f"File not found {filename}"
if not res.ok:
raise Exception(f"File not found {filename}")
try:
return res.content
finally:
Expand All @@ -498,7 +500,8 @@ def upload_file(self, filename: str, contents: bytes):
"""
url="/".join([self.base_url, "fileservice" , filename])
res=self._session.put(url, contents, auth=self.auth)
assert res.ok, res.reason
if not res.ok:
raise Exception(res.reason)
res.close()

def delete_file(self, filename: str):
Expand Down Expand Up @@ -589,7 +592,8 @@ def get_jointtarget(self, mechunit="ROB_1") -> JointTarget:
"""
res_json=self._do_get("rw/motionsystem/mechunits/" + mechunit + "/jointtarget")
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "ms-jointtarget"
if not state["_type"] == "ms-jointtarget":
raise Exception("Invalid jointtarget type")
robjoint=np.array([state["rax_1"], state["rax_2"], state["rax_3"], state["rax_4"], state["rax_5"],
state["rax_6"]], dtype=np.float64)
extjoint=np.array([state["eax_a"], state["eax_b"], state["eax_c"], state["eax_d"], state["eax_e"],
Expand All @@ -610,7 +614,8 @@ def get_robtarget(self, mechunit='ROB_1', tool='tool0', wobj='wobj0', coordinate
"""
res_json=self._do_get(f"rw/motionsystem/mechunits/{mechunit}/robtarget?tool={tool}&wobj={wobj}&coordinate={coordinate}")
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "ms-robtargets"
if not state["_type"] == "ms-robtargets":
raise Exception("Invalid robtarget type")
trans=np.array([state["x"], state["y"], state["z"]], dtype=np.float64)
rot=np.array([state["q1"], state["q2"], state["q3"], state["q4"]], dtype=np.float64)
robconf=np.array([state["cf1"],state["cf4"],state["cf6"],state["cfx"]], dtype=np.float64)
Expand All @@ -625,8 +630,10 @@ def _rws_value_to_jointtarget(self, val):
return JointTarget(robax,extax)

def _jointtarget_to_rws_value(self, val):
assert np.shape(val[0]) == (6,)
assert np.shape(val[1]) == (6,)
if not np.shape(val[0]) == (6,):
raise Exception("Invalid jointtarget")
if not np.shape(val[1]) == (6,):
raise Exception("Invalid jointtarget")
robax=','.join([format(x, '.4f') for x in np.rad2deg(val[0])])
extax=','.join([format(x, '.4f') for x in np.rad2deg(val[1])])
rws_value="[[" + robax + "],[" + extax + "]]"
Expand Down Expand Up @@ -752,7 +759,8 @@ def read_ipc_message(self, queue_name: str, timeout: float=0) -> List[IpcMessage

res_json=self._do_get("rw/dipc/" + queue_name + "/?action=dipc-read" + timeout_str)
for state in res_json["_embedded"]["_state"]:
assert state["_type"] == "dipc-read-li"
if not state["_type"] == "dipc-read-li":
raise Exception("Invalid IPC message type")

o.append(IpcMessage(state["dipc-data"], state["dipc-userdef"],
state["dipc-msgtype"], state["dipc-cmd"], state["queue-name"]))
Expand All @@ -768,7 +776,8 @@ def get_speedratio(self) -> float:
"""
res_json=self._do_get(f"rw/panel/speedratio")
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "pnl-speedratio"
if not state["_type"] == "pnl-speedratio":
raise Exception("Invalid speedratio type")
return float(state["speedratio"])

def set_speedratio(self, speedratio: float):
Expand Down Expand Up @@ -839,7 +848,8 @@ def request_rmmp(self, timeout: float=5):

res_json=self._do_get('users/rmmp/poll?json=1')
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "user-rmmp-poll"
if not state["_type"] == "user-rmmp-poll":
raise Exception("Invalid rmmp poll type")
status = state["status"]
if status=="GRANTED":
self.poll_rmmp()
Expand Down Expand Up @@ -883,7 +893,8 @@ def poll_rmmp(self):
res=rmmp_session.get(url, auth=self.auth)
res_json=self._process_response(res)
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "user-rmmp-poll"
if not state["_type"] == "user-rmmp-poll":
raise Exception("Invalid rmmp poll type")

if old_rmmp_session is not None:
self._rmmp_session=rmmp_session
Expand Down Expand Up @@ -967,7 +978,7 @@ def subscribe(self, resources: List[SubscriptionResourceRequest], handler: Calla
unit = r.param.get("unit", "DRV_1")
payload[f"{payload_ind}"] = f'/rw/iosystem/signals/{network}/{unit}/{signal};state'
else:
assert False, "Invalid resource type"
raise Exception("Invalid resource type")
payload[f"{payload_ind}-p"] = f"{r.priority.value}"

payload["resources"] = [f"{i+1}" for i in range(payload_ind)]
Expand All @@ -980,10 +991,12 @@ def subscribe(self, resources: List[SubscriptionResourceRequest], handler: Calla
finally:
res1.close()

assert res1.status_code == 201, "Subscription creation failed"
if not res1.status_code == 201:
raise Exception("Subscription creation failed")

m = re.search(r'<a href="ws:\/\/.*(\/poll\/\d+)" rel="self">', res1.content.decode("ascii"))
assert m
if not m:
raise Exception("Invalid subscription response")
ws_url = self.base_url.replace("http:","ws:") + m.group(1)

cookie = f"ABBCX={self._session.cookies['ABBCX']}"
Expand Down
41 changes: 27 additions & 14 deletions src/abb_robot_client/rws_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ async def start(self, cycle: str='asis',tasks: List[str]=['T_ROB1']):
"""
rob_tasks = await self.get_tasks()
for t in tasks:
assert t in rob_tasks, f"Cannot start unknown task {t}"
if t not in rob_tasks
raise Exception(f"Cannot start unknown task {t}")

for rob_task in rob_tasks.values():
if not rob_task.motiontask:
Expand Down Expand Up @@ -333,7 +334,8 @@ async def read_file(self, filename: str) -> bytes:
"""
url="/".join([self.base_url, "fileservice", filename])
res=await self._session.get(url)
assert res.is_success, f"File not found {filename}"
if not res.is_success:
raise Exception(f"File not found {filename}")
try:
return res.content
finally:
Expand All @@ -348,7 +350,8 @@ async def upload_file(self, filename: str, contents: bytes) -> None:
"""
url="/".join([self.base_url, "fileservice" , filename])
res=await self._session.put(url, content=contents)
assert res.is_success, res.reason_phrase
if not res.is_success:
raise Exception(res.reason_phrase)
await res.aclose()

async def delete_file(self, filename: str) -> None:
Expand Down Expand Up @@ -439,7 +442,8 @@ async def get_jointtarget(self, mechunit: str="ROB_1"):
"""
res_json=await self._do_get("rw/motionsystem/mechunits/" + mechunit + "/jointtarget")
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "ms-jointtarget"
if not state["_type"] == "ms-jointtarget":
raise Exception("Invalid response from controller")
robjoint=np.array([state["rax_1"], state["rax_2"], state["rax_3"], state["rax_4"], state["rax_5"],
state["rax_6"]], dtype=np.float64)
extjoint=np.array([state["eax_a"], state["eax_b"], state["eax_c"], state["eax_d"], state["eax_e"],
Expand All @@ -460,7 +464,8 @@ async def get_robtarget(self, mechunit: str='ROB_1', tool: str='tool0', wobj: st
"""
res_json=await self._do_get(f"rw/motionsystem/mechunits/{mechunit}/robtarget?tool={tool}&wobj={wobj}&coordinate={coordinate}")
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "ms-robtargets"
if not state["_type"] == "ms-robtargets":
raise Exception("Invalid response from controller")
trans=np.array([state["x"], state["y"], state["z"]], dtype=np.float64)
rot=np.array([state["q1"], state["q2"], state["q3"], state["q4"]], dtype=np.float64)
robconf=np.array([state["cf1"],state["cf4"],state["cf6"],state["cfx"]], dtype=np.float64)
Expand All @@ -475,8 +480,10 @@ def _rws_value_to_jointtarget(self, val):
return JointTarget(robax,extax)

def _jointtarget_to_rws_value(self, val):
assert np.shape(val[0]) == (6,)
assert np.shape(val[1]) == (6,)
if not np.shape(val[0]) == (6,):
raise Exception("Invalid jointtarget")
if not np.shape(val[1]) == (6,):
raise Exception("Invalid jointtarget")
robax=','.join([format(x, '.4f') for x in np.rad2deg(val[0])])
extax=','.join([format(x, '.4f') for x in np.rad2deg(val[1])])
rws_value="[[" + robax + "],[" + extax + "]]"
Expand Down Expand Up @@ -603,7 +610,8 @@ async def read_ipc_message(self, queue_name: str, timeout: float=0) -> List[IpcM

res_json=await self._do_get("rw/dipc/" + queue_name + "/?action=dipc-read" + timeout_str)
for state in res_json["_embedded"]["_state"]:
assert state["_type"] == "dipc-read-li"
if not state["_type"] == "dipc-read-li":
raise Exception("Invalid response from controller")

o.append(IpcMessage(state["dipc-data"], state["dipc-userdef"],
state["dipc-msgtype"], state["dipc-cmd"], state["queue-name"]))
Expand Down Expand Up @@ -670,7 +678,8 @@ async def request_rmmp(self, timeout: float=5):

res_json=self._do_get('users/rmmp/poll?json=1')
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "user-rmmp-poll"
if not state["_type"] == "user-rmmp-poll":
raise Exception("Invalid response from controller")
status = state["status"]
if status=="GRANTED":
await self.poll_rmmp()
Expand Down Expand Up @@ -714,7 +723,8 @@ async def poll_rmmp(self):
res=await rmmp_session.get(url)
res_json=self._process_response(res)
state = res_json["_embedded"]["_state"][0]
assert state["_type"] == "user-rmmp-poll"
if not state["_type"] == "user-rmmp-poll":
raise Exception("Invalid response from controller")

if old_rmmp_session is not None:
self._rmmp_session=rmmp_session
Expand Down Expand Up @@ -787,7 +797,7 @@ async def subscribe(self, resources: List[SubscriptionResourceRequest]):
unit = r.param.get("unit", "DRV_1")
payload[f"{payload_ind}"] = f'/rw/iosystem/signals/{network}/{unit}/{signal};state'
else:
assert False, "Invalid resource type"
raise Exception("Invalid resource type")
payload[f"{payload_ind}-p"] = f"{r.priority.value}"

payload["resources"] = [f"{i+1}" for i in range(payload_ind)]
Expand All @@ -800,18 +810,21 @@ async def subscribe(self, resources: List[SubscriptionResourceRequest]):
finally:
await res1.aclose()

assert res1.status_code == 201, "Subscription creation failed"
if not res1.status_code == 201:
raise Exception("Subscription creation failed")

m = re.search(r'<a href="ws:\/\/.*(\/poll\/\d+)" rel="self">', res1.content.decode("ascii"))
assert m
if not m:
raise Exception("Invalid response from controller")
ws_url = self.base_url.replace("http:","ws:") + m.group(1)

cookie = f"-http-session-={self._session.cookies['-http-session-']}; ABBCX={self._session.cookies['ABBCX']}"

header={'Cookie': cookie}

async with self._websocket_lock:
assert self._websocket is None, "Subscription already created"
if not self._websocket is None:
raise Exception("Subscription already created")

self._websocket = await websockets.connect(
ws_url,
Expand Down

0 comments on commit 09778da

Please sign in to comment.