handler.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import math
4 import rospy
5 import rosservice
6 import roslib
7 
8 import rosweb
9 import threading
10 
11 import cv
12 from cv_bridge import CvBridge
13 
14 subscriptions = {}
15 images = {}
16 sub_lock = threading.Lock()
17 
18 def config_plugin(context):
19  context.register_handler("/image", image_handler)
20 
21 def image_callback(msg, t):
22  (topic, cond) = t
23  bridge = CvBridge()
24  img = bridge.imgmsg_to_cv(msg, "bgr8")
25  data = cv.EncodeImage(".jpeg", img).tostring()
26  #convert to jpeg
27  cond.acquire()
28  images[topic].append(data)
29  cond.notifyAll()
30  cond.release()
31 
32 def image_handler(self, path, qdict):
33  global images
34  topic = qdict.get('topic', [''])[0]
35  if not topic:
36  return False
37  m = roslib.scriptutil.get_master()
38  code, _, topics = m.getPublishedTopics('/'+rosweb.PKG_NAME, '/')
39  if code != 1:
40  raise rosweb.ROSWebException("unable to communicate with master")
41 
42  for t, topic_type in topics:
43  if t == topic:
44  break
45  else:
46  raise rosweb.ROSWebException("%s is not a published topic" % topic)
47 
48  msg_class = roslib.message.get_message_class(topic_type)
49  sub_lock.acquire()
50  if topic in subscriptions:
51  cond = subscriptions[topic][1]
52  else:
53  cond = threading.Condition()
54  images[topic] = []
55  subscriptions[topic] = (rospy.Subscriber(topic, msg_class, image_callback, (topic, cond)), cond)
56  sub_lock.release()
57 
58  self.send_response(200)
59  self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=--myboundary')
60  self.end_headers()
61  while 1:
62  cond.acquire()
63  while len(images[topic]) == 0:
64  #print "waiting for an image"
65  cond.wait()
66  try:
67  if len(images[topic]) > 0:
68  data = images[topic][-1]
69  images[topic] = []
70  self.wfile.write('--myboundary\r\n')
71  self.wfile.write('Content-Type: image/jpeg\r\n')
72  self.wfile.write('Content-Length: %s\r\n' % len(data))
73  self.wfile.write('\r\n')
74  self.wfile.write(data)
75  except:
76  pass
77  cond.release()
78 
79  return True
80 
def config_plugin(context)
Definition: handler.py:18
def image_callback(msg, t)
Definition: handler.py:21
def image_handler(self, path, qdict)
Definition: handler.py:32


image_stream
Author(s): Rob Wheeler
autogenerated on Mon Jun 10 2019 15:51:21