Python源码示例:rospy.wait_for_message()
示例1
def __init__(self, camera_name, base_frame, table_height):
"""
Initialize the instance
:param camera_name: The camera name. One of (head_camera, right_hand_camera)
:param base_frame: The frame for the robot base
:param table_height: The table height with respect to base_frame
"""
self.camera_name = camera_name
self.base_frame = base_frame
self.table_height = table_height
self.image_queue = Queue.Queue()
self.pinhole_camera_model = PinholeCameraModel()
self.tf_listener = tf.TransformListener()
camera_info_topic = "/io/internal_camera/{}/camera_info".format(camera_name)
camera_info = rospy.wait_for_message(camera_info_topic, CameraInfo)
self.pinhole_camera_model.fromCameraInfo(camera_info)
cameras = intera_interface.Cameras()
cameras.set_callback(camera_name, self.__show_image_callback, rectify_image=True)
示例2
def __init__(self, args):
self.index = 0
if len(sys.argv) > 1:
self.index = int(sys.argv[1])
rospy.init_node('save_img')
self.bridge = CvBridge()
while not rospy.is_shutdown():
raw_input()
data = rospy.wait_for_message('/camera1/usb_cam/image_raw', Image)
try:
cv_image = self.bridge.imgmsg_to_cv2(data, "passthrough")
except CvBridgeError as e:
print(e)
print "Saved to: ", base_path+str(self.index)+".jpg"
cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB, cv_image)
cv2.imwrite(join(base_path, "frame{:06d}.jpg".format(self.index)), cv_image)#*255)
self.index += 1
rospy.spin()
示例3
def __init__(self):
# Get the camera parameters
cam_info_topic = rospy.get_param('~camera/info_topic')
camera_info_msg = rospy.wait_for_message(cam_info_topic, CameraInfo)
self.cam_K = np.array(camera_info_msg.K).reshape((3, 3))
self.img_pub = rospy.Publisher('~visualisation', Image, queue_size=1)
rospy.Service('~predict', GraspPrediction, self.compute_service_handler)
self.base_frame = rospy.get_param('~camera/robot_base_frame')
self.camera_frame = rospy.get_param('~camera/camera_frame')
self.img_crop_size = rospy.get_param('~camera/crop_size')
self.img_crop_y_offset = rospy.get_param('~camera/crop_y_offset')
self.cam_fov = rospy.get_param('~camera/fov')
self.counter = 0
self.curr_depth_img = None
self.curr_img_time = 0
self.last_image_pose = None
rospy.Subscriber(rospy.get_param('~camera/depth_topic'), Image, self._depth_img_callback, queue_size=1)
self.waiting = False
self.received = False
示例4
def get_current_fk(self, fk_link_names, frame_id='base_link'):
"""
Get the current forward kinematics of a set of links.
:param fk_link_names: [string]
list of links that we want to
get the forward kinematics from
:param frame_id: string
the reference frame to be used
:return fk_result: moveit_msgs.srv.GetPositionFKResponse
"""
# Subscribe to a joint_states
js = rospy.wait_for_message('/robot/joint_states', JointState)
# Call FK service
fk_result = self.get_fk(fk_link_names, js.name, js.position, frame_id)
return fk_result
示例5
def run(self):
while not rospy.is_shutdown():
msg = CNN_out()
msg.header.stamp = rospy.Time.now()
data = None
while data is None:
try:
data = rospy.wait_for_message("camera", Image, timeout=10)
except:
pass
if self.use_network_out:
print("Publishing commands!")
else:
print("NOT Publishing commands!")
cv_image = utils.callback_img(data, self.target_size, self.crop_size,
self.imgs_rootpath, self.use_network_out)
outs = self.model.predict_on_batch(cv_image[None])
steer, coll = outs[0][0], outs[1][0]
msg.steering_angle = steer
msg.collision_prob = coll
self.pub.publish(msg)
示例6
def run(self):
"""
main loop
"""
# wait for ros-bridge to set up CARLA world
rospy.loginfo("Waiting for CARLA world (topic: /carla/world_info)...")
try:
rospy.wait_for_message("/carla/world_info", CarlaWorldInfo, timeout=10.0)
except rospy.ROSException as e:
rospy.logerr("Timeout while waiting for world info!")
raise e
rospy.loginfo("CARLA world available. Spawn infrastructure...")
client = carla.Client(self.host, self.port)
client.set_timeout(self.timeout)
self.world = client.get_world()
self.restart()
try:
rospy.spin()
except rospy.ROSInterruptException:
pass
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================
示例7
def test_vehicle_info(self):
"""
Tests vehicle_info
"""
rospy.init_node('test_node', anonymous=True)
msg = rospy.wait_for_message(
"/carla/ego_vehicle/vehicle_info", CarlaEgoVehicleInfo, timeout=TIMEOUT)
self.assertNotEqual(msg.id, 0)
self.assertEqual(msg.type, "vehicle.tesla.model3")
self.assertEqual(msg.rolename, "ego_vehicle")
self.assertEqual(len(msg.wheels), 4)
self.assertNotEqual(msg.max_rpm, 0.0)
self.assertNotEqual(msg.moi, 0.0)
self.assertNotEqual(msg.damping_rate_full_throttle, 0.0)
self.assertNotEqual(msg.damping_rate_zero_throttle_clutch_engaged, 0.0)
self.assertNotEqual(
msg.damping_rate_zero_throttle_clutch_disengaged, 0.0)
self.assertTrue(msg.use_gear_autobox)
self.assertNotEqual(msg.gear_switch_time, 0.0)
self.assertNotEqual(msg.mass, 0.0)
self.assertNotEqual(msg.clutch_strength, 0.0)
self.assertNotEqual(msg.drag_coefficient, 0.0)
self.assertNotEqual(msg.center_of_mass, Vector3())
示例8
def start(self):
""" Start the sensor """
# initialize subscribers
self._image_sub = rospy.Subscriber(self.topic_image_color, sensor_msgs.msg.Image, self._color_image_callback)
self._depth_sub = rospy.Subscriber(self.topic_image_depth, sensor_msgs.msg.Image, self._depth_image_callback)
self._camera_info_sub = rospy.Subscriber(self.topic_info_camera, sensor_msgs.msg.CameraInfo, self._camera_info_callback)
timeout = 10
try:
rospy.loginfo("waiting to recieve a message from the Kinect")
rospy.wait_for_message(self.topic_image_color, sensor_msgs.msg.Image, timeout=timeout)
rospy.wait_for_message(self.topic_image_depth, sensor_msgs.msg.Image, timeout=timeout)
rospy.wait_for_message(self.topic_info_camera, sensor_msgs.msg.CameraInfo, timeout=timeout)
except rospy.ROSException as e:
print("KINECT NOT FOUND")
rospy.logerr("Kinect topic not found, Kinect not started")
rospy.logerr(e)
while self._camera_intr is None:
time.sleep(0.1)
self._running = True
示例9
def step(self, action):
max_angular_vel = 1.5
ang_vel = ((self.action_size - 1)/2 - action) * max_angular_vel * 0.5
vel_cmd = Twist()
vel_cmd.linear.x = 0.15
vel_cmd.angular.z = ang_vel
self.pub_cmd_vel.publish(vel_cmd)
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
state, done = self.getState(data)
reward = self.setReward(state, done, action)
return np.asarray(state), reward, done
示例10
def reset(self):
rospy.wait_for_service('gazebo/reset_simulation')
try:
self.reset_proxy()
except (rospy.ServiceException) as e:
print("gazebo/reset_simulation service call failed")
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
if self.initGoal:
self.goal_x, self.goal_y = self.respawn_goal.getPosition()
self.initGoal = False
self.goal_distance = self.getGoalDistace()
state, done = self.getState(data)
return np.asarray(state)
示例11
def step(self, action):
max_angular_vel = 1.5
ang_vel = ((self.action_size - 1)/2 - action) * max_angular_vel * 0.5
vel_cmd = Twist()
vel_cmd.linear.x = 0.15
vel_cmd.angular.z = ang_vel
self.pub_cmd_vel.publish(vel_cmd)
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
state, done = self.getState(data)
reward = self.setReward(state, done, action)
return np.asarray(state), reward, done
示例12
def reset(self):
rospy.wait_for_service('gazebo/reset_simulation')
try:
self.reset_proxy()
except (rospy.ServiceException) as e:
print("gazebo/reset_simulation service call failed")
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
if self.initGoal:
self.goal_x, self.goal_y = self.respawn_goal.getPosition()
self.initGoal = False
self.goal_distance = self.getGoalDistace()
state, done = self.getState(data)
return np.asarray(state)
示例13
def step(self, action):
max_angular_vel = 1.5
ang_vel = ((self.action_size - 1)/2 - action) * max_angular_vel * 0.5
vel_cmd = Twist()
vel_cmd.linear.x = 0.15
vel_cmd.angular.z = ang_vel
self.pub_cmd_vel.publish(vel_cmd)
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
state, done = self.getState(data)
reward = self.setReward(state, done, action)
return np.asarray(state), reward, done
示例14
def step(self, action):
max_angular_vel = 1.5
ang_vel = ((self.action_size - 1)/2 - action) * max_angular_vel * 0.5
vel_cmd = Twist()
vel_cmd.linear.x = 0.15
vel_cmd.angular.z = ang_vel
self.pub_cmd_vel.publish(vel_cmd)
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
state, done = self.getState(data)
reward = self.setReward(state, done, action)
return np.asarray(state), reward, done
示例15
def reset(self):
rospy.wait_for_service('gazebo/reset_simulation')
try:
self.reset_proxy()
except (rospy.ServiceException) as e:
print("gazebo/reset_simulation service call failed")
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
if self.initGoal:
self.goal_x, self.goal_y = self.respawn_goal.getPosition()
self.initGoal = False
self.goal_distance = self.getGoalDistace()
state, done = self.getState(data)
return np.asarray(state)
示例16
def main():
rospy.init_node('jaco_jtas_test')
dof = rospy.get_param('~jaco_dof')
tmp = rospy.wait_for_message("/movo/right_arm/joint_states", JointState)
current_angles= tmp.position
traj = JacoJTASTest('right')
traj.add_point(current_angles, 0.0)
if '6dof' == dof:
p1 = [0.0] * 6
if '7dof' == dof:
p1 = [0.0] * 7
traj.add_point(p1,10.0)
p2 = list(current_angles)
traj.add_point(p2,20.0)
traj.start()
traj.wait(20.0)
print("Exiting - Joint Trajectory Action Test Complete")
示例17
def step(self, action):
# Publish action
if action==0:
self.left_pub.publish(self.v_forward-self.v_turn)
self.right_pub.publish(self.v_forward+self.v_turn)
self.rate.sleep()
elif action==1:
self.left_pub.publish(self.v_forward)
self.right_pub.publish(self.v_forward)
self.rate.sleep()
elif action==2:
self.left_pub.publish(self.v_forward+self.v_turn)
self.right_pub.publish(self.v_forward-self.v_turn)
self.rate.sleep()
# Get transform data
p = rospy.wait_for_message('transformData', Transform).translation
p = np.array([p.x,p.y])
# Calculate robot position and distance
d, p = self.getDistance(p)
# Calculate reward
r = normpdf(d)
# Translate DVS data from FIFO queue into state image
s = self.getState()
# Check if distance causes reset
if abs(d) > self.reset_distance:
return s, r, True, d, p
else:
return s, r, False, d, p
示例18
def __init__(self):
# Give the node a name
rospy.init_node('odom_ekf', anonymous=False)
# Publisher of type nav_msgs/Odometry
self.ekf_pub = rospy.Publisher('output', Odometry, queue_size=5)
# Wait for the /odom_combined topic to become available
rospy.wait_for_message('input', PoseWithCovarianceStamped)
# Subscribe to the /odom_combined topic
rospy.Subscriber('input', PoseWithCovarianceStamped, self.pub_ekf_odom)
rospy.loginfo("Publishing combined odometry on /odom_ekf")
示例19
def onStart(self):
""" starting = start listening to depth images """
self.sub_depth = rospy.Subscriber("/camera/depth_registered/image_raw", ImageMSG, self.incomingDepthData)
self.cameraInfo = rospy.wait_for_message('/camera/depth_registered/camera_info', CamInfoMSG)
self.cameraModel.fromCameraInfo(self.cameraInfo)
rospy.loginfo("Camera info received")
示例20
def __init__(self):
# initialize ROS node and transform publisher
rospy.init_node('crazyflie_detector', anonymous=True)
self.pub_tf = tf.TransformBroadcaster()
self.rate = rospy.Rate(50.0) # publish transform at 50 Hz
# initialize values for crazyflie location on Kinect v2 image
self.cf_u = 0 # u is pixels left(0) to right(+)
self.cf_v = 0 # v is pixels top(0) to bottom(+)
self.cf_d = 0 # d is distance camera(0) to crazyflie(+) from depth image
self.last_d = 0 # last non-zero depth measurement
# crazyflie orientation to Kinect v2 image (Euler)
self.r = -1.5708
self.p = 0
self.y = -3.1415
# Convert image from a ROS image message to a CV image
self.bridge = CvBridge()
cv2.namedWindow("KinectV2", 1)
# Wait for the camera_info topic to become available
rospy.wait_for_message('/kinect2/qhd/camera_info', CameraInfo)
# Subscribe to Kinect v2 sd camera_info to get image frame height and width
rospy.Subscriber('/kinect2/qhd/camera_info', CameraInfo, self.camera_data, queue_size=1)
# Subscribe to registered color and depth images
rospy.Subscriber('/kinect2/qhd/image_color_rect', Image, self.image_callback, queue_size=1)
rospy.Subscriber('/kinect2/qhd/image_depth_rect', Image, self.depth_callback, queue_size=1)
self.rate.sleep() # suspend until next cycle
# This callback function sets parameters regarding the camera.
示例21
def __init__(self):
# initialize ROS node
rospy.init_node('target_detector', anonymous=True)
# initialize publisher for target pose, PoseStamped message, and set initial sequence number
self.pub = rospy.Publisher('target_pose', PoseStamped, queue_size=1)
self.pub_pose = PoseStamped()
self.pub_pose.header.seq = 0
self.rate = rospy.Rate(1.0) # publish message at 1 Hz
# initialize values for locating target on Kinect v2 image
self.target_u = 0 # u is pixels left(0) to right(+)
self.target_v = 0 # v is pixels top(0) to bottom(+)
self.target_d = 0 # d is distance camera(0) to target(+) from depth image
self.target_found = False # flag initialized to False
self.last_d = 0 # last non-zero depth measurement
# target orientation to Kinect v2 image (Euler)
self.r = 0
self.p = 0
self.y = 0
# Convert image from a ROS image message to a CV image
self.bridge = CvBridge()
# Wait for the camera_info topic to become available
rospy.wait_for_message('/kinect2/qhd/image_color_rect', Image)
# Subscribe to registered color and depth images
rospy.Subscriber('/kinect2/qhd/image_color_rect', Image, self.image_callback, queue_size=1)
rospy.Subscriber('/kinect2/qhd/image_depth_rect', Image, self.depth_callback, queue_size=1)
self.rate.sleep() # suspend until next cycle
# This callback function handles processing Kinect color image, looking for the pink target.
示例22
def __calibrate(self, calib_type_int):
"""
Call service to calibrate motors then wait for its end. If failed, raise NiryoOneException
:param calib_type_int: 1 for auto-calibration & 2 for manual calibration
:return: status, message
:rtype: (GoalStatus, str)
"""
result = self.call_service('niryo_one/calibrate_motors',
SetInt, [calib_type_int])
if result.status != OK:
raise NiryoOneException(result.message)
# Wait until calibration is finished
rospy.sleep(1)
calibration_finished = False
while not calibration_finished:
try:
hw_status = rospy.wait_for_message('niryo_one/hardware_status',
HardwareStatus, timeout=5)
if not hw_status.calibration_in_progress:
calibration_finished = True
except rospy.ROSException as e:
raise NiryoOneException(str(e))
# Calibration
示例23
def capture_sample():
""" Captures a PointCloud2 using the sensor stick RGBD camera
Args: None
Returns:
PointCloud2: a single point cloud from the RGBD camrea
"""
get_model_state_prox = rospy.ServiceProxy('gazebo/get_model_state',GetModelState)
model_state = get_model_state_prox('training_model','world')
set_model_state_prox = rospy.ServiceProxy('gazebo/set_model_state', SetModelState)
roll = random.uniform(0, 2*math.pi)
pitch = random.uniform(0, 2*math.pi)
yaw = random.uniform(0, 2*math.pi)
quaternion = tf.transformations.quaternion_from_euler(roll, pitch, yaw)
model_state.pose.orientation.x = quaternion[0]
model_state.pose.orientation.y = quaternion[1]
model_state.pose.orientation.z = quaternion[2]
model_state.pose.orientation.w = quaternion[3]
sms_req = SetModelStateRequest()
sms_req.model_state.pose = model_state.pose
sms_req.model_state.twist = model_state.twist
sms_req.model_state.model_name = 'training_model'
sms_req.model_state.reference_frame = 'world'
set_model_state_prox(sms_req)
return rospy.wait_for_message('/sensor_stick/point_cloud', PointCloud2)
示例24
def _depth_img_callback(self, msg):
# Doing a rospy.wait_for_message is super slow, compared to just subscribing and keeping the newest one.
if not self.waiting:
return
self.curr_img_time = time.time()
self.last_image_pose = tfh.current_robot_pose(self.base_frame, self.camera_frame)
self.curr_depth_img = bridge.imgmsg_to_cv2(msg)
self.received = True
示例25
def __weight_increase_check(self):
try:
w = rospy.wait_for_message('/scales/weight', Int16, timeout=2).data
increased = w > self.last_weight
self.last_weight = w
return increased
except:
return raw_input('No weight. Success? [1/0]') == '1'
示例26
def __weight_increase_check(self):
try:
w = rospy.wait_for_message('/scales/weight', Int16, timeout=2).data
increased = w > self.last_weight
self.last_weight = w
return increased
except:
return raw_input('No weight. Success? [1/0]') == '1'
示例27
def __init__(self,
initial_joint_pos,
moveit_group,
control_mode='position'):
"""
Sawyer class.
:param initial_joint_pos: {str: float}
{'joint_name': position_value}, and also
initial_joint_pos should include all of the
joints that user wants to control and observe.
:param moveit_group: str
Use this to check safety
:param control_mode: string
robot control mode: 'position' or velocity
or effort
"""
Robot.__init__(self)
self._limb = intera_interface.Limb('right')
self._gripper = intera_interface.Gripper()
self._initial_joint_pos = initial_joint_pos
self._control_mode = control_mode
self._used_joints = []
for joint in initial_joint_pos:
self._used_joints.append(joint)
self._joint_limits = rospy.wait_for_message('/robot/joint_limits',
JointLimits)
self._moveit_group = moveit_group
self._sv = StateValidity()
示例28
def main():
"""
main function
"""
try:
rospy.init_node("carla_waypoint_publisher", anonymous=True)
# wait for ros-bridge to set up CARLA world
rospy.loginfo("Waiting for CARLA world (topic: /carla/world_info)...")
rospy.wait_for_message("/carla/world_info", CarlaWorldInfo, timeout=10.0)
except rospy.ROSException:
rospy.logerr("Error while waiting for world info!")
sys.exit(1)
host = rospy.get_param("/carla/host", "127.0.0.1")
port = rospy.get_param("/carla/port", 2000)
timeout = rospy.get_param("/carla/timeout", 2)
rospy.loginfo("CARLA world available. Trying to connect to {host}:{port}".format(
host=host, port=port))
try:
carla_client = carla.Client(host=host, port=port)
carla_client.set_timeout(timeout)
carla_world = carla_client.get_world()
rospy.loginfo("Connected to Carla.")
waypointConverter = CarlaToRosWaypointConverter(carla_world)
rospy.spin()
waypointConverter.destroy()
del waypointConverter
del carla_world
del carla_client
finally:
rospy.loginfo("Done")
示例29
def __init__(self, role_name):
"""
Constructor
"""
rospy.loginfo("Wait for vehicle info...")
try:
vehicle_info = rospy.wait_for_message("/carla/{}/vehicle_info".format(role_name),
CarlaEgoVehicleInfo)
except rospy.ROSInterruptException as e:
if not rospy.is_shutdown():
raise e
else:
sys.exit(0)
if not vehicle_info.wheels: # pylint: disable=no-member
rospy.logerr("Cannot determine max steering angle: Vehicle has no wheels.")
sys.exit(1)
self.max_steering_angle = vehicle_info.wheels[0].max_steer_angle # pylint: disable=no-member
if not self.max_steering_angle:
rospy.logerr("Cannot determine max steering angle: Value is %s",
self.max_steering_angle)
sys.exit(1)
rospy.loginfo("Vehicle info received. Max steering angle=%s",
self.max_steering_angle)
rospy.Subscriber("/carla/{}/twist".format(role_name), Twist, self.twist_received)
self.pub = rospy.Publisher("/carla/{}/vehicle_control_cmd".format(role_name),
CarlaEgoVehicleControl, queue_size=1)
示例30
def run(self):
"""
main loop
"""
# wait for ros-bridge to set up CARLA world
rospy.loginfo("Waiting for CARLA world (topic: /carla/world_info)...")
try:
rospy.wait_for_message("/carla/world_info", CarlaWorldInfo, timeout=10.0)
except rospy.ROSException:
rospy.logerr("Error while waiting for world info!")
sys.exit(1)
rospy.loginfo("CARLA world available. Waiting for ego vehicle...")
client = carla.Client(self.host, self.port)
client.set_timeout(self.timeout)
self.world = client.get_world()
try:
r = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
self.find_ego_vehicle_actor()
r.sleep()
except rospy.ROSInterruptException:
pass
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================