feat: implement negotiation

By implementing SocketBase and adding the socket to the state, the negotiation will automatically give the right endpoints.

ref: N25B-168
This commit is contained in:
Twirre Meulenbelt
2025-10-13 22:06:27 +02:00
parent 7cfa6b44e8
commit c6916470e9
5 changed files with 86 additions and 13 deletions

View File

@@ -1,5 +1,9 @@
from abc import ABCMeta
import zmq
from robot_interface.utils import zmq_socket_type_int_to_str, zmq_socket_type_complement
class SocketBase(object):
__metaclass__ = ABCMeta
@@ -7,15 +11,21 @@ class SocketBase(object):
name = None
socket = None
def __init__(self, name):
def __init__(self, name, data_type):
"""
:param name: The name of the endpoint.
:type name: str
:param data_type: The data type of the endpoint, e.g. "json", "binary", "text", etc.
:type data_type: str
"""
self.name = name
self.socket = None
self.data_type = data_type
self.port = None # Set later by `create_socket`
self.socket = None # Set later by `create_socket`
self.bound = None # Set later by `create_socket`
def create_socket(self, zmq_context, socket_type, port):
def create_socket(self, zmq_context, socket_type, port, bind=True):
"""
Create a ZeroMQ socket.
@@ -27,12 +37,35 @@ class SocketBase(object):
:param port: The port to use.
:type port: int
:param bind: Whether to bind the socket or connect to it.
:type bind: bool
"""
self.port = port
self.socket = zmq_context.socket(socket_type)
self.socket.connect("tcp://localhost:{}".format(port))
self.bound = bind
if bind:
self.socket.bind("tcp://*:{}".format(port))
else:
self.socket.connect("tcp://localhost:{}".format(port))
def close(self):
"""Close the ZeroMQ socket."""
if not self.socket: return
self.socket.close()
self.socket = None
def endpoint_description(self):
"""
Description of the endpoint. Used for negotiation.
:return: A dictionary with the following keys: name, port, pattern, data_type. See https://utrechtuniversity.youtrack.cloud/articles/N25B-A-14/RI-CB-Communication#negotiation
:rtype: dict
"""
return {
"name": self.name,
"port": self.port,
"pattern": zmq_socket_type_int_to_str[zmq_socket_type_complement[self.socket.getsockopt(zmq.TYPE)]],
"data_type": self.data_type,
"bind": not self.bound
}