axis.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #
00003 # Axis camera image driver. Based on:
00004 # https://code.ros.org/svn/wg-ros-pkg/branches/trunk_cturtle/sandbox/axis_camera/axis.py
00005 #
00006 
00007 import os, sys, string, time
00008 import urllib2
00009 
00010 import roslib; roslib.load_manifest('axis_camera') 
00011 import rospy 
00012 
00013 from sensor_msgs.msg import CompressedImage, CameraInfo
00014 
00015 import threading
00016 import camera_info_manager
00017 
00018 class StreamThread(threading.Thread):
00019   def __init__(self, axis):
00020     threading.Thread.__init__(self)
00021 
00022     self.axis = axis
00023     self.daemon = True
00024 
00025   def run(self):
00026     while True:
00027       try:
00028         self.stream()
00029       except:
00030         import traceback
00031         traceback.print_exc()
00032       time.sleep(1)
00033 
00034   def stream(self):
00035     url = 'http://%s/mjpg/video.mjpg' % self.axis.hostname
00036     url = url + "?fps=0&resolultion=%dx%d" % (self.axis.width, self.axis.height)
00037 
00038     rospy.logdebug('opening ' + str(self.axis))
00039 
00040     # only try to authenticate if user/pass configured
00041     if self.axis.password != '' and self.axis.username != '':
00042       # create a password manager
00043       password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
00044 
00045       # Add the username and password, use default realm.
00046       top_level_url = "http://" + self.axis.hostname
00047       password_mgr.add_password(None, top_level_url,
00048                                 self.axis.username,
00049                                 self.axis.password)
00050       handler = urllib2.HTTPBasicAuthHandler(password_mgr)
00051 
00052       # create "opener" (OpenerDirector instance)
00053       opener = urllib2.build_opener(handler)
00054 
00055       # ...and install it globally so it can be used with urlopen.
00056       urllib2.install_opener(opener)
00057 
00058     fp = urllib2.urlopen(url)
00059 
00060     while True:
00061       boundary = fp.readline()
00062 
00063       header = {}
00064       while 1:
00065         line = fp.readline()
00066         if line == "\r\n": break
00067         line = line.strip()
00068 
00069         parts = line.split(": ", 1)
00070         header[parts[0]] = parts[1]
00071 
00072       content_length = int(header['Content-Length'])
00073 
00074       img = fp.read(content_length)
00075       line = fp.readline()
00076       
00077       msg = CompressedImage()
00078       msg.header.stamp = rospy.Time.now()
00079       msg.header.frame_id = self.axis.frame_id
00080       msg.format = "jpeg"
00081       msg.data = img
00082 
00083       self.axis.pub.publish(msg)
00084 
00085       cimsg = self.axis.cinfo.getCameraInfo()
00086       cimsg.header.stamp = msg.header.stamp
00087       cimsg.header.frame_id = self.axis.frame_id
00088       cimsg.width = self.axis.width
00089       cimsg.height = self.axis.height
00090       self.axis.caminfo_pub.publish(cimsg)
00091 
00092 class Axis:
00093   def __init__(self, hostname, username, password,
00094                width, height, frame_id, camera_info_url):
00095     self.hostname = hostname
00096     self.username = username
00097     self.password = password
00098     self.width = width
00099     self.height = height
00100     self.frame_id = frame_id
00101     self.camera_info_url = camera_info_url
00102 
00103     # generate a valid camera name based on the hostname
00104     self.cname = camera_info_manager.genCameraName(self.hostname)
00105     self.cinfo = camera_info_manager.CameraInfoManager(cname = self.cname,
00106                                                        url = self.camera_info_url)
00107     self.cinfo.loadCameraInfo()         # required before getCameraInfo()
00108     self.st = None
00109     self.pub = rospy.Publisher("image_raw/compressed", CompressedImage, self)
00110     self.caminfo_pub = rospy.Publisher("camera_info", CameraInfo, self)
00111 
00112   def __str__(self):
00113     """Return string representation."""
00114     return(self.hostname + ',' + self.username + ',' + self.password +
00115            '(' + str(self.width) + 'x' + str(self.height) + ')')
00116 
00117   def peer_subscribe(self, topic_name, topic_publish, peer_publish):
00118     # Lazy-start the image-publisher.
00119     if self.st is None:
00120       self.st = StreamThread(self)
00121       self.st.start()
00122 
00123 
00124 def main():
00125   rospy.init_node("axis_driver")
00126 
00127   arg_defaults = {
00128       'hostname': '192.168.0.90',       # default IP address
00129       'username': 'root',               # default login name
00130       'password': '',
00131       'width': 640,
00132       'height': 480,
00133       'frame_id': 'axis_camera',
00134       'camera_info_url': ''}
00135 
00136   # Look up parameters starting in the driver's private parameter
00137   # space, but also searching outer namespaces.  Defining them in a
00138   # higher namespace allows the axis_ptz.py script to share parameters
00139   # with the driver.
00140   args = {}
00141   for name, val in arg_defaults.iteritems():
00142     full_name = rospy.search_param(name)
00143     if full_name is None:
00144       args[name] = val
00145     else:
00146       args[name] = rospy.get_param(full_name, val)
00147 
00148   # resolve frame_id with tf_prefix (unless already absolute)
00149   if args['frame_id'][0] != '/':        # not absolute?
00150     tf_prefix = rospy.search_param('tf_prefix')
00151     prefix_val = ''
00152     if tf_prefix is not None:           # prefix defined?
00153       prefix_val = rospy.get_param(tf_prefix)
00154       if prefix_val[0] != '/':          # prefix not absolute?
00155         prefix_val = '/' + prefix_val
00156     args['frame_id'] = prefix_val + '/' + args['frame_id']
00157 
00158   Axis(**args)
00159   rospy.spin()
00160 
00161 
00162 if __name__ == "__main__":
00163   main()
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends


axis_camera
Author(s): Ryan Gariepy
autogenerated on Mon May 13 2013 10:15:52