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,6 +1,7 @@
import zmq
from robot_interface.endpoints.receiver_base import ReceiverBase
from robot_interface.state import state
class MainReceiver(ReceiverBase):
@@ -14,14 +15,20 @@ class MainReceiver(ReceiverBase):
:param port: The port to use.
:type port: int
"""
super(MainReceiver, self).__init__("main")
self.create_socket(zmq_context, zmq.REP, port)
super(MainReceiver, self).__init__("main", "json")
self.create_socket(zmq_context, zmq.REP, port, bind=False)
@staticmethod
def _handle_ping(message):
"""A simple ping endpoint. Returns the provided data."""
return {"endpoint": "ping", "data": message.get("data")}
@staticmethod
def _handle_port_negotiation(message):
endpoints = [socket.endpoint_description() for socket in state.sockets]
return {"endpoint": "negotiation/ports", "data": endpoints}
@staticmethod
def _handle_negotiation(message):
"""
@@ -33,7 +40,11 @@ class MainReceiver(ReceiverBase):
:return: A response dictionary with a 'ports' key containing a list of ports and their function.
:rtype: dict[str, list[dict]]
"""
# TODO: .../error on all endpoints?
# In the future, the sender could send information like the robot's IP address, etc.
if message["endpoint"] == "negotiation/ports":
return MainReceiver._handle_port_negotiation(message)
return {"endpoint": "negotiation/error", "data": "The requested endpoint is not implemented."}
def handle_message(self, message):
@@ -42,7 +53,7 @@ class MainReceiver(ReceiverBase):
if message["endpoint"] == "ping":
return self._handle_ping(message)
elif message["endpoint"] == "negotiation":
elif message["endpoint"].startswith("negotiation"):
return self._handle_negotiation(message)
return {"endpoint": "error", "data": "The requested endpoint is not supported."}