Skip to content

Commit

Permalink
blacken 🖤
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzalocasas committed Mar 27, 2024
1 parent 8457dd7 commit a73cb0b
Show file tree
Hide file tree
Showing 13 changed files with 319 additions and 209 deletions.
117 changes: 52 additions & 65 deletions src/compas_rrc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,9 @@
__copyright__,
__license__,
__url__,
__version__
)
from compas_rrc.client import (
AbbClient,
RosClient
__version__,
)
from compas_rrc.client import AbbClient, RosClient
from compas_rrc.common import (
CLIENT_PROTOCOL_VERSION,
ExecutionLevel,
Expand All @@ -99,7 +96,7 @@
FutureResult,
InstructionException,
RobotJoints,
TimeoutException
TimeoutException,
)
from compas_rrc.custom import CustomInstruction
from compas_rrc.io import (
Expand All @@ -109,15 +106,9 @@
ReadGroup,
SetAnalog,
SetDigital,
SetGroup
)
from compas_rrc.motion import (
Motion,
MoveToFrame,
MoveToJoints,
MoveToRobtarget,
Zone
SetGroup,
)
from compas_rrc.motion import Motion, MoveToFrame, MoveToJoints, MoveToRobtarget, Zone
from compas_rrc.msg import PrintText
from compas_rrc.utility import (
Debug,
Expand All @@ -130,58 +121,54 @@
SetTool,
SetWorkObject,
Stop,
WaitTime
)
from compas_rrc.watch import (
ReadWatch,
StartWatch,
StopWatch
WaitTime,
)
from compas_rrc.watch import ReadWatch, StartWatch, StopWatch

__all_plugins__ = ['compas_rrc.__install']
__all_plugins__ = ["compas_rrc.__install"]
__all__ = [
'__url__',
'__version__',
'__author__',
'__author_email__',
'__license__',
'__copyright__',
'CLIENT_PROTOCOL_VERSION',
'FeedbackLevel',
'ExecutionLevel',
'InstructionException',
'TimeoutException',
'FutureResult',
'ExternalAxes',
'RobotJoints',
'RosClient',
'AbbClient',
'SetDigital',
'SetAnalog',
'SetGroup',
'PulseDigital',
'ReadAnalog',
'ReadDigital',
'ReadGroup',
'Zone',
'Motion',
'MoveToJoints',
'MoveToFrame',
'MoveToRobtarget',
'PrintText',
'CustomInstruction',
'Noop',
'GetFrame',
'GetJoints',
'GetRobtarget',
'SetAcceleration',
'SetTool',
'SetMaxSpeed',
'Stop',
'WaitTime',
'SetWorkObject',
'Debug',
'ReadWatch',
'StartWatch',
'StopWatch',
"__url__",
"__version__",
"__author__",
"__author_email__",
"__license__",
"__copyright__",
"CLIENT_PROTOCOL_VERSION",
"FeedbackLevel",
"ExecutionLevel",
"InstructionException",
"TimeoutException",
"FutureResult",
"ExternalAxes",
"RobotJoints",
"RosClient",
"AbbClient",
"SetDigital",
"SetAnalog",
"SetGroup",
"PulseDigital",
"ReadAnalog",
"ReadDigital",
"ReadGroup",
"Zone",
"Motion",
"MoveToJoints",
"MoveToFrame",
"MoveToRobtarget",
"PrintText",
"CustomInstruction",
"Noop",
"GetFrame",
"GetJoints",
"GetRobtarget",
"SetAcceleration",
"SetTool",
"SetMaxSpeed",
"Stop",
"WaitTime",
"SetWorkObject",
"Debug",
"ReadWatch",
"StartWatch",
"StopWatch",
]
4 changes: 2 additions & 2 deletions src/compas_rrc/__install.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import compas.plugins


