rosbridge.py
Go to the documentation of this file.
1 import websocket
2 import thread
3 
4 import json
5 import traceback
6 import time
7 
8 import string
9 import random
10 
11 
13  def __init__(self, host, port):
14  self.callbacks = {}
16  self.resp = None
17  self.connection = RosbridgeWSConnection(host, port)
18  self.connection.registerCallback(self.onMessageReceived)
19 
20  def publish(self, topic, obj):
21  pub = {"op": "publish", "topic": topic, "msg": obj}
22  self.send(pub)
23 
24  def subscribe(self, topic, callback, throttle_rate=-1):
25  if self.addCallback(topic, callback):
26  sub = {"op": "subscribe", "topic": topic}
27  if throttle_rate > 0:
28  sub['throttle_rate'] = throttle_rate
29 
30  self.send(sub)
31 
32  def unhook(self, callback):
33  keys_for_deletion = []
34  for key, values in self.callbacks.iteritems():
35  for value in values:
36  if callback == value:
37  print "Found!"
38  values.remove(value)
39  if len(values) == 0:
40  keys_for_deletion.append(key)
41 
42  for key in keys_for_deletion:
43  self.unsubscribe(key)
44  self.callbacks.pop(key)
45 
46  def unsubscribe(self, topic):
47  unsub = {"op": "unsubscribe", "topic": topic}
48  self.send(unsub)
49 
50  def callService(self, serviceName, callback=None, msg=None):
51  id = self.generate_id()
52  call = {"op": "call_service", "id": id, "service": serviceName}
53  if msg != None:
54  call['args'] = msg
55 
56  if callback == None:
57  self.resp = None
58 
59  def internalCB(msg):
60  self.resp = msg
61  return None
62 
63  self.addServiceCallback(id, internalCB)
64  self.send(call)
65 
66  while self.resp == None:
67  time.sleep(0.01)
68 
69  return self.resp
70 
71  self.addServiceCallback(id, callback)
72  self.send(call)
73  return None
74 
75  def send(self, obj):
76  try:
77  self.connection.sendString(json.dumps(obj))
78  except:
79  traceback.print_exc()
80  raise
81 
82  def generate_id(self, chars=16):
83  return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(chars))
84 
85  def addServiceCallback(self, id, callback):
86  self.service_callbacks[id] = callback
87 
88  def addCallback(self, topic, callback):
89  if self.callbacks.has_key(topic):
90  self.callbacks[topic].append(callback)
91  return False
92 
93  self.callbacks[topic] = [callback]
94  return True
95 
96  def is_connected(self):
97  return self.connection.connected
98 
99  def is_errored(self):
100  return self.connection.errored
101 
102  def onMessageReceived(self, message):
103  try:
104  # Load the string into a JSON object
105  obj = json.loads(message)
106  # print "Received: ", obj
107 
108  if obj.has_key('op'):
109  option = obj['op']
110  if option == "publish": # A message from a topic we have subscribed to..
111  topic = obj["topic"]
112  msg = obj["msg"]
113  if self.callbacks.has_key(topic):
114  for callback in self.callbacks[topic]:
115  try:
116  callback(msg)
117  except:
118  print "exception on callback", callback, "from", topic
119  traceback.print_exc()
120  raise
121  elif option == "service_response":
122  if obj.has_key("id"):
123  id = obj["id"]
124  values = obj["values"]
125  if self.service_callbacks.has_key(id):
126  try:
127  # print 'id:', id, 'func:', self.service_callbacks[id]
128  self.service_callbacks[id](values)
129  except:
130  print "exception on callback ID:", id
131  traceback.print_exc()
132  raise
133  else:
134  print "Missing ID!"
135  else:
136  print "Recieved unknown option - it was: ", option
137  else:
138  print "No OP key!"
139  except:
140  print "exception in onMessageReceived"
141  print "message", message
142  traceback.print_exc()
143  raise
144 
145 
147  def __init__(self, host, port):
148  self.ws = websocket.WebSocketApp(
149  ("ws://%s:%d/" % (host, port)), on_message=self.on_message, on_error=self.on_error, on_close=self.on_close
150  )
151  self.ws.on_open = self.on_open
152  self.run_thread = thread.start_new_thread(self.run, ())
153  self.connected = False
154  self.errored = False
155  self.callbacks = []
156 
157  def on_open(self, ws):
158  print "### ROS bridge connected ###"
159  self.connected = True
160 
161  def sendString(self, message):
162  if not self.connected:
163  print "Error: not connected, could not send message"
164  # TODO: throw exception
165  else:
166  self.ws.send(message)
167 
168  def on_error(self, ws, error):
169  self.errored = True
170  print "Error: %s" % error
171 
172  def on_close(self, ws):
173  self.connected = False
174  print "### ROS bridge closed ###"
175 
176  def run(self, *args):
177  self.ws.run_forever()
178 
179  def on_message(self, ws, message):
180  # Call the handlers
181  for callback in self.callbacks:
182  callback(message)
183 
184  def registerCallback(self, callback):
185  self.callbacks.append(callback)
def unhook(self, callback)
Definition: rosbridge.py:32
def onMessageReceived(self, message)
Definition: rosbridge.py:102
def addServiceCallback(self, id, callback)
Definition: rosbridge.py:85
def subscribe(self, topic, callback, throttle_rate=-1)
Definition: rosbridge.py:24
def addCallback(self, topic, callback)
Definition: rosbridge.py:88
def generate_id(self, chars=16)
Definition: rosbridge.py:82
def __init__(self, host, port)
Definition: rosbridge.py:13
def callback(msg)
Definition: rep117_filter.py:9
def publish(self, topic, obj)
Definition: rosbridge.py:20
def callService(self, serviceName, callback=None, msg=None)
Definition: rosbridge.py:50


mir_driver
Author(s): Martin Günther
autogenerated on Wed Mar 22 2023 02:18:51