Skip to content

Commit f7b16a3

Browse files
committed
Add headers to ws connection
1 parent 055d507 commit f7b16a3

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/roslibpy/comm/comm_autobahn.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,17 @@
2323
class AutobahnRosBridgeProtocol(RosBridgeProtocol, WebSocketClientProtocol):
2424
def __init__(self, *args, **kwargs):
2525
super(AutobahnRosBridgeProtocol, self).__init__(*args, **kwargs)
26+
self.headers = {}
2627

2728
def onConnect(self, response):
2829
LOGGER.debug("Server connected: %s", response.peer)
2930

31+
def getHandshakeRequestHeaders(self):
32+
headers = super(AutobahnRosBridgeProtocol, self).getHandshakeRequestHeaders()
33+
for key, value in self.headers.items():
34+
headers.append((key, value))
35+
return headers
36+
3037
def onOpen(self):
3138
LOGGER.info("Connection to ROS ready.")
3239
self._manual_disconnect = False
@@ -62,13 +69,20 @@ class AutobahnRosBridgeClientFactory(EventEmitterMixin, ReconnectingClientFactor
6269

6370
protocol = AutobahnRosBridgeProtocol
6471

65-
def __init__(self, *args, **kwargs):
72+
def __init__(self, *args, headers=None, **kwargs):
6673
super(AutobahnRosBridgeClientFactory, self).__init__(*args, **kwargs)
74+
self.headers = headers or {}
6775
self._proto = None
6876
self._manager = None
6977
self.connector = None
7078
self.setProtocolOptions(closeHandshakeTimeout=5)
7179

80+
def buildProtocol(self, addr):
81+
proto = self.protocol()
82+
proto.factory = self
83+
proto.headers = self.headers
84+
return proto
85+
7286
def connect(self):
7387
"""Establish WebSocket connection to the ROS server defined for this factory."""
7488
self.connector = connectWS(self)

src/roslibpy/ros.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,13 @@ class Ros(object):
3232
host (:obj:`str`): Name or IP address of the ROS bridge host, e.g. ``127.0.0.1``.
3333
port (:obj:`int`): ROS bridge port, e.g. ``9090``.
3434
is_secure (:obj:`bool`): ``True`` to use a secure web sockets connection, otherwise ``False``.
35+
headers (:obj:`dict`): Additional headers to include in the WebSocket connection.
3536
"""
3637

37-
def __init__(self, host, port=None, is_secure=False):
38+
def __init__(self, host, port=None, is_secure=False, headers=None):
3839
self._id_counter = 0
3940
url = RosBridgeClientFactory.create_url(host, port, is_secure)
40-
self.factory = RosBridgeClientFactory(url)
41+
self.factory = RosBridgeClientFactory(url, headers=headers)
4142
self.is_connecting = False
4243
self.connect()
4344

0 commit comments

Comments
 (0)