@compas.plugins.plugin(category='install')
@compas.plugins.plugin(category="install")
def installable_rhino_packages():
return ['compas_rrc']
return ["compas_rrc"]
27 changes: 18 additions & 9 deletions src/compas_rrc/__version__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
__title__ = 'compas_rrc'
__description__ = 'COMPAS RRC: Library for ABB Robots'
__url__ = 'https://github.com/compas-rrc/compas_rrc'
__version__ = '1.1.0'
__author__ = 'ETH Zurich'
__author_email__ = '[email protected]'
__license__ = 'MIT license'
__copyright__ = 'Copyright 2019 ETH Zurich'
__title__ = "compas_rrc"
__description__ = "COMPAS RRC: Library for ABB Robots"
__url__ = "https://github.com/compas-rrc/compas_rrc"
__version__ = "1.1.0"
__author__ = "ETH Zurich"
__author_email__ = "[email protected]"
__license__ = "MIT license"
__copyright__ = "Copyright 2019 ETH Zurich"

__all__ = ['__author__', '__author_email__', '__copyright__', '__description__', '__license__', '__title__', '__url__', '__version__']
__all__ = [
"__author__",
"__author_email__",
"__copyright__",
"__description__",
"__license__",
"__title__",
"__url__",
"__version__",
]
99 changes: 66 additions & 33 deletions src/compas_rrc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,23 @@
from .common import FutureResult
from .common import InstructionException

__all__ = ['RosClient', 'AbbClient']
__all__ = ["RosClient", "AbbClient"]


FEEDBACK_ERROR_PREFIX = 'Done FError '
FEEDBACK_ERROR_PREFIX = "Done FError "


def _get_key(message):
return 'msg:{}'.format(message.sequence_id)
return "msg:{}".format(message.sequence_id)


def _get_response_key(message):
return 'msg:{}'.format(message['feedback_id'])
return "msg:{}".format(message["feedback_id"])


class SequenceCounter(object):
"""An atomic, thread-safe sequence increament counter."""

ROLLOVER_THRESHOLD = 1000000

def __init__(self, start=0):
Expand All @@ -49,7 +50,7 @@ def value(self):


def default_feedback_parser(result):
feedback_value = result['feedback']
feedback_value = result["feedback"]

if feedback_value.startswith(FEEDBACK_ERROR_PREFIX):
return InstructionException(feedback_value, result)
Expand Down Expand Up @@ -103,7 +104,7 @@ class AbbClient(object):
"""

def __init__(self, ros, namespace='/rob1'):
def __init__(self, ros, namespace="/rob1"):
"""Initialize a new robot client instance.
Parameters
Expand All @@ -116,53 +117,77 @@ def __init__(self, ros, namespace='/rob1'):
"""
self.ros = ros
self.counter = SequenceCounter()
if not namespace.endswith('/'):
namespace += '/'
if not namespace.endswith("/"):
namespace += "/"
self._version_checked = False
self._server_protocol_check = dict(event=threading.Event(),
param=roslibpy.Param(ros, namespace + 'protocol_version'),
version=None)
self._server_protocol_check = dict(
event=threading.Event(),
param=roslibpy.Param(ros, namespace + "protocol_version"),
version=None,
)
self.ros.on_ready(self.version_check)
self.topic = roslibpy.Topic(ros, namespace + 'robot_command', 'compas_rrc_driver/RobotMessage', queue_size=None)
self.feedback = roslibpy.Topic(ros, namespace + 'robot_response', 'compas_rrc_driver/RobotMessage', queue_size=0)
self.topic = roslibpy.Topic(
ros,
namespace + "robot_command",
"compas_rrc_driver/RobotMessage",
queue_size=None,
)
self.feedback = roslibpy.Topic(
ros,
namespace + "robot_response",
"compas_rrc_driver/RobotMessage",
queue_size=0,
)
self.feedback.subscribe(self.feedback_callback)
self.topic.advertise()
self.futures = {}

self.ros.on('closing', self._disconnect_topics)
self.ros.on("closing", self._disconnect_topics)

def version_check(self):
"""Check if the protocol version on the server matches the protocol version on the client."""
self._server_protocol_check['version'] = self._server_protocol_check['param'].get()
self._server_protocol_check["version"] = self._server_protocol_check[
"param"
].get()
# No version is usually caused by wrong namespace in the connection, check that and raise correct error
if self._server_protocol_check['version'] is None:
if self._server_protocol_check["version"] is None:
params = self.ros.get_params()

detected_namespaces = set()
tentative_namespaces = set()
for param in params:
if param.endswith('/robot_state_port') or param.endswith('/protocol_version'):
namespace = param[:param.rindex('/')]
if param.endswith("/robot_state_port") or param.endswith(
"/protocol_version"
):
namespace = param[: param.rindex("/")]
if namespace not in tentative_namespaces:
tentative_namespaces.add(namespace)
else:
detected_namespaces.add(namespace)

raise Exception('Cannot find the specified namespace. Detected namespaces={}'.format(sorted(detected_namespaces)))
raise Exception(
"Cannot find the specified namespace. Detected namespaces={}".format(
sorted(detected_namespaces)
)
)

self._server_protocol_check['event'].set()
self._server_protocol_check["event"].set()

def ensure_protocol_version(self):
"""Ensure protocol version on the server matches the protocol version on the client."""
if self._version_checked:
return

if not self._server_protocol_check['version']:
if not self._server_protocol_check['event'].wait(10):
raise Exception('Could not yet retrieve server protocol version')
if not self._server_protocol_check["version"]:
if not self._server_protocol_check["event"].wait(10):
raise Exception("Could not yet retrieve server protocol version")

if self._server_protocol_check['version'] != CLIENT_PROTOCOL_VERSION:
raise Exception('Protocol version mismatch. Server={}, Client={}'.format(self._server_protocol_check['version'], CLIENT_PROTOCOL_VERSION))
if self._server_protocol_check["version"] != CLIENT_PROTOCOL_VERSION:
raise Exception(
"Protocol version mismatch. Server={}, Client={}".format(
self._server_protocol_check["version"], CLIENT_PROTOCOL_VERSION
)
)

self._version_checked = True

Expand Down Expand Up @@ -227,7 +252,11 @@ def send(self, instruction):

if instruction.feedback_level > 0:
result = FutureResult()
parser = instruction.parse_feedback if hasattr(instruction, 'parse_feedback') else None
parser = (
instruction.parse_feedback
if hasattr(instruction, "parse_feedback")
else None
)
self.futures[key] = dict(result=result, parser=parser)

self.topic.publish(roslibpy.Message(instruction.msg))
Expand Down Expand Up @@ -292,7 +321,11 @@ def send_and_subscribe(self, instruction, callback):

key = _get_key(instruction)

parser = instruction.parse_feedback if hasattr(instruction, 'parse_feedback') else None
parser = (
instruction.parse_feedback
if hasattr(instruction, "parse_feedback")
else None
)
self.futures[key] = dict(callback=callback, parser=parser)

self.topic.publish(roslibpy.Message(instruction.msg))
Expand All @@ -304,13 +337,13 @@ def feedback_callback(self, message):

if future:
result = message
if future['parser']:
result = future['parser'](result)
if future["parser"]:
result = future["parser"](result)
else:
result = default_feedback_parser(result)
if 'result' in future:
future['result']._set_result(result)
if "result" in future:
future["result"]._set_result(result)
self.futures.pop(response_key)
elif 'callback' in future:
future['callback'](result)
elif "callback" in future:
future["callback"](result)
# TODO: Handle unsubscribes
11 changes: 9 additions & 2 deletions src/compas_rrc/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from compas_rrc.common import ExecutionLevel
from compas_rrc.common import FeedbackLevel

__all__ = ['CustomInstruction']
__all__ = ["CustomInstruction"]


class CustomInstruction(ROSmsg):
Expand All @@ -24,7 +24,14 @@ class CustomInstruction(ROSmsg):
"""

def __init__(self, name, string_values=[], float_values=[], feedback_level=FeedbackLevel.NONE, execution_level=ExecutionLevel.ROBOT):
def __init__(
self,
name,
string_values=[],
float_values=[],
feedback_level=FeedbackLevel.NONE,
execution_level=ExecutionLevel.ROBOT,
):
"""Create a new instance of the instruction.
Parameters
Expand Down
Loading

0 comments on commit a73cb0b

Please sign in to comment.