repo_id stringlengths 19 138 | file_path stringlengths 32 200 | content stringlengths 1 12.9M | __index_level_0__ int64 0 0 |
|---|---|---|---|
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_online.hpp | // Copyright (C) 2011 PAL Robotics S.L. All rights reserved.
// Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Copyright (C) 2008 Mikael Mayer
// Copyright (C) 2008 Julia Jesse
// Version: 1.0
// Author: Marcus Liebhardt
// This class has been derived from the KDL::TreeIkSolverPos_NR_JL class
// by Julia Jesse, Mikael Mayer and Ruben Smits
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDLTREEIKSOLVERPOS_ONLINE_HPP
#define KDLTREEIKSOLVERPOS_ONLINE_HPP
#include <vector>
#include <string>
#include "treeiksolver.hpp"
#include "treefksolver.hpp"
namespace KDL {
/**
* Implementation of a general inverse position kinematics algorithm to calculate the position transformation from
* Cartesian to joint space of a general KDL::Tree. This class has been derived from the TreeIkSolverPos_NR_JL class,
* but was modified for online solving for use in realtime systems. Thus, the calculation is only done once,
* meaning that no iteration is done, because this solver is intended to run at a high frequency.
* It enforces velocity limits in task as well as in joint space. It also takes joint limits into account.
*
* @ingroup KinematicFamily
*/
class TreeIkSolverPos_Online: public TreeIkSolverPos {
public:
/**
* Constructor of the solver, it needs the number of joints of the tree, a list of the endpoints
* you are interested in, the maximum and minimum values you want to enforce and a forward position kinematics
* solver as well as an inverse velocity kinematics solver for the calculations
*
* @param nr_of_jnts number of joints of the tree to calculate the joint positions for
* @param endpoints the list of endpoints you are interested in
* @param q_min the minimum joint positions
* @param q_max the maximum joint positions
* @param q_dot_max the maximum joint velocities
* @param x_dot_trans_max the maximum translational velocity of your endpoints
* @param x_dot_rot_max the maximum rotational velocity of your endpoints
* @param fksolver a forward position kinematics solver
* @param iksolver an inverse velocity kinematics solver
*
* @return
*/
TreeIkSolverPos_Online(const double& nr_of_jnts,
const std::vector<std::string>& endpoints,
const JntArray& q_min,
const JntArray& q_max,
const JntArray& q_dot_max,
const double x_dot_trans_max,
const double x_dot_rot_max,
TreeFkSolverPos& fksolver,
TreeIkSolverVel& iksolver);
~TreeIkSolverPos_Online();
virtual double CartToJnt(const JntArray& q_in, const Frames& p_in, JntArray& q_out);
private:
/**
* Scales the class member KDL::JntArray q_dot_, if one (or more) joint velocity exceeds the maximum value.
* Scaling is done propotional to the biggest overshoot among all joint velocities.
*/
void enforceJointVelLimits();
/**
* Scales translational and rotational velocity vectors of the class member KDL::Twist twist_,
* if at least one of both exceeds the maximum value/length.
* Scaling is done propotional to the biggest overshoot among both velocities.
*/
void enforceCartVelLimits();
JntArray q_min_;
JntArray q_max_;
JntArray q_dot_max_;
double x_dot_trans_max_;
double x_dot_rot_max_;
TreeFkSolverPos& fksolver_;
TreeIkSolverVel& iksolver_;
JntArray q_dot_;
Twist twist_;
Frames frames_;
Twists delta_twists_;
};
} // namespace
#endif /* KDLTREEIKSOLVERPOS_ONLINE_HPP */
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainjnttojacsolver.cpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "chainjnttojacsolver.hpp"
namespace KDL
{
ChainJntToJacSolver::ChainJntToJacSolver(const Chain& _chain):
chain(_chain),locked_joints_(chain.getNrOfJoints(),false),
nr_of_unlocked_joints_(chain.getNrOfJoints())
{
}
ChainJntToJacSolver::~ChainJntToJacSolver()
{
}
int ChainJntToJacSolver::setLockedJoints(const std::vector<bool> locked_joints)
{
if(locked_joints.size()!=locked_joints_.size())
return -1;
locked_joints_=locked_joints;
nr_of_unlocked_joints_=0;
for(unsigned int i=0;i<locked_joints_.size();i++){
if(!locked_joints_[i])
nr_of_unlocked_joints_++;
}
return 0;
}
int ChainJntToJacSolver::JntToJac(const JntArray& q_in, Jacobian& jac, int seg_nr)
{
unsigned int segmentNr;
if(seg_nr<0)
segmentNr=chain.getNrOfSegments();
else
segmentNr = seg_nr;
//Initialize Jacobian to zero since only segmentNr colunns are computed
SetToZero(jac) ;
if(q_in.rows()!=chain.getNrOfJoints()||nr_of_unlocked_joints_!=jac.columns())
return (error = E_JAC_FAILED);
else if(segmentNr>chain.getNrOfSegments())
return (error = E_JAC_FAILED);
T_tmp = Frame::Identity();
SetToZero(t_tmp);
int j=0;
int k=0;
Frame total;
for (unsigned int i=0;i<segmentNr;i++) {
//Calculate new Frame_base_ee
if(chain.getSegment(i).getJoint().getType()!=Joint::None){
//pose of the new end-point expressed in the base
total = T_tmp*chain.getSegment(i).pose(q_in(j));
//changing base of new segment's twist to base frame if it is not locked
//t_tmp = T_tmp.M*chain.getSegment(i).twist(1.0);
if(!locked_joints_[j])
t_tmp = T_tmp.M*chain.getSegment(i).twist(q_in(j),1.0);
}else{
total = T_tmp*chain.getSegment(i).pose(0.0);
}
//Changing Refpoint of all columns to new ee
changeRefPoint(jac,total.p-T_tmp.p,jac);
//Only increase jointnr if the segment has a joint
if(chain.getSegment(i).getJoint().getType()!=Joint::None){
//Only put the twist inside if it is not locked
if(!locked_joints_[j])
jac.setColumn(k++,t_tmp);
j++;
}
T_tmp = total;
}
return (error = E_NOERROR);
}
const char* ChainJntToJacSolver::strError(const int error) const
{
if (E_JAC_FAILED == error) return "Jac Failed";
else return SolverI::strError(error);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.hpp | // Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Copyright (C) 2008 Mikael Mayer
// Copyright (C) 2008 Julia Jesse
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDLTREEIKSOLVERPOS_NR_JL_HPP
#define KDLTREEIKSOLVERPOS_NR_JL_HPP
#include "treeiksolver.hpp"
#include "treefksolver.hpp"
#include <vector>
#include <string>
namespace KDL {
/**
* Implementation of a general inverse position kinematics
* algorithm based on Newton-Raphson iterations to calculate the
* position transformation from Cartesian to joint space of a general
* KDL::Tree. Takes joint limits into account.
*
* @ingroup KinematicFamily
*/
class TreeIkSolverPos_NR_JL: public TreeIkSolverPos {
public:
/**
* Constructor of the solver, it needs the tree, a forward
* position kinematics solver and an inverse velocity
* kinematics solver for that tree, and a list of the segments you are interested in.
*
* @param tree the tree to calculate the inverse position for
* @param endpoints the list of endpoints you are interested in.
* @param q_max the maximum joint positions
* @param q_min the minimum joint positions
* @param fksolver a forward position kinematics solver
* @param iksolver an inverse velocity kinematics solver
* @param maxiter the maximum Newton-Raphson iterations,
* default: 100
* @param eps the precision for the position, used to end the
* iterations, default: epsilon (defined in kdl.hpp)
*
* @return
*/
TreeIkSolverPos_NR_JL(const Tree& tree, const std::vector<std::string>& endpoints, const JntArray& q_min, const JntArray& q_max, TreeFkSolverPos& fksolver,TreeIkSolverVel& iksolver,unsigned int maxiter=100,double eps=1e-6);
~TreeIkSolverPos_NR_JL();
virtual double CartToJnt(const JntArray& q_init, const Frames& p_in, JntArray& q_out);
private:
const Tree tree;
JntArray q_min;
JntArray q_max;
TreeIkSolverVel& iksolver;
TreeFkSolverPos& fksolver;
JntArray delta_q;
Frames frames;
Twists delta_twists;
std::vector<std::string> endpoints;
unsigned int maxiter;
double eps;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/rotational_interpolation_sa.hpp | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:39 CET 2005 rotational_interpolation_sa.h
rotational_interpolation_sa.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: rotational_interpolation_singleaxis.h,v 1.1.1.1.2.3 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_ROTATIONALINTERPOLATION_SINGLEAXIS_H
#define KDL_ROTATIONALINTERPOLATION_SINGLEAXIS_H
#include "frames.hpp"
#include "frames_io.hpp"
#include "rotational_interpolation.hpp"
namespace KDL {
/**
* An interpolation algorithm which rotates a frame over the existing
* single rotation axis
* formed by start and end rotation. If more than one rotational axis
* exist, an arbitrary one will be choosen, therefore it is not recommended
* to try to interpolate a 180 degrees rotation.
* @ingroup Motion
*/
class RotationalInterpolation_SingleAxis: public RotationalInterpolation
{
Rotation R_base_start;
Rotation R_base_end;
Vector rot_start_end;
double angle;
public:
RotationalInterpolation_SingleAxis();
virtual void SetStartEnd(Rotation start,Rotation end);
virtual double Angle();
virtual Rotation Pos(double th) const;
virtual Vector Vel(double th,double thd) const;
virtual Vector Acc(double th,double thd,double thdd) const;
virtual void Write(std::ostream& os) const;
virtual RotationalInterpolation* Clone() const;
virtual ~RotationalInterpolation_SingleAxis();
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/framevel_io.hpp | /*****************************************************************************
* \file
* provides I/O operations on FrameVels classes
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V2
*
* \par History
* - $log$
*
* \par Release
* $Id: rframes_io.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_FRAMESVEL_IO
#define KDL_FRAMESVEL_IO
#include "utilities/utility_io.h"
#include "utilities/rall1d_io.h"
#include "framevel_io.hpp"
#include "frames_io.hpp"
namespace KDL {
// Output...
inline std::ostream& operator << (std::ostream& os,const VectorVel& r) {
os << "{" << r.p << "," << r.v << "}" << std::endl;
return os;
}
inline std::ostream& operator << (std::ostream& os,const RotationVel& r) {
os << "{" << std::endl << r.R << "," <<std::endl << r.w << std::endl << "}" << std::endl;
return os;
}
inline std::ostream& operator << (std::ostream& os,const FrameVel& r) {
os << "{" << std::endl << r.M << "," << std::endl << r.p << std::endl << "}" << std::endl;
return os;
}
inline std::ostream& operator << (std::ostream& os,const TwistVel& r) {
os << "{" << std::endl << r.vel << "," << std::endl << r.rot << std::endl << "}" << std::endl;
return os;
}
} // namespace Frame
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/path_cyclic_closed.hpp | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:38 CET 2005 path_cyclic_closed.h
path_cyclic_closed.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V2
*
* \par History
* - $log$
*
* \par Release
* $Id: path_cyclic_closed.h,v 1.1.1.1.2.3 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_MOTION_PATH_CYCLIC_CLOSED_H
#define KDL_MOTION_PATH_CYCLIC_CLOSED_H
#include "frames.hpp"
#include "frames_io.hpp"
#include "path.hpp"
#include <vector>
namespace KDL {
/**
* A Path representing a closed circular movement,
* which is traversed a number of times.
* @ingroup Motion
*/
class Path_Cyclic_Closed : public Path
{
int times;
Path* geom;
bool aggregate;
public:
Path_Cyclic_Closed(Path* _geom,int _times, bool _aggregate=true);
virtual double LengthToS(double length);
virtual double PathLength();
virtual Frame Pos(double s) const;
virtual Twist Vel(double s,double sd) const;
virtual Twist Acc(double s,double sd,double sdd) const;
virtual void Write(std::ostream& os);
static Path* Read(std::istream& is);
virtual Path* Clone();
/**
* gets an identifier indicating the type of this Path object
*/
virtual IdentifierType getIdentifier() const {
return ID_CYCLIC_CLOSED;
}
virtual ~Path_Cyclic_Closed();
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/frameacc.inl | /*****************************************************************************
* \file
* provides inline functions of rrframes.h
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: rrframes.inl,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
/////////////////// VectorAcc /////////////////////////////////////
VectorAcc operator + (const VectorAcc& r1,const VectorAcc& r2) {
return VectorAcc(r1.p+r2.p,r1.v+r2.v,r1.dv+r2.dv);
}
VectorAcc operator - (const VectorAcc& r1,const VectorAcc& r2) {
return VectorAcc(r1.p-r2.p, r1.v-r2.v, r1.dv-r2.dv);
}
VectorAcc operator + (const Vector& r1,const VectorAcc& r2) {
return VectorAcc(r1+r2.p,r2.v,r2.dv);
}
VectorAcc operator - (const Vector& r1,const VectorAcc& r2) {
return VectorAcc(r1-r2.p, -r2.v, -r2.dv);
}
VectorAcc operator + (const VectorAcc& r1,const Vector& r2) {
return VectorAcc(r1.p+r2,r1.v,r1.dv);
}
VectorAcc operator - (const VectorAcc& r1,const Vector& r2) {
return VectorAcc(r1.p-r2, r1.v, r1.dv);
}
// unary -
VectorAcc operator - (const VectorAcc& r) {
return VectorAcc(-r.p,-r.v,-r.dv);
}
// cross prod.
VectorAcc operator * (const VectorAcc& r1,const VectorAcc& r2) {
return VectorAcc(r1.p*r2.p,
r1.p*r2.v+r1.v*r2.p,
r1.dv*r2.p+2*r1.v*r2.v+r1.p*r2.dv
);
}
VectorAcc operator * (const VectorAcc& r1,const Vector& r2) {
return VectorAcc(r1.p*r2, r1.v*r2, r1.dv*r2 );
}
VectorAcc operator * (const Vector& r1,const VectorAcc& r2) {
return VectorAcc(r1*r2.p, r1*r2.v, r1*r2.dv );
}
// scalar mult.
VectorAcc operator * (double r1,const VectorAcc& r2) {
return VectorAcc(r1*r2.p, r1*r2.v, r1*r2.dv );
}
VectorAcc operator * (const VectorAcc& r1,double r2) {
return VectorAcc(r1.p*r2, r1.v*r2, r1.dv*r2 );
}
VectorAcc operator * (const doubleAcc& r1,const VectorAcc& r2) {
return VectorAcc(r1.t*r2.p,
r1.t*r2.v + r1.d*r2.p,
r1.t*r2.dv + 2*r1.d*r2.v + r1.dd*r2.p
);
}
VectorAcc operator * (const VectorAcc& r2,const doubleAcc& r1) {
return VectorAcc(r1.t*r2.p,
r1.t*r2.v + r1.d*r2.p,
r1.t*r2.dv + 2*r1.d*r2.v + r1.dd*r2.p
);
}
VectorAcc& VectorAcc::operator = (const VectorAcc& arg) {
p=arg.p;
v=arg.v;
dv=arg.dv;
return *this;
}
VectorAcc& VectorAcc::operator = (const Vector& arg) {
p=arg;
v=Vector::Zero();
dv=Vector::Zero();
return *this;
}
VectorAcc& VectorAcc::operator += (const VectorAcc& arg) {
p+=arg.p;
v+=arg.v;
dv+= arg.dv;
return *this;
}
VectorAcc& VectorAcc::operator -= (const VectorAcc& arg) {
p-=arg.p;
v-=arg.v;
dv-=arg.dv;
return *this;
}
VectorAcc VectorAcc::Zero() {
return VectorAcc(Vector::Zero(),Vector::Zero(),Vector::Zero());
}
void VectorAcc::ReverseSign() {
p.ReverseSign();
v.ReverseSign();
dv.ReverseSign();
}
doubleAcc VectorAcc::Norm() {
doubleAcc res;
res.t = p.Norm();
res.d = dot(p,v)/res.t;
res.dd = (dot(p,dv)+dot(v,v)-res.d*res.d)/res.t;
return res;
}
doubleAcc dot(const VectorAcc& lhs,const VectorAcc& rhs) {
return doubleAcc( dot(lhs.p,rhs.p),
dot(lhs.p,rhs.v)+dot(lhs.v,rhs.p),
dot(lhs.p,rhs.dv)+2*dot(lhs.v,rhs.v)+dot(lhs.dv,rhs.p)
);
}
doubleAcc dot(const VectorAcc& lhs,const Vector& rhs) {
return doubleAcc( dot(lhs.p,rhs),
dot(lhs.v,rhs),
dot(lhs.dv,rhs)
);
}
doubleAcc dot(const Vector& lhs,const VectorAcc& rhs) {
return doubleAcc( dot(lhs,rhs.p),
dot(lhs,rhs.v),
dot(lhs,rhs.dv)
);
}
bool Equal(const VectorAcc& r1,const VectorAcc& r2,double eps) {
return (Equal(r1.p,r2.p,eps)
&& Equal(r1.v,r2.v,eps)
&& Equal(r1.dv,r2.dv,eps)
);
}
bool Equal(const Vector& r1,const VectorAcc& r2,double eps) {
return (Equal(r1,r2.p,eps)
&& Equal(Vector::Zero(),r2.v,eps)
&& Equal(Vector::Zero(),r2.dv,eps)
);
}
bool Equal(const VectorAcc& r1,const Vector& r2,double eps) {
return (Equal(r1.p,r2,eps)
&& Equal(r1.v,Vector::Zero(),eps)
&& Equal(r1.dv,Vector::Zero(),eps)
);
}
VectorAcc operator / (const VectorAcc& r1,double r2) {
return r1*(1.0/r2);
}
VectorAcc operator / (const VectorAcc& r2,const doubleAcc& r1) {
return r2*(1.0/r1);
}
/////////////////// RotationAcc /////////////////////////////////////
RotationAcc operator* (const RotationAcc& r1,const RotationAcc& r2) {
return RotationAcc( r1.R * r2.R,
r1.w + r1.R*r2.w,
r1.dw + r1.w*(r1.R*r2.w) + r1.R*r2.dw
);
}
RotationAcc operator* (const Rotation& r1,const RotationAcc& r2) {
return RotationAcc( r1*r2.R, r1*r2.w, r1*r2.dw);
}
RotationAcc operator* (const RotationAcc& r1,const Rotation& r2) {
return RotationAcc( r1.R*r2, r1.w, r1.dw );
}
RotationAcc& RotationAcc::operator = (const RotationAcc& arg) {
R=arg.R;
w=arg.w;
dw=arg.dw;
return *this;
}
RotationAcc& RotationAcc::operator = (const Rotation& arg) {
R = arg;
w = Vector::Zero();
dw = Vector::Zero();
return *this;
}
RotationAcc RotationAcc::Identity() {
return RotationAcc(Rotation::Identity(),Vector::Zero(),Vector::Zero());
}
RotationAcc RotationAcc::Inverse() const {
return RotationAcc(R.Inverse(),-R.Inverse(w),-R.Inverse(dw));
}
VectorAcc RotationAcc::Inverse(const VectorAcc& arg) const {
VectorAcc tmp;
tmp.p = R.Inverse(arg.p);
tmp.v = R.Inverse(arg.v - w * arg.p);
tmp.dv = R.Inverse(arg.dv - dw*arg.p - w*(arg.v+R*tmp.v));
return tmp;
}
VectorAcc RotationAcc::Inverse(const Vector& arg) const {
VectorAcc tmp;
tmp.p = R.Inverse(arg);
tmp.v = R.Inverse(-w*arg);
tmp.dv = R.Inverse(-dw*arg - w*(R*tmp.v));
return tmp;
}
VectorAcc RotationAcc::operator*(const VectorAcc& arg) const {
VectorAcc tmp;
tmp.p = R*arg.p;
tmp.dv = R*arg.v;
tmp.v = w*tmp.p + tmp.dv;
tmp.dv = dw*tmp.p + w*(tmp.v + tmp.dv) + R*arg.dv;
return tmp;
}
VectorAcc operator*(const Rotation& R,const VectorAcc& x) {
return VectorAcc(R*x.p,R*x.v,R*x.dv);
}
VectorAcc RotationAcc::operator*(const Vector& arg) const {
VectorAcc tmp;
tmp.p = R*arg;
tmp.v = w*tmp.p;
tmp.dv = dw*tmp.p + w*tmp.v;
return tmp;
}
/*
// = Rotations
// The Rot... static functions give the value of the appropriate rotation matrix back.
// The DoRot... functions apply a rotation R to *this,such that *this = *this * R.
void RRotation::DoRotX(const RDouble& angle) {
w+=R*Vector(angle.grad,0,0);
R.DoRotX(angle.t);
}
RotationAcc RotationAcc::RotX(const doubleAcc& angle) {
return RotationAcc(Rotation::RotX(angle.t),
Vector(angle.d,0,0),
Vector(angle.dd,0,0)
);
}
void RRotation::DoRotY(const RDouble& angle) {
w+=R*Vector(0,angle.grad,0);
R.DoRotY(angle.t);
}
RotationAcc RotationAcc::RotY(const doubleAcc& angle) {
return RotationAcc(
Rotation::RotX(angle.t),
Vector(0,angle.d,0),
Vector(0,angle.dd,0)
);
}
void RRotation::DoRotZ(const RDouble& angle) {
w+=R*Vector(0,0,angle.grad);
R.DoRotZ(angle.t);
}
RotationAcc RotationAcc::RotZ(const doubleAcc& angle) {
return RotationAcc(
Rotation::RotZ(angle.t),
Vector(0,0,angle.d),
Vector(0,0,angle.dd)
);
}
RRotation RRotation::Rot(const Vector& rotvec,const RDouble& angle)
// rotvec has arbitrary norm
// rotation around a constant vector !
{
Vector v = rotvec.Normalize();
return RRotation(Rotation::Rot2(v,angle.t),v*angle.grad);
}
RRotation RRotation::Rot2(const Vector& rotvec,const RDouble& angle)
// rotvec is normalized.
{
return RRotation(Rotation::Rot2(rotvec,angle.t),rotvec*angle.grad);
}
*/
bool Equal(const RotationAcc& r1,const RotationAcc& r2,double eps) {
return (Equal(r1.w,r2.w,eps) && Equal(r1.R,r2.R,eps) && Equal(r1.dw,r2.dw,eps) );
}
bool Equal(const Rotation& r1,const RotationAcc& r2,double eps) {
return (Equal(Vector::Zero(),r2.w,eps) && Equal(r1,r2.R,eps) &&
Equal(Vector::Zero(),r2.dw,eps) );
}
bool Equal(const RotationAcc& r1,const Rotation& r2,double eps) {
return (Equal(r1.w,Vector::Zero(),eps) && Equal(r1.R,r2,eps) &&
Equal(r1.dw,Vector::Zero(),eps) );
}
// Methods and operators related to FrameAcc
// They all delegate most of the work to RotationAcc and VectorAcc
FrameAcc& FrameAcc::operator = (const FrameAcc& arg) {
M=arg.M;
p=arg.p;
return *this;
}
FrameAcc FrameAcc::Identity() {
return FrameAcc(RotationAcc::Identity(),VectorAcc::Zero());
}
FrameAcc operator *(const FrameAcc& lhs,const FrameAcc& rhs)
{
return FrameAcc(lhs.M*rhs.M,lhs.M*rhs.p+lhs.p);
}
FrameAcc operator *(const FrameAcc& lhs,const Frame& rhs)
{
return FrameAcc(lhs.M*rhs.M,lhs.M*rhs.p+lhs.p);
}
FrameAcc operator *(const Frame& lhs,const FrameAcc& rhs)
{
return FrameAcc(lhs.M*rhs.M,lhs.M*rhs.p+lhs.p);
}
VectorAcc FrameAcc::operator *(const VectorAcc & arg) const
{
return M*arg+p;
}
VectorAcc FrameAcc::operator *(const Vector & arg) const
{
return M*arg+p;
}
VectorAcc FrameAcc::Inverse(const VectorAcc& arg) const
{
return M.Inverse(arg-p);
}
VectorAcc FrameAcc::Inverse(const Vector& arg) const
{
return M.Inverse(arg-p);
}
FrameAcc FrameAcc::Inverse() const
{
return FrameAcc(M.Inverse(),-M.Inverse(p));
}
FrameAcc& FrameAcc::operator =(const Frame & arg)
{
M = arg.M;
p = arg.p;
return *this;
}
bool Equal(const FrameAcc& r1,const FrameAcc& r2,double eps) {
return (Equal(r1.M,r2.M,eps) && Equal(r1.p,r2.p,eps));
}
bool Equal(const Frame& r1,const FrameAcc& r2,double eps) {
return (Equal(r1.M,r2.M,eps) && Equal(r1.p,r2.p,eps));
}
bool Equal(const FrameAcc& r1,const Frame& r2,double eps) {
return (Equal(r1.M,r2.M,eps) && Equal(r1.p,r2.p,eps));
}
Frame FrameAcc::GetFrame() const {
return Frame(M.R,p.p);
}
Twist FrameAcc::GetTwist() const {
return Twist(p.v,M.w);
}
Twist FrameAcc::GetAccTwist() const {
return Twist(p.dv,M.dw);
}
TwistAcc TwistAcc::Zero()
{
return TwistAcc(VectorAcc::Zero(),VectorAcc::Zero());
}
void TwistAcc::ReverseSign()
{
vel.ReverseSign();
rot.ReverseSign();
}
TwistAcc TwistAcc::RefPoint(const VectorAcc& v_base_AB)
// Changes the reference point of the TwistAcc.
// The RVector v_base_AB is expressed in the same base as the TwistAcc
// The RVector v_base_AB is a RVector from the old point to
// the new point.
// Complexity : 6M+6A
{
return TwistAcc(this->vel+this->rot*v_base_AB,this->rot);
}
TwistAcc& TwistAcc::operator-=(const TwistAcc& arg)
{
vel-=arg.vel;
rot -=arg.rot;
return *this;
}
TwistAcc& TwistAcc::operator+=(const TwistAcc& arg)
{
vel+=arg.vel;
rot +=arg.rot;
return *this;
}
TwistAcc operator*(const TwistAcc& lhs,double rhs)
{
return TwistAcc(lhs.vel*rhs,lhs.rot*rhs);
}
TwistAcc operator*(double lhs,const TwistAcc& rhs)
{
return TwistAcc(lhs*rhs.vel,lhs*rhs.rot);
}
TwistAcc operator/(const TwistAcc& lhs,double rhs)
{
return TwistAcc(lhs.vel/rhs,lhs.rot/rhs);
}
TwistAcc operator*(const TwistAcc& lhs,const doubleAcc& rhs)
{
return TwistAcc(lhs.vel*rhs,lhs.rot*rhs);
}
TwistAcc operator*(const doubleAcc& lhs,const TwistAcc& rhs)
{
return TwistAcc(lhs*rhs.vel,lhs*rhs.rot);
}
TwistAcc operator/(const TwistAcc& lhs,const doubleAcc& rhs)
{
return TwistAcc(lhs.vel/rhs,lhs.rot/rhs);
}
// addition of TwistAcc's
TwistAcc operator+(const TwistAcc& lhs,const TwistAcc& rhs)
{
return TwistAcc(lhs.vel+rhs.vel,lhs.rot+rhs.rot);
}
TwistAcc operator-(const TwistAcc& lhs,const TwistAcc& rhs)
{
return TwistAcc(lhs.vel-rhs.vel,lhs.rot-rhs.rot);
}
// unary -
TwistAcc operator-(const TwistAcc& arg)
{
return TwistAcc(-arg.vel,-arg.rot);
}
TwistAcc RotationAcc::Inverse(const TwistAcc& arg) const
{
return TwistAcc(Inverse(arg.vel),Inverse(arg.rot));
}
TwistAcc RotationAcc::operator * (const TwistAcc& arg) const
{
return TwistAcc((*this)*arg.vel,(*this)*arg.rot);
}
TwistAcc RotationAcc::Inverse(const Twist& arg) const
{
return TwistAcc(Inverse(arg.vel),Inverse(arg.rot));
}
TwistAcc RotationAcc::operator * (const Twist& arg) const
{
return TwistAcc((*this)*arg.vel,(*this)*arg.rot);
}
TwistAcc FrameAcc::operator * (const TwistAcc& arg) const
{
TwistAcc tmp;
tmp.rot = M*arg.rot;
tmp.vel = M*arg.vel+p*tmp.rot;
return tmp;
}
TwistAcc FrameAcc::operator * (const Twist& arg) const
{
TwistAcc tmp;
tmp.rot = M*arg.rot;
tmp.vel = M*arg.vel+p*tmp.rot;
return tmp;
}
TwistAcc FrameAcc::Inverse(const TwistAcc& arg) const
{
TwistAcc tmp;
tmp.rot = M.Inverse(arg.rot);
tmp.vel = M.Inverse(arg.vel-p*arg.rot);
return tmp;
}
TwistAcc FrameAcc::Inverse(const Twist& arg) const
{
TwistAcc tmp;
tmp.rot = M.Inverse(arg.rot);
tmp.vel = M.Inverse(arg.vel-p*arg.rot);
return tmp;
}
Twist TwistAcc::GetTwist() const {
return Twist(vel.p,rot.p);
}
Twist TwistAcc::GetTwistDot() const {
return Twist(vel.v,rot.v);
}
bool Equal(const TwistAcc& a,const TwistAcc& b,double eps) {
return (Equal(a.rot,b.rot,eps)&&
Equal(a.vel,b.vel,eps) );
}
bool Equal(const Twist& a,const TwistAcc& b,double eps) {
return (Equal(a.rot,b.rot,eps)&&
Equal(a.vel,b.vel,eps) );
}
bool Equal(const TwistAcc& a,const Twist& b,double eps) {
return (Equal(a.rot,b.rot,eps)&&
Equal(a.vel,b.vel,eps) );
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/frames.inl | /***************************************************************************
frames.inl - description
-------------------------
begin : June 2006
copyright : (C) 2006 Erwin Aertbelien
email : firstname.lastname@mech.kuleuven.ac.be
History (only major changes)( AUTHOR-Description ) :
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/**
* \file frames.inl
* Inlined member functions and global functions that relate to the classes in frames.cpp
*
*/
IMETHOD Vector::Vector(const Vector & arg)
{
data[0] = arg.data[0];
data[1] = arg.data[1];
data[2] = arg.data[2];
}
IMETHOD Vector::Vector(double x,double y, double z)
{
data[0]=x;data[1]=y;data[2]=z;
}
IMETHOD Vector& Vector::operator =(const Vector & arg)
{
data[0] = arg.data[0];
data[1] = arg.data[1];
data[2] = arg.data[2];
return *this;
}
IMETHOD Vector operator +(const Vector & lhs,const Vector& rhs)
{
Vector tmp;
tmp.data[0] = lhs.data[0]+rhs.data[0];
tmp.data[1] = lhs.data[1]+rhs.data[1];
tmp.data[2] = lhs.data[2]+rhs.data[2];
return tmp;
}
IMETHOD Vector operator -(const Vector & lhs,const Vector& rhs)
{
Vector tmp;
tmp.data[0] = lhs.data[0]-rhs.data[0];
tmp.data[1] = lhs.data[1]-rhs.data[1];
tmp.data[2] = lhs.data[2]-rhs.data[2];
return tmp;
}
IMETHOD double Vector::x() const { return data[0]; }
IMETHOD double Vector::y() const { return data[1]; }
IMETHOD double Vector::z() const { return data[2]; }
IMETHOD void Vector::x( double _x ) { data[0] = _x; }
IMETHOD void Vector::y( double _y ) { data[1] = _y; }
IMETHOD void Vector::z( double _z ) { data[2] = _z; }
Vector operator *(const Vector& lhs,double rhs)
{
Vector tmp;
tmp.data[0] = lhs.data[0]*rhs;
tmp.data[1] = lhs.data[1]*rhs;
tmp.data[2] = lhs.data[2]*rhs;
return tmp;
}
Vector operator *(double lhs,const Vector& rhs)
{
Vector tmp;
tmp.data[0] = lhs*rhs.data[0];
tmp.data[1] = lhs*rhs.data[1];
tmp.data[2] = lhs*rhs.data[2];
return tmp;
}
Vector operator /(const Vector& lhs,double rhs)
{
Vector tmp;
tmp.data[0] = lhs.data[0]/rhs;
tmp.data[1] = lhs.data[1]/rhs;
tmp.data[2] = lhs.data[2]/rhs;
return tmp;
}
Vector operator *(const Vector & lhs,const Vector& rhs)
// Complexity : 6M+3A
{
Vector tmp;
tmp.data[0] = lhs.data[1]*rhs.data[2]-lhs.data[2]*rhs.data[1];
tmp.data[1] = lhs.data[2]*rhs.data[0]-lhs.data[0]*rhs.data[2];
tmp.data[2] = lhs.data[0]*rhs.data[1]-lhs.data[1]*rhs.data[0];
return tmp;
}
Vector& Vector::operator +=(const Vector & arg)
// Complexity : 3A
{
data[0]+=arg.data[0];
data[1]+=arg.data[1];
data[2]+=arg.data[2];
return *this;
}
Vector& Vector::operator -=(const Vector & arg)
// Complexity : 3A
{
data[0]-=arg.data[0];
data[1]-=arg.data[1];
data[2]-=arg.data[2];
return *this;
}
Vector Vector::Zero()
{
return Vector(0,0,0);
}
double Vector::operator()(int index) const {
FRAMES_CHECKI((0<=index)&&(index<=2));
return data[index];
}
double& Vector::operator () (int index)
{
FRAMES_CHECKI((0<=index)&&(index<=2));
return data[index];
}
Wrench Frame::operator * (const Wrench& arg) const
// Complexity : 24M+18A
{
Wrench tmp;
tmp.force = M*arg.force;
tmp.torque = M*arg.torque + p*tmp.force;
return tmp;
}
Wrench Frame::Inverse(const Wrench& arg) const
{
Wrench tmp;
tmp.force = M.Inverse(arg.force);
tmp.torque = M.Inverse(arg.torque-p*arg.force);
return tmp;
}
Wrench Rotation::Inverse(const Wrench& arg) const
{
return Wrench(Inverse(arg.force),Inverse(arg.torque));
}
Twist Rotation::Inverse(const Twist& arg) const
{
return Twist(Inverse(arg.vel),Inverse(arg.rot));
}
Wrench Wrench::Zero()
{
return Wrench(Vector::Zero(),Vector::Zero());
}
void Wrench::ReverseSign()
{
torque.ReverseSign();
force.ReverseSign();
}
Wrench Wrench::RefPoint(const Vector& v_base_AB) const
// Changes the reference point of the Wrench.
// The vector v_base_AB is expressed in the same base as the twist
// The vector v_base_AB is a vector from the old point to
// the new point.
{
return Wrench(this->force,
this->torque+this->force*v_base_AB
);
}
Wrench& Wrench::operator-=(const Wrench& arg)
{
torque-=arg.torque;
force -=arg.force;
return *this;
}
Wrench& Wrench::operator+=(const Wrench& arg)
{
torque+=arg.torque;
force +=arg.force;
return *this;
}
double& Wrench::operator()(int i)
{
// assert((0<=i)&&(i<6)); done by underlying routines
if (i<3)
return force(i);
else
return torque(i-3);
}
double Wrench::operator()(int i) const
{
// assert((0<=i)&&(i<6)); done by underlying routines
if (i<3)
return force(i);
else
return torque(i-3);
}
Wrench operator*(const Wrench& lhs,double rhs)
{
return Wrench(lhs.force*rhs,lhs.torque*rhs);
}
Wrench operator*(double lhs,const Wrench& rhs)
{
return Wrench(lhs*rhs.force,lhs*rhs.torque);
}
Wrench operator/(const Wrench& lhs,double rhs)
{
return Wrench(lhs.force/rhs,lhs.torque/rhs);
}
// addition of Wrench's
Wrench operator+(const Wrench& lhs,const Wrench& rhs)
{
return Wrench(lhs.force+rhs.force,lhs.torque+rhs.torque);
}
Wrench operator-(const Wrench& lhs,const Wrench& rhs)
{
return Wrench(lhs.force-rhs.force,lhs.torque-rhs.torque);
}
// unary -
Wrench operator-(const Wrench& arg)
{
return Wrench(-arg.force,-arg.torque);
}
Twist Frame::operator * (const Twist& arg) const
// Complexity : 24M+18A
{
Twist tmp;
tmp.rot = M*arg.rot;
tmp.vel = M*arg.vel+p*tmp.rot;
return tmp;
}
Twist Frame::Inverse(const Twist& arg) const
{
Twist tmp;
tmp.rot = M.Inverse(arg.rot);
tmp.vel = M.Inverse(arg.vel-p*arg.rot);
return tmp;
}
Twist Twist::Zero()
{
return Twist(Vector::Zero(),Vector::Zero());
}
void Twist::ReverseSign()
{
vel.ReverseSign();
rot.ReverseSign();
}
Twist Twist::RefPoint(const Vector& v_base_AB) const
// Changes the reference point of the twist.
// The vector v_base_AB is expressed in the same base as the twist
// The vector v_base_AB is a vector from the old point to
// the new point.
// Complexity : 6M+6A
{
return Twist(this->vel+this->rot*v_base_AB,this->rot);
}
Twist& Twist::operator-=(const Twist& arg)
{
vel-=arg.vel;
rot -=arg.rot;
return *this;
}
Twist& Twist::operator+=(const Twist& arg)
{
vel+=arg.vel;
rot +=arg.rot;
return *this;
}
double& Twist::operator()(int i)
{
// assert((0<=i)&&(i<6)); done by underlying routines
if (i<3)
return vel(i);
else
return rot(i-3);
}
double Twist::operator()(int i) const
{
// assert((0<=i)&&(i<6)); done by underlying routines
if (i<3)
return vel(i);
else
return rot(i-3);
}
Twist operator*(const Twist& lhs,double rhs)
{
return Twist(lhs.vel*rhs,lhs.rot*rhs);
}
Twist operator*(double lhs,const Twist& rhs)
{
return Twist(lhs*rhs.vel,lhs*rhs.rot);
}
Twist operator/(const Twist& lhs,double rhs)
{
return Twist(lhs.vel/rhs,lhs.rot/rhs);
}
// addition of Twist's
Twist operator+(const Twist& lhs,const Twist& rhs)
{
return Twist(lhs.vel+rhs.vel,lhs.rot+rhs.rot);
}
Twist operator-(const Twist& lhs,const Twist& rhs)
{
return Twist(lhs.vel-rhs.vel,lhs.rot-rhs.rot);
}
// unary -
Twist operator-(const Twist& arg)
{
return Twist(-arg.vel,-arg.rot);
}
//Spatial products for twists
Twist operator*(const Twist& lhs,const Twist& rhs)
{
return Twist(lhs.rot*rhs.vel+lhs.vel*rhs.rot,lhs.rot*rhs.rot);
}
Wrench operator*(const Twist& lhs,const Wrench& rhs)
{
return Wrench(lhs.rot*rhs.force,lhs.rot*rhs.torque+lhs.vel*rhs.force);
}
Frame::Frame(const Rotation & R)
{
M=R;
p=Vector::Zero();
}
Frame::Frame(const Vector & V)
{
M = Rotation::Identity();
p = V;
}
Frame::Frame(const Rotation & R, const Vector & V)
{
M = R;
p = V;
}
Frame operator *(const Frame& lhs,const Frame& rhs)
// Complexity : 36M+36A
{
return Frame(lhs.M*rhs.M,lhs.M*rhs.p+lhs.p);
}
Vector Frame::operator *(const Vector & arg) const
{
return M*arg+p;
}
Vector Frame::Inverse(const Vector& arg) const
{
return M.Inverse(arg-p);
}
Frame Frame::Inverse() const
{
return Frame(M.Inverse(),-M.Inverse(p));
}
Frame& Frame::operator =(const Frame & arg)
{
M = arg.M;
p = arg.p;
return *this;
}
Frame::Frame(const Frame & arg) :
p(arg.p),M(arg.M)
{}
void Vector::ReverseSign()
{
data[0] = -data[0];
data[1] = -data[1];
data[2] = -data[2];
}
Vector operator-(const Vector & arg)
{
Vector tmp;
tmp.data[0]=-arg.data[0];
tmp.data[1]=-arg.data[1];
tmp.data[2]=-arg.data[2];
return tmp;
}
void Vector::Set2DXY(const Vector2& v)
// a 3D vector where the 2D vector v is put in the XY plane
{
data[0]=v(0);
data[1]=v(1);
data[2]=0;
}
void Vector::Set2DYZ(const Vector2& v)
// a 3D vector where the 2D vector v is put in the YZ plane
{
data[1]=v(0);
data[2]=v(1);
data[0]=0;
}
void Vector::Set2DZX(const Vector2& v)
// a 3D vector where the 2D vector v is put in the ZX plane
{
data[2]=v(0);
data[0]=v(1);
data[1]=0;
}
double& Rotation::operator()(int i,int j) {
FRAMES_CHECKI((0<=i)&&(i<=2)&&(0<=j)&&(j<=2));
return data[i*3+j];
}
double Rotation::operator()(int i,int j) const {
FRAMES_CHECKI((0<=i)&&(i<=2)&&(0<=j)&&(j<=2));
return data[i*3+j];
}
Rotation::Rotation( double Xx,double Yx,double Zx,
double Xy,double Yy,double Zy,
double Xz,double Yz,double Zz)
{
data[0] = Xx;data[1]=Yx;data[2]=Zx;
data[3] = Xy;data[4]=Yy;data[5]=Zy;
data[6] = Xz;data[7]=Yz;data[8]=Zz;
}
Rotation::Rotation(const Vector& x,const Vector& y,const Vector& z)
{
data[0] = x.data[0];data[3] = x.data[1];data[6] = x.data[2];
data[1] = y.data[0];data[4] = y.data[1];data[7] = y.data[2];
data[2] = z.data[0];data[5] = z.data[1];data[8] = z.data[2];
}
Rotation& Rotation::operator=(const Rotation& arg) {
int count=9;
while (count--) data[count] = arg.data[count];
return *this;
}
Vector Rotation::operator*(const Vector& v) const {
// Complexity : 9M+6A
return Vector(
data[0]*v.data[0] + data[1]*v.data[1] + data[2]*v.data[2],
data[3]*v.data[0] + data[4]*v.data[1] + data[5]*v.data[2],
data[6]*v.data[0] + data[7]*v.data[1] + data[8]*v.data[2]
);
}
Twist Rotation::operator * (const Twist& arg) const
// Transformation of the base to which the twist is expressed.
// look at Frame*Twist for a transformation that also transforms
// the velocity reference point.
// Complexity : 18M+12A
{
return Twist((*this)*arg.vel,(*this)*arg.rot);
}
Wrench Rotation::operator * (const Wrench& arg) const
// Transformation of the base to which the wrench is expressed.
// look at Frame*Twist for a transformation that also transforms
// the force reference point.
{
return Wrench((*this)*arg.force,(*this)*arg.torque);
}
Rotation Rotation::Identity() {
return Rotation(1,0,0,0,1,0,0,0,1);
}
// *this = *this * ROT(X,angle)
void Rotation::DoRotX(double angle)
{
double cs = cos(angle);
double sn = sin(angle);
double x1,x2,x3;
x1 = cs* (*this)(0,1) + sn* (*this)(0,2);
x2 = cs* (*this)(1,1) + sn* (*this)(1,2);
x3 = cs* (*this)(2,1) + sn* (*this)(2,2);
(*this)(0,2) = -sn* (*this)(0,1) + cs* (*this)(0,2);
(*this)(1,2) = -sn* (*this)(1,1) + cs* (*this)(1,2);
(*this)(2,2) = -sn* (*this)(2,1) + cs* (*this)(2,2);
(*this)(0,1) = x1;
(*this)(1,1) = x2;
(*this)(2,1) = x3;
}
void Rotation::DoRotY(double angle)
{
double cs = cos(angle);
double sn = sin(angle);
double x1,x2,x3;
x1 = cs* (*this)(0,0) - sn* (*this)(0,2);
x2 = cs* (*this)(1,0) - sn* (*this)(1,2);
x3 = cs* (*this)(2,0) - sn* (*this)(2,2);
(*this)(0,2) = sn* (*this)(0,0) + cs* (*this)(0,2);
(*this)(1,2) = sn* (*this)(1,0) + cs* (*this)(1,2);
(*this)(2,2) = sn* (*this)(2,0) + cs* (*this)(2,2);
(*this)(0,0) = x1;
(*this)(1,0) = x2;
(*this)(2,0) = x3;
}
void Rotation::DoRotZ(double angle)
{
double cs = cos(angle);
double sn = sin(angle);
double x1,x2,x3;
x1 = cs* (*this)(0,0) + sn* (*this)(0,1);
x2 = cs* (*this)(1,0) + sn* (*this)(1,1);
x3 = cs* (*this)(2,0) + sn* (*this)(2,1);
(*this)(0,1) = -sn* (*this)(0,0) + cs* (*this)(0,1);
(*this)(1,1) = -sn* (*this)(1,0) + cs* (*this)(1,1);
(*this)(2,1) = -sn* (*this)(2,0) + cs* (*this)(2,1);
(*this)(0,0) = x1;
(*this)(1,0) = x2;
(*this)(2,0) = x3;
}
Rotation Rotation::RotX(double angle) {
double cs=cos(angle);
double sn=sin(angle);
return Rotation(1,0,0,0,cs,-sn,0,sn,cs);
}
Rotation Rotation::RotY(double angle) {
double cs=cos(angle);
double sn=sin(angle);
return Rotation(cs,0,sn,0,1,0,-sn,0,cs);
}
Rotation Rotation::RotZ(double angle) {
double cs=cos(angle);
double sn=sin(angle);
return Rotation(cs,-sn,0,sn,cs,0,0,0,1);
}
void Frame::Integrate(const Twist& t_this,double samplefrequency)
{
double n = t_this.rot.Norm()/samplefrequency;
if (n<epsilon) {
p += M*(t_this.vel/samplefrequency);
} else {
(*this) = (*this) *
Frame ( Rotation::Rot( t_this.rot, n ),
t_this.vel/samplefrequency
);
}
}
Rotation Rotation::Inverse() const
{
Rotation tmp(*this);
tmp.SetInverse();
return tmp;
}
Vector Rotation::Inverse(const Vector& v) const {
return Vector(
data[0]*v.data[0] + data[3]*v.data[1] + data[6]*v.data[2],
data[1]*v.data[0] + data[4]*v.data[1] + data[7]*v.data[2],
data[2]*v.data[0] + data[5]*v.data[1] + data[8]*v.data[2]
);
}
void Rotation::SetInverse()
{
double tmp;
tmp = data[1];data[1]=data[3];data[3]=tmp;
tmp = data[2];data[2]=data[6];data[6]=tmp;
tmp = data[5];data[5]=data[7];data[7]=tmp;
}
double Frame::operator()(int i,int j) {
FRAMES_CHECKI((0<=i)&&(i<=3)&&(0<=j)&&(j<=3));
if (i==3) {
if (j==3)
return 1.0;
else
return 0.0;
} else {
if (j==3)
return p(i);
else
return M(i,j);
}
}
double Frame::operator()(int i,int j) const {
FRAMES_CHECKI((0<=i)&&(i<=3)&&(0<=j)&&(j<=3));
if (i==3) {
if (j==3)
return 1;
else
return 0;
} else {
if (j==3)
return p(i);
else
return M(i,j);
}
}
Frame Frame::Identity() {
return Frame(Rotation::Identity(),Vector::Zero());
}
void Vector::Set2DPlane(const Frame& F_someframe_XY,const Vector2& v_XY)
// a 3D vector where the 2D vector v is put in the XY plane of the frame
// F_someframe_XY.
{
Vector tmp_XY;
tmp_XY.Set2DXY(v_XY);
tmp_XY = F_someframe_XY*(tmp_XY);
}
//============ 2 dimensional version of the frames objects =============
IMETHOD Vector2::Vector2(const Vector2 & arg)
{
data[0] = arg.data[0];
data[1] = arg.data[1];
}
IMETHOD Vector2::Vector2(double x,double y)
{
data[0]=x;data[1]=y;
}
IMETHOD Vector2& Vector2::operator =(const Vector2 & arg)
{
data[0] = arg.data[0];
data[1] = arg.data[1];
return *this;
}
IMETHOD Vector2 operator +(const Vector2 & lhs,const Vector2& rhs)
{
return Vector2(lhs.data[0]+rhs.data[0],lhs.data[1]+rhs.data[1]);
}
IMETHOD Vector2 operator -(const Vector2 & lhs,const Vector2& rhs)
{
return Vector2(lhs.data[0]-rhs.data[0],lhs.data[1]-rhs.data[1]);
}
IMETHOD Vector2 operator *(const Vector2& lhs,double rhs)
{
return Vector2(lhs.data[0]*rhs,lhs.data[1]*rhs);
}
IMETHOD Vector2 operator *(double lhs,const Vector2& rhs)
{
return Vector2(lhs*rhs.data[0],lhs*rhs.data[1]);
}
IMETHOD Vector2 operator /(const Vector2& lhs,double rhs)
{
return Vector2(lhs.data[0]/rhs,lhs.data[1]/rhs);
}
IMETHOD Vector2& Vector2::operator +=(const Vector2 & arg)
{
data[0]+=arg.data[0];
data[1]+=arg.data[1];
return *this;
}
IMETHOD Vector2& Vector2::operator -=(const Vector2 & arg)
{
data[0]-=arg.data[0];
data[1]-=arg.data[1];
return *this;
}
IMETHOD Vector2 Vector2::Zero() {
return Vector2(0,0);
}
IMETHOD double Vector2::operator()(int index) const {
FRAMES_CHECKI((0<=index)&&(index<=1));
return data[index];
}
IMETHOD double& Vector2::operator () (int index)
{
FRAMES_CHECKI((0<=index)&&(index<=1));
return data[index];
}
IMETHOD double Vector2::x() const { return data[0]; }
IMETHOD double Vector2::y() const { return data[1]; }
IMETHOD void Vector2::x( double _x ) { data[0] = _x; }
IMETHOD void Vector2::y( double _y ) { data[1] = _y; }
IMETHOD void Vector2::ReverseSign()
{
data[0] = -data[0];
data[1] = -data[1];
}
IMETHOD Vector2 operator-(const Vector2 & arg)
{
return Vector2(-arg.data[0],-arg.data[1]);
}
IMETHOD void Vector2::Set3DXY(const Vector& v)
// projects v in its XY plane, and sets *this to these values
{
data[0]=v(0);
data[1]=v(1);
}
IMETHOD void Vector2::Set3DYZ(const Vector& v)
// projects v in its XY plane, and sets *this to these values
{
data[0]=v(1);
data[1]=v(2);
}
IMETHOD void Vector2::Set3DZX(const Vector& v)
// projects v in its XY plane, and and sets *this to these values
{
data[0]=v(2);
data[1]=v(0);
}
IMETHOD void Vector2::Set3DPlane(const Frame& F_someframe_XY,const Vector& v_someframe)
// projects v in the XY plane of F_someframe_XY, and sets *this to these values
// expressed wrt someframe.
{
Vector tmp = F_someframe_XY.Inverse(v_someframe);
data[0]=tmp(0);
data[1]=tmp(1);
}
IMETHOD Rotation2& Rotation2::operator=(const Rotation2& arg) {
c=arg.c;s=arg.s;
return *this;
}
IMETHOD Vector2 Rotation2::operator*(const Vector2& v) const {
return Vector2(v.data[0]*c-v.data[1]*s,v.data[0]*s+v.data[1]*c);
}
IMETHOD double Rotation2::operator()(int i,int j) const {
FRAMES_CHECKI((0<=i)&&(i<=1)&&(0<=j)&&(j<=1));
if (i==j) return c;
if (i==0)
return s;
else
return -s;
}
IMETHOD Rotation2 operator *(const Rotation2& lhs,const Rotation2& rhs) {
return Rotation2(lhs.c*rhs.c-lhs.s*rhs.s,lhs.s*rhs.c+lhs.c*rhs.s);
}
IMETHOD void Rotation2::SetInverse() {
s=-s;
}
IMETHOD Rotation2 Rotation2::Inverse() const {
return Rotation2(c,-s);
}
IMETHOD Vector2 Rotation2::Inverse(const Vector2& v) const {
return Vector2(v.data[0]*c+v.data[1]*s,-v.data[0]*s+v.data[1]*c);
}
IMETHOD Rotation2 Rotation2::Identity() {
return Rotation2(1,0);
}
IMETHOD void Rotation2::SetIdentity()
{
c = 1;
s = 0;
}
IMETHOD void Rotation2::SetRot(double angle) {
c=cos(angle);s=sin(angle);
}
IMETHOD Rotation2 Rotation2::Rot(double angle) {
return Rotation2(cos(angle),sin(angle));
}
IMETHOD double Rotation2::GetRot() const {
return atan2(s,c);
}
IMETHOD Frame2::Frame2() {
}
IMETHOD Frame2::Frame2(const Rotation2 & R)
{
M=R;
p=Vector2::Zero();
}
IMETHOD Frame2::Frame2(const Vector2 & V)
{
M = Rotation2::Identity();
p = V;
}
IMETHOD Frame2::Frame2(const Rotation2 & R, const Vector2 & V)
{
M = R;
p = V;
}
IMETHOD Frame2 operator *(const Frame2& lhs,const Frame2& rhs)
{
return Frame2(lhs.M*rhs.M,lhs.M*rhs.p+lhs.p);
}
IMETHOD Vector2 Frame2::operator *(const Vector2 & arg)
{
return M*arg+p;
}
IMETHOD Vector2 Frame2::Inverse(const Vector2& arg) const
{
return M.Inverse(arg-p);
}
IMETHOD void Frame2::SetIdentity()
{
M.SetIdentity();
p = Vector2::Zero();
}
IMETHOD void Frame2::SetInverse()
{
M.SetInverse();
p = M*p;
p.ReverseSign();
}
IMETHOD Frame2 Frame2::Inverse() const
{
Frame2 tmp(*this);
tmp.SetInverse();
return tmp;
}
IMETHOD Frame2& Frame2::operator =(const Frame2 & arg)
{
M = arg.M;
p = arg.p;
return *this;
}
IMETHOD Frame2::Frame2(const Frame2 & arg) :
p(arg.p), M(arg.M)
{}
IMETHOD double Frame2::operator()(int i,int j) {
FRAMES_CHECKI((0<=i)&&(i<=2)&&(0<=j)&&(j<=2));
if (i==2) {
if (j==2)
return 1;
else
return 0;
} else {
if (j==2)
return p(i);
else
return M(i,j);
}
}
IMETHOD double Frame2::operator()(int i,int j) const {
FRAMES_CHECKI((0<=i)&&(i<=2)&&(0<=j)&&(j<=2));
if (i==2) {
if (j==2)
return 1;
else
return 0;
} else {
if (j==2)
return p(i);
else
return M(i,j);
}
}
// Scalar products.
IMETHOD double dot(const Vector& lhs,const Vector& rhs) {
return rhs(0)*lhs(0)+rhs(1)*lhs(1)+rhs(2)*lhs(2);
}
IMETHOD double dot(const Twist& lhs,const Wrench& rhs) {
return dot(lhs.vel,rhs.force)+dot(lhs.rot,rhs.torque);
}
IMETHOD double dot(const Wrench& rhs,const Twist& lhs) {
return dot(lhs.vel,rhs.force)+dot(lhs.rot,rhs.torque);
}
// Equality operators
IMETHOD bool Equal(const Vector& a,const Vector& b,double eps) {
return (Equal(a.data[0],b.data[0],eps)&&
Equal(a.data[1],b.data[1],eps)&&
Equal(a.data[2],b.data[2],eps) );
}
IMETHOD bool Equal(const Frame& a,const Frame& b,double eps) {
return (Equal(a.p,b.p,eps)&&
Equal(a.M,b.M,eps) );
}
IMETHOD bool Equal(const Wrench& a,const Wrench& b,double eps) {
return (Equal(a.force,b.force,eps)&&
Equal(a.torque,b.torque,eps) );
}
IMETHOD bool Equal(const Twist& a,const Twist& b,double eps) {
return (Equal(a.rot,b.rot,eps)&&
Equal(a.vel,b.vel,eps) );
}
IMETHOD bool Equal(const Vector2& a,const Vector2& b,double eps) {
return (Equal(a.data[0],b.data[0],eps)&&
Equal(a.data[1],b.data[1],eps) );
}
IMETHOD bool Equal(const Rotation2& a,const Rotation2& b,double eps) {
return ( Equal(a.c,b.c,eps) && Equal(a.s,b.s,eps) );
}
IMETHOD bool Equal(const Frame2& a,const Frame2& b,double eps) {
return (Equal(a.p,b.p,eps)&&
Equal(a.M,b.M,eps) );
}
IMETHOD void SetToZero(Vector& v) {
v=Vector::Zero();
}
IMETHOD void SetToZero(Twist& v) {
SetToZero(v.rot);
SetToZero(v.vel);
}
IMETHOD void SetToZero(Wrench& v) {
SetToZero(v.force);
SetToZero(v.torque);
}
IMETHOD void SetToZero(Vector2& v) {
v = Vector2::Zero();
}
////////////////////////////////////////////////////////////////
// The following defines the operations
// diff
// addDelta
// random
// posrandom
// on all the types defined in this library.
// (mostly for uniform integration, differentiation and testing).
// Defined as functions because double is not a class and a method
// would brake uniformity when defined for a double.
////////////////////////////////////////////////////////////////
/**
* axis_a_b is a rotation vector, its norm is a rotation angle
* axis_a_b rotates the a frame towards the b frame.
* This routine returns the rotation matrix R_a_b
*/
IMETHOD Rotation Rot(const Vector& axis_a_b) {
// The formula is
// V.(V.tr) + st*[V x] + ct*(I-V.(V.tr))
// can be found by multiplying it with an arbitrary vector p
// and noting that this vector is rotated.
Vector rotvec = axis_a_b;
double angle = rotvec.Normalize(1E-10);
double ct = ::cos(angle);
double st = ::sin(angle);
double vt = 1-ct;
return Rotation(
ct + vt*rotvec(0)*rotvec(0),
-rotvec(2)*st + vt*rotvec(0)*rotvec(1),
rotvec(1)*st + vt*rotvec(0)*rotvec(2),
rotvec(2)*st + vt*rotvec(1)*rotvec(0),
ct + vt*rotvec(1)*rotvec(1),
-rotvec(0)*st + vt*rotvec(1)*rotvec(2),
-rotvec(1)*st + vt*rotvec(2)*rotvec(0),
rotvec(0)*st + vt*rotvec(2)*rotvec(1),
ct + vt*rotvec(2)*rotvec(2)
);
}
IMETHOD Vector diff(const Vector& a,const Vector& b,double dt) {
return (b-a)/dt;
}
IMETHOD Vector diff(const Rotation& R_a_b1,const Rotation& R_a_b2,double dt) {
Rotation R_b1_b2(R_a_b1.Inverse()*R_a_b2);
return R_a_b1 * R_b1_b2.GetRot() / dt;
}
IMETHOD Twist diff(const Frame& F_a_b1,const Frame& F_a_b2,double dt) {
return Twist(
diff(F_a_b1.p,F_a_b2.p,dt),
diff(F_a_b1.M,F_a_b2.M,dt)
);
}
IMETHOD Twist diff(const Twist& a,const Twist& b,double dt) {
return Twist(diff(a.vel,b.vel,dt),diff(a.rot,b.rot,dt));
}
IMETHOD Wrench diff(const Wrench& a,const Wrench& b,double dt) {
return Wrench(
diff(a.force,b.force,dt),
diff(a.torque,b.torque,dt)
);
}
IMETHOD Vector addDelta(const Vector& a,const Vector&da,double dt) {
return a+da*dt;
}
IMETHOD Rotation addDelta(const Rotation& a,const Vector&da,double dt) {
return a*Rot(a.Inverse(da)*dt);
}
IMETHOD Frame addDelta(const Frame& a,const Twist& da,double dt) {
return Frame(
addDelta(a.M,da.rot,dt),
addDelta(a.p,da.vel,dt)
);
}
IMETHOD Twist addDelta(const Twist& a,const Twist&da,double dt) {
return Twist(addDelta(a.vel,da.vel,dt),addDelta(a.rot,da.rot,dt));
}
IMETHOD Wrench addDelta(const Wrench& a,const Wrench&da,double dt) {
return Wrench(addDelta(a.force,da.force,dt),addDelta(a.torque,da.torque,dt));
}
/**
* \brief addDelta operator for displacement rotational velocity.
*
* The Vector arguments here represent a displacement rotational velocity. i.e. a rotation
* around a fixed axis for a certain angle. For this representation you cannot use diff() but
* have to use diff_displ().
*
* \param a : displacement rotational velocity
* \param da : rotational velocity
* \return displacement rotational velocity
*
* \warning do not confuse displacement rotational velocities and velocities
* \warning do not confuse displacement twist and twist.
*
IMETHOD Vector addDelta_displ(const Vector& a,const Vector&da,double dt) {
return getRot(addDelta(Rot(a),da,dt));
}*/
/**
* \brief addDelta operator for displacement twist.
*
* The Vector arguments here represent a displacement rotational velocity. i.e. a rotation
* around a fixed axis for a certain angle. For this representation you cannot use diff() but
* have to use diff_displ().
*
* \param a : displacement twist
* \param da : twist
* \return displacement twist
*
* \warning do not confuse displacement rotational velocities and velocities
* \warning do not confuse displacement twist and twist.
*
IMETHOD Twist addDelta_displ(const Twist& a,const Twist&da,double dt) {
return Twist(addDelta(a.vel,da.vel,dt),addDelta_displ(a.rot,da.rot,dt));
}*/
IMETHOD void random(Vector& a) {
random(a[0]);
random(a[1]);
random(a[2]);
}
IMETHOD void random(Twist& a) {
random(a.rot);
random(a.vel);
}
IMETHOD void random(Wrench& a) {
random(a.torque);
random(a.force);
}
IMETHOD void random(Rotation& R) {
double alfa;
double beta;
double gamma;
random(alfa);
random(beta);
random(gamma);
R = Rotation::EulerZYX(alfa,beta,gamma);
}
IMETHOD void random(Frame& F) {
random(F.M);
random(F.p);
}
IMETHOD void posrandom(Vector& a) {
posrandom(a[0]);
posrandom(a[1]);
posrandom(a[2]);
}
IMETHOD void posrandom(Twist& a) {
posrandom(a.rot);
posrandom(a.vel);
}
IMETHOD void posrandom(Wrench& a) {
posrandom(a.torque);
posrandom(a.force);
}
IMETHOD void posrandom(Rotation& R) {
double alfa;
double beta;
double gamma;
posrandom(alfa);
posrandom(beta);
posrandom(gamma);
R = Rotation::EulerZYX(alfa,beta,gamma);
}
IMETHOD void posrandom(Frame& F) {
random(F.M);
random(F.p);
}
IMETHOD bool operator==(const Frame& a,const Frame& b ) {
#ifdef KDL_USE_EQUAL
return Equal(a,b);
#else
return (a.p == b.p &&
a.M == b.M );
#endif
}
IMETHOD bool operator!=(const Frame& a,const Frame& b) {
return !operator==(a,b);
}
IMETHOD bool operator==(const Vector& a,const Vector& b) {
#ifdef KDL_USE_EQUAL
return Equal(a,b);
#else
return (a.data[0]==b.data[0]&&
a.data[1]==b.data[1]&&
a.data[2]==b.data[2] );
#endif
}
IMETHOD bool operator!=(const Vector& a,const Vector& b) {
return !operator==(a,b);
}
IMETHOD bool operator==(const Twist& a,const Twist& b) {
#ifdef KDL_USE_EQUAL
return Equal(a,b);
#else
return (a.rot==b.rot &&
a.vel==b.vel );
#endif
}
IMETHOD bool operator!=(const Twist& a,const Twist& b) {
return !operator==(a,b);
}
IMETHOD bool operator==(const Wrench& a,const Wrench& b ) {
#ifdef KDL_USE_EQUAL
return Equal(a,b);
#else
return (a.force==b.force &&
a.torque==b.torque );
#endif
}
IMETHOD bool operator!=(const Wrench& a,const Wrench& b) {
return !operator==(a,b);
}
IMETHOD bool operator!=(const Rotation& a,const Rotation& b) {
return !operator==(a,b);
}
IMETHOD bool operator==(const Vector2& a,const Vector2& b) {
#ifdef KDL_USE_EQUAL
return Equal(a,b);
#else
return (a.data[0]==b.data[0]&&
a.data[1]==b.data[1] );
#endif
}
IMETHOD bool operator!=(const Vector2& a,const Vector2& b) {
return !operator==(a,b);
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/joint.hpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_JOINT_HPP
#define KDL_JOINT_HPP
#include "frames.hpp"
#include <string>
#include <exception>
namespace KDL {
/**
* \brief This class encapsulates a simple joint, that is with one
* parameterized degree of freedom and with scalar dynamic properties.
*
* A simple joint is described by the following properties :
* - scale: ratio between motion input and motion output
* - offset: between the "physical" and the "logical" zero position.
* - type: revolute or translational, along one of the basic frame axes
* - inertia, stiffness and damping: scalars representing the physical
* effects along/about the joint axis only.
*
* @ingroup KinematicFamily
*/
class Joint {
public:
typedef enum { RotAxis,RotX,RotY,RotZ,TransAxis,TransX,TransY,TransZ,None} JointType;
/**
* Constructor of a joint.
*
* @param name of the joint
* @param type type of the joint, default: Joint::None
* @param scale scale between joint input and actual geometric
* movement, default: 1
* @param offset offset between joint input and actual
* geometric input, default: 0
* @param inertia 1D inertia along the joint axis, default: 0
* @param damping 1D damping along the joint axis, default: 0
* @param stiffness 1D stiffness along the joint axis,
* default: 0
*/
explicit Joint(const std::string& name, const JointType& type=None,const double& scale=1,const double& offset=0,
const double& inertia=0,const double& damping=0,const double& stiffness=0);
/**
* Constructor of a joint.
*
* @param type type of the joint, default: Joint::None
* @param scale scale between joint input and actual geometric
* movement, default: 1
* @param offset offset between joint input and actual
* geometric input, default: 0
* @param inertia 1D inertia along the joint axis, default: 0
* @param damping 1D damping along the joint axis, default: 0
* @param stiffness 1D stiffness along the joint axis,
* default: 0
*/
explicit Joint(const JointType& type=None,const double& scale=1,const double& offset=0,
const double& inertia=0,const double& damping=0,const double& stiffness=0);
/**
* Constructor of a joint.
*
* @param name of the joint
* @param origin the origin of the joint
* @param axis the axis of the joint
* @param scale scale between joint input and actual geometric
* movement, default: 1
* @param offset offset between joint input and actual
* geometric input, default: 0
* @param inertia 1D inertia along the joint axis, default: 0
* @param damping 1D damping along the joint axis, default: 0
* @param stiffness 1D stiffness along the joint axis,
* default: 0
*/
Joint(const std::string& name, const Vector& _origin, const Vector& _axis, const JointType& type, const double& _scale=1, const double& _offset=0,
const double& _inertia=0, const double& _damping=0, const double& _stiffness=0);
/**
* Constructor of a joint.
*
* @param origin the origin of the joint
* @param axis the axis of the joint
* @param scale scale between joint input and actual geometric
* movement, default: 1
* @param offset offset between joint input and actual
* geometric input, default: 0
* @param inertia 1D inertia along the joint axis, default: 0
* @param damping 1D damping along the joint axis, default: 0
* @param stiffness 1D stiffness along the joint axis,
* default: 0
*/
Joint(const Vector& _origin, const Vector& _axis, const JointType& type, const double& _scale=1, const double& _offset=0,
const double& _inertia=0, const double& _damping=0, const double& _stiffness=0);
/**
* Request the 6D-pose between the beginning and the end of
* the joint at joint position q
*
* @param q the 1D joint position
*
* @return the resulting 6D-pose
*/
Frame pose(const double& q)const;
/**
* Request the resulting 6D-velocity with a joint velocity qdot
*
* @param qdot the 1D joint velocity
*
* @return the resulting 6D-velocity
*/
Twist twist(const double& qdot)const;
/**
* Request the Vector corresponding to the axis of a revolute joint.
*
* @return Vector. e.g (1,0,0) for RotX etc.
*/
Vector JointAxis() const;
/**
* Request the Vector corresponding to the origin of a revolute joint.
*
* @return Vector
*/
Vector JointOrigin() const;
/**
* Request the name of the joint
*
*
* @return const reference to the name of the joint
*/
const std::string& getName()const
{
return name;
}
/**
* Request the type of the joint.
*
* @return const reference to the type
*/
const JointType& getType() const
{
return type;
};
/**
* Request the stringified type of the joint.
*
* @return const string
*/
const std::string getTypeName() const
{
switch (type) {
case RotAxis:
return "RotAxis";
case TransAxis:
return "TransAxis";
case RotX:
return "RotX";
case RotY:
return "RotY";
case RotZ:
return "RotZ";
case TransX:
return "TransX";
case TransY:
return "TransY";
case TransZ:
return "TransZ";
case None:
return "None";
default:
return "None";
}
};
virtual ~Joint();
private:
std::string name;
Joint::JointType type;
double scale;
double offset;
double inertia;
double damping;
double stiffness;
// variables for RotAxis joint
Vector axis, origin;
mutable Frame joint_pose;
mutable double q_previous;
class joint_type_exception: public std::exception{
virtual const char* what() const throw(){
return "Joint Type excption";}
} joint_type_ex;
};
} // end of namespace KDL
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/velocityprofile_dirac.hpp | /***************************************************************************
tag: Peter Soetens Fri Feb 11 15:59:12 CET 2005 velocityprofile_dirac.h
velocityprofile_dirac.h - description
-------------------
begin : Fri February 11 2005
copyright : (C) 2005 Peter Soetens
email : peter.soetens@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#ifndef MOTIONPROFILE_DIRAC_H
#define MOTIONPROFILE_DIRAC_H
#include "velocityprofile.hpp"
namespace KDL {
/**
* A Dirac VelocityProfile generates an infinite velocity
* so that the position jumps from A to B in in infinite short time.
* In practice, this means that the maximum values are ignored and
* for any t : Vel(t) == 0 and Acc(t) == 0.
* Further Pos( -0 ) = pos1 and Pos( +0 ) = pos2.
*
* However, if a duration is given, it will create an unbound
* rectangular velocity profile for that duration, otherwise,
* Duration() == 0;
* @ingroup Motion
*/
class VelocityProfile_Dirac : public VelocityProfile
{
double p1,p2,t;
public:
void SetProfile(double pos1,double pos2);
virtual void SetProfileDuration(double pos1,double pos2,double duration);
virtual double Duration() const;
virtual double Pos(double time) const;
virtual double Vel(double time) const;
virtual double Acc(double time) const;
virtual void Write(std::ostream& os) const;
virtual VelocityProfile* Clone() const {
VelocityProfile_Dirac* res = new VelocityProfile_Dirac();
res->SetProfileDuration( p1, p2, t );
return res;
}
virtual ~VelocityProfile_Dirac() {}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/velocityprofile_traphalf.cpp | /***************************************************************************
tag: Erwin Aertbelien Mon May 10 19:10:36 CEST 2004 velocityprofile_traphalf.cxx
velocityprofile_traphalf.cxx - description
-------------------
begin : Mon May 10 2004
copyright : (C) 2004 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: velocityprofile_traphalf.cpp,v 1.1.1.1.2.5 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
//#include "error.h"
#include "velocityprofile_traphalf.hpp"
namespace KDL {
VelocityProfile_TrapHalf::VelocityProfile_TrapHalf(double _maxvel,double _maxacc,bool _starting):
maxvel(_maxvel),maxacc(_maxacc),starting(_starting) {}
void VelocityProfile_TrapHalf::SetMax(double _maxvel,double _maxacc, bool _starting)
{
maxvel = _maxvel; maxacc = _maxacc; starting = _starting;
}
void VelocityProfile_TrapHalf::PlanProfile1(double v,double a) {
a3 = 0;
a2 = 0;
a1 = startpos;
b3 = a/2;
b2 = -a*t1;
b1 = startpos + a*t1*t1/2;
c3 = 0;
c2 = v;
c1 = endpos - v*duration;
}
void VelocityProfile_TrapHalf::PlanProfile2(double v,double a) {
a3 = 0;
a2 = v;
a1 = startpos;
b3 = -a/2;
b2 = a*t2;
b1 = endpos - a*t2*t2/2;
c3 = 0;
c2 = 0;
c1 = endpos;
}
void VelocityProfile_TrapHalf::SetProfile(double pos1,double pos2) {
startpos = pos1;
endpos = pos2;
double s = sign(endpos-startpos);
duration = s*(endpos-startpos)/maxvel+maxvel/maxacc/2.0;
if (starting) {
t1 = 0;
t2 = maxvel/maxacc;
PlanProfile1(maxvel*s,maxacc*s);
} else {
t1 = duration-maxvel/maxacc;
t2 = duration;
PlanProfile2(s*maxvel,s*maxacc);
}
}
void VelocityProfile_TrapHalf::SetProfileDuration(
double pos1,double pos2,double newduration)
{
SetProfile(pos1,pos2);
double factor = duration/newduration;
if ( factor > 1 )
return;
double s = sign(endpos-startpos);
double tmp = 2.0*s*(endpos-startpos)/maxvel;
double v = s*maxvel;
duration = newduration;
if (starting) {
if (tmp > duration) {
t1 = 0;
double a = v*v/2.0/(v*duration-(endpos-startpos));
t2 = v/a;
PlanProfile1(v,a);
} else {
t2 = duration;
double a = v*v/2.0/(endpos-startpos);
t1 = t2-v/a;
PlanProfile1(v,a);
}
} else {
if (tmp > duration) {
t2 = duration;
double a = v*v/2.0/(v*duration-(endpos-startpos));
t1 = t2-v/a;
PlanProfile2(v,a);
} else {
double a = v*v/2.0/(endpos-startpos);
t1 = 0;
t2 = v/a;
PlanProfile2(v,a);
}
}
}
double VelocityProfile_TrapHalf::Duration() const {
return duration;
}
double VelocityProfile_TrapHalf::Pos(double time) const {
if (time < 0) {
return startpos;
} else if (time<t1) {
return a1+time*(a2+a3*time);
} else if (time<t2) {
return b1+time*(b2+b3*time);
} else if (time<=duration) {
return c1+time*(c2+c3*time);
} else {
return endpos;
}
}
double VelocityProfile_TrapHalf::Vel(double time) const {
if (time < 0) {
return 0;
} else if (time<t1) {
return a2+2*a3*time;
} else if (time<t2) {
return b2+2*b3*time;
} else if (time<=duration) {
return c2+2*c3*time;
} else {
return 0;
}
}
double VelocityProfile_TrapHalf::Acc(double time) const {
if (time < 0) {
return 0;
} else if (time<t1) {
return 2*a3;
} else if (time<t2) {
return 2*b3;
} else if (time<=duration) {
return 2*c3;
} else {
return 0;
}
}
VelocityProfile* VelocityProfile_TrapHalf::Clone() const {
VelocityProfile_TrapHalf* res = new VelocityProfile_TrapHalf(maxvel,maxacc, starting);
res->SetProfileDuration( this->startpos, this->endpos, this->duration );
return res;
}
VelocityProfile_TrapHalf::~VelocityProfile_TrapHalf() {}
void VelocityProfile_TrapHalf::Write(std::ostream& os) const {
os << "TRAPEZOIDALHALF[" << maxvel << "," << maxacc << "," << starting << "]";
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolverpos_nr_jl.hpp | // Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Copyright (C) 2008 Mikael Mayer
// Copyright (C) 2008 Julia Jesse
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDLCHAINIKSOLVERPOS_NR_JL_HPP
#define KDLCHAINIKSOLVERPOS_NR_JL_HPP
#include "chainiksolver.hpp"
#include "chainfksolver.hpp"
namespace KDL {
/**
* Implementation of a general inverse position kinematics
* algorithm based on Newton-Raphson iterations to calculate the
* position transformation from Cartesian to joint space of a general
* KDL::Chain. Takes joint limits into account.
*
* @ingroup KinematicFamily
*/
class ChainIkSolverPos_NR_JL : public ChainIkSolverPos
{
public:
/**
* Constructor of the solver, it needs the chain, a forward
* position kinematics solver and an inverse velocity
* kinematics solver for that chain.
*
* @param chain the chain to calculate the inverse position for
* @param q_min the minimum joint positions
* @param q_max the maximum joint positions
* @param fksolver a forward position kinematics solver
* @param iksolver an inverse velocity kinematics solver
* @param maxiter the maximum Newton-Raphson iterations,
* default: 100
* @param eps the precision for the position, used to end the
* iterations, default: epsilon (defined in kdl.hpp)
*
* @return
*/
ChainIkSolverPos_NR_JL(const Chain& chain,const JntArray& q_min, const JntArray& q_max, ChainFkSolverPos& fksolver,ChainIkSolverVel& iksolver,unsigned int maxiter=100,double eps=1e-6);
~ChainIkSolverPos_NR_JL();
virtual int CartToJnt(const JntArray& q_init, const Frame& p_in, JntArray& q_out);
private:
const Chain chain;
JntArray q_min;
JntArray q_max;
ChainIkSolverVel& iksolver;
ChainFkSolverPos& fksolver;
JntArray delta_q;
unsigned int maxiter;
double eps;
Frame f;
Twist delta_twist;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/treejnttojacsolver.cpp | /*
* TreeJntToJacSolver.cpp
*
* Created on: Nov 27, 2008
* Author: rubensmits
*/
#include "treejnttojacsolver.hpp"
#include <iostream>
#include "kinfam_io.hpp"
namespace KDL {
TreeJntToJacSolver::TreeJntToJacSolver(const Tree& tree_in) :
tree(tree_in) {
}
TreeJntToJacSolver::~TreeJntToJacSolver() {
}
int TreeJntToJacSolver::JntToJac(const JntArray& q_in, Jacobian& jac, const std::string& segmentname) {
//First we check all the sizes:
if (q_in.rows() != tree.getNrOfJoints() || jac.columns() != tree.getNrOfJoints())
return -1;
//Lets search the tree-element
SegmentMap::const_iterator it = tree.getSegments().find(segmentname);
//If segmentname is not inside the tree, back out:
if (it == tree.getSegments().end())
return -2;
//Let's make the jacobian zero:
SetToZero(jac);
SegmentMap::const_iterator root = tree.getRootSegment();
Frame T_total = Frame::Identity();
//Lets recursively iterate until we are in the root segment
while (it != root) {
//get the corresponding q_nr for this TreeElement:
unsigned int q_nr = GetTreeElementQNr(it->second);
//get the pose of the segment:
Frame T_local = GetTreeElementSegment(it->second).pose(q_in(q_nr));
//calculate new T_end:
T_total = T_local * T_total;
//get the twist of the segment:
if (GetTreeElementSegment(it->second).getJoint().getType() != Joint::None) {
Twist t_local = GetTreeElementSegment(it->second).twist(q_in(q_nr), 1.0);
//transform the endpoint of the local twist to the global endpoint:
t_local = t_local.RefPoint(T_total.p - T_local.p);
//transform the base of the twist to the endpoint
t_local = T_total.M.Inverse(t_local);
//store the twist in the jacobian:
jac.setColumn(q_nr,t_local);
}//endif
//goto the parent
it = GetTreeElementParent(it->second);
}//endwhile
//Change the base of the complete jacobian from the endpoint to the base
changeBase(jac, T_total.M, jac);
return 0;
}//end JntToJac
}//end namespace
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainidsolver_vereshchagin.hpp | // Copyright (C) 2009, 2011
// Version: 1.0
// Author: Ruben Smits, Herman Bruyninckx, Azamat Shakhimardanov
// Maintainer: Ruben Smits, Azamat Shakhimardanov
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_CHAINIDSOLVER_VERESHCHAGIN_HPP
#define KDL_CHAINIDSOLVER_VERESHCHAGIN_HPP
#include "chainidsolver.hpp"
#include "frames.hpp"
#include "articulatedbodyinertia.hpp"
namespace KDL
{
/**
* \brief Dynamics calculations by constraints based on Vereshchagin 1989.
* for a chain. This class creates instance of hybrid dynamics solver.
* The solver calculates total joint space accelerations in a chain when a constraint force(s) is applied
* to the chain's end-effector (task space/cartesian space).
*/
class ChainIdSolver_Vereshchagin
{
typedef std::vector<Twist> Twists;
typedef std::vector<Frame> Frames;
typedef Eigen::Matrix<double, 6, 1 > Vector6d;
typedef Eigen::Matrix<double, 6, 6 > Matrix6d;
typedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd;
public:
/**
* Constructor for the solver, it will allocate all the necessary memory
* \param chain The kinematic chain to calculate the inverse dynamics for, an internal copy will be made.
* \param root_acc The acceleration vector of the root to use during the calculation.(most likely contains gravity)
*
*/
ChainIdSolver_Vereshchagin(const Chain& chain, Twist root_acc, unsigned int nc);
~ChainIdSolver_Vereshchagin()
{
};
/**
* This method calculates joint space constraint torques and total joint space acceleration.
* It returns 0 when it succeeds, otherwise -1 or -2 for unmatching matrix and array sizes.
* Input parameters;
* \param q The current joint positions
* \param q_dot The current joint velocities
* \param f_ext The external forces (no gravity, it is given in root acceleration) on the segments.
* Output parameters:
* \param q_dotdot The joint accelerations
* \param torques the resulting constraint torques for the joints
*/
int CartToJnt(const JntArray &q, const JntArray &q_dot, JntArray &q_dotdot, const Jacobian& alfa, const JntArray& beta, const Wrenches& f_ext, JntArray &torques);
/*
//Returns cartesian positions of links in base coordinates
void getLinkCartesianPose(Frames& x_base);
//Returns cartesian velocities of links in base coordinates
void getLinkCartesianVelocity(Twists& xDot_base);
//Returns cartesian acceleration of links in base coordinates
void getLinkCartesianAcceleration(Twists& xDotDot_base);
//Returns cartesian postions of links in link tip coordinates
void getLinkPose(Frames& x_local);
//Returns cartesian velocities of links in link tip coordinates
void getLinkVelocity(Twists& xDot_local);
//Returns cartesian acceleration of links in link tip coordinates
void getLinkAcceleration(Twists& xDotdot_local);
//Acceleration energy due to unit constraint forces at the end-effector
void getLinkUnitForceAccelerationEnergy(Eigen::MatrixXd& M);
//Acceleration energy due to arm configuration: bias force plus input joint torques
void getLinkBiasForceAcceleratoinEnergy(Eigen::VectorXd& G);
void getLinkUnitForceMatrix(Matrix6Xd& E_tilde);
void getLinkBiasForceMatrix(Wrenches& R_tilde);
void getJointBiasAcceleration(JntArray &bias_q_dotdot);
*/
private:
/**
* This method calculates all cartesian space poses, twists, bias accelerations.
* External forces are also taken into account in this outward sweep.
*/
void initial_upwards_sweep(const JntArray &q, const JntArray &q_dot, const JntArray &q_dotdot, const Wrenches& f_ext);
/**
* This method is a force balance sweep. It calculates articulated body inertias and bias forces.
* Additionally, acceleration energies generated by bias forces and unit forces are calculated here.
*/
void downwards_sweep(const Jacobian& alfa, const JntArray& torques);
/**
* This method calculates constraint force magnitudes.
*
*/
void constraint_calculation(const JntArray& beta);
/**
* This method puts all acceleration contributions (constraint, bias, nullspace and parent accelerations) together.
*
*/
void final_upwards_sweep(JntArray &q_dotdot, JntArray &torques);
private:
Chain chain;
unsigned int nj;
unsigned int ns;
unsigned int nc;
Twist acc_root;
Jacobian alfa_N;
Jacobian alfa_N2;
Eigen::MatrixXd M_0_inverse;
Eigen::MatrixXd Um;
Eigen::MatrixXd Vm;
JntArray beta_N;
Eigen::VectorXd nu;
Eigen::VectorXd nu_sum;
Eigen::VectorXd Sm;
Eigen::VectorXd tmpm;
Wrench qdotdot_sum;
Frame F_total;
struct segment_info
{
Frame F; //local pose with respect to previous link in segments coordinates
Frame F_base; // pose of a segment in root coordinates
Twist Z; //Unit twist
Twist v; //twist
Twist acc; //acceleration twist
Wrench U; //wrench p of the bias forces (in cartesian space)
Wrench R; //wrench p of the bias forces
Wrench R_tilde; //vector of wrench p of the bias forces (new) in matrix form
Twist C; //constraint
Twist A; //constraint
ArticulatedBodyInertia H; //I (expressed in 6*6 matrix)
ArticulatedBodyInertia P; //I (expressed in 6*6 matrix)
ArticulatedBodyInertia P_tilde; //I (expressed in 6*6 matrix)
Wrench PZ; //vector U[i] = I_A[i]*S[i]
Wrench PC; //vector E[i] = I_A[i]*c[i]
double D; //vector D[i] = S[i]^T*U[i]
Matrix6Xd E; //matrix with virtual unit constraint force due to acceleration constraints
Matrix6Xd E_tilde;
Eigen::MatrixXd M; //acceleration energy already generated at link i
Eigen::VectorXd G; //magnitude of the constraint forces already generated at link i
Eigen::VectorXd EZ; //K[i] = Etiltde'*Z
double nullspaceAccComp; //Azamat: constribution of joint space u[i] forces to joint space acceleration
double constAccComp; //Azamat: constribution of joint space constraint forces to joint space acceleration
double biasAccComp; //Azamat: constribution of joint space bias forces to joint space acceleration
double totalBias; //Azamat: R+PC (centrepital+coriolis) in joint subspace
double u; //vector u[i] = torques(i) - S[i]^T*(p_A[i] + I_A[i]*C[i]) in joint subspace. Azamat: In code u[i] = torques(i) - s[i].totalBias
segment_info(unsigned int nc):
D(0),nullspaceAccComp(0),constAccComp(0),biasAccComp(0),totalBias(0),u(0)
{
E.resize(6, nc);
E_tilde.resize(6, nc);
G.resize(nc);
M.resize(nc, nc);
EZ.resize(nc);
E.setZero();
E_tilde.setZero();
M.setZero();
G.setZero();
EZ.setZero();
};
};
std::vector<segment_info> results;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/velocityprofile_spline.hpp | #ifndef VELOCITYPROFILE_SPLINE_H
#define VELOCITYPROFILE_SPLINE_H
#include "velocityprofile.hpp"
namespace KDL
{
/**
* \brief A spline VelocityProfile trajectory interpolation.
* @ingroup Motion
*/
class VelocityProfile_Spline : public VelocityProfile
{
public:
VelocityProfile_Spline();
VelocityProfile_Spline(const VelocityProfile_Spline &p);
virtual ~VelocityProfile_Spline();
virtual void SetProfile(double pos1, double pos2);
/**
* Generate linear interpolation coeffcients.
*
* @param pos1 begin position.
* @param pos2 end position.
* @param duration duration of the profile.
*/
virtual void SetProfileDuration(
double pos1, double pos2, double duration);
/**
* Generate cubic spline interpolation coeffcients.
*
* @param pos1 begin position.
* @param vel1 begin velocity.
* @param pos2 end position.
* @param vel2 end velocity.
* @param duration duration of the profile.
*/
virtual void SetProfileDuration(
double pos1, double vel1, double pos2, double vel2, double duration);
/**
* Generate quintic spline interpolation coeffcients.
*
* @param pos1 begin position.
* @param vel1 begin velocity.
* @param acc1 begin acceleration
* @param pos2 end position.
* @param vel2 end velocity.
* @param acc2 end acceleration.
* @param duration duration of the profile.
*/
virtual void SetProfileDuration(double pos1, double vel1, double acc1, double pos2, double vel2, double acc2, double duration);
virtual double Duration() const;
virtual double Pos(double time) const;
virtual double Vel(double time) const;
virtual double Acc(double time) const;
virtual void Write(std::ostream& os) const;
virtual VelocityProfile* Clone() const;
private:
double coeff_[6];
double duration_;
};
}
#endif // VELOCITYPROFILE_CUBICSPLINE_H
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/trajectory_composite.cpp | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* LRL V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: trajectory_composite.cpp 22 2004-09-21 08:58:54Z eaertbellocal $
* $Name: $
****************************************************************************/
#include "trajectory_composite.hpp"
#include "path_composite.hpp"
namespace KDL {
using namespace std;
Trajectory_Composite::Trajectory_Composite():duration(0.0)
{
}
double Trajectory_Composite::Duration() const{
return duration;
}
Frame Trajectory_Composite::Pos(double time) const {
// not optimal, could be done in log(#elem)
// or one could buffer the last segment and start looking from there.
unsigned int i;
double previoustime;
Trajectory* traj;
if (time < 0) {
return vt[0]->Pos(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Pos(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Pos(traj->Duration());
}
Twist Trajectory_Composite::Vel(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Vel(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Vel(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Vel(traj->Duration());
}
Twist Trajectory_Composite::Acc(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Acc(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Acc(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Acc(traj->Duration());
}
void Trajectory_Composite::Add(Trajectory* elem) {
vt.insert(vt.end(),elem);
duration += elem->Duration();
vd.insert(vd.end(),duration);
}
void Trajectory_Composite::Destroy() {
VectorTraj::iterator it;
for (it=vt.begin();it!=vt.end();it++) {
delete *it;
}
vt.erase(vt.begin(),vt.end());
vd.erase(vd.begin(),vd.end());
}
Trajectory_Composite::~Trajectory_Composite() {
Destroy();
}
void Trajectory_Composite::Write(ostream& os) const {
os << "COMPOSITE[ " << vt.size() << endl;
unsigned int i;
for (i=0;i<vt.size();i++) {
vt[i]->Write(os);
}
os << "]" << endl;
}
Trajectory* Trajectory_Composite::Clone() const{
Trajectory_Composite* comp = new Trajectory_Composite();
for (unsigned int i = 0; i < vt.size(); ++i) {
comp->Add(vt[i]->Clone());
}
return comp;
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chaindynparam.cpp | // Copyright (C) 2009 Dominick Vanthienen <dominick dot vanthienen at mech dot kuleuven dot be>
// Version: 1.0
// Author: Dominick Vanthienen <dominick dot vanthienen at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "chaindynparam.hpp"
#include "frames_io.hpp"
#include <iostream>
namespace KDL {
ChainDynParam::ChainDynParam(const Chain& _chain, Vector _grav):
chain(_chain),
nr(0),
nj(chain.getNrOfJoints()),
ns(chain.getNrOfSegments()),
grav(_grav),
jntarraynull(nj),
chainidsolver_coriolis( chain, Vector::Zero()),
chainidsolver_gravity( chain, grav),
wrenchnull(ns,Wrench::Zero()),
X(ns),
S(ns),
Ic(ns)
{
ag=-Twist(grav,Vector::Zero());
}
//calculate inertia matrix H
int ChainDynParam::JntToMass(const JntArray &q, JntSpaceInertiaMatrix& H)
{
//Check sizes when in debug mode
if(q.rows()!=nj || H.rows()!=nj || H.columns()!=nj )
return -1;
unsigned int k=0;
double q_;
//Sweep from root to leaf
for(unsigned int i=0;i<ns;i++)
{
//Collect RigidBodyInertia
Ic[i]=chain.getSegment(i).getInertia();
if(chain.getSegment(i).getJoint().getType()!=Joint::None)
{
q_=q(k);
k++;
}
else
{
q_=0.0;
}
X[i]=chain.getSegment(i).pose(q_);//Remark this is the inverse of the frame for transformations from the parent to the current coord frame
S[i]=X[i].M.Inverse(chain.getSegment(i).twist(q_,1.0));
}
//Sweep from leaf to root
int j,l;
k=nj-1; //reset k
for(int i=ns-1;i>=0;i--)
{
if(i!=0)
{
//assumption that previous segment is parent
Ic[i-1]=Ic[i-1]+X[i]*Ic[i];
}
F=Ic[i]*S[i];
if(chain.getSegment(i).getJoint().getType()!=Joint::None)
{
H(k,k)=dot(S[i],F);
j=k; //countervariable for the joints
l=i; //countervariable for the segments
while(l!=0) //go from leaf to root starting at i
{
//assumption that previous segment is parent
F=X[l]*F; //calculate the unit force (cfr S) for every segment: F[l-1]=X[l]*F[l]
l--; //go down a segment
if(chain.getSegment(l).getJoint().getType()!=Joint::None) //if the joint connected to segment is not a fixed joint
{
j--;
H(k,j)=dot(F,S[l]); //here you actually match a certain not fixed joint with a segment
H(j,k)=H(k,j);
}
}
k--; //this if-loop should be repeated nj times (k=nj-1 to k=0)
}
}
return 0;
}
//calculate coriolis matrix C
int ChainDynParam::JntToCoriolis(const JntArray &q, const JntArray &q_dot, JntArray &coriolis)
{
//make a null matrix with the size of q_dotdot and a null wrench
SetToZero(jntarraynull);
//the calculation of coriolis matrix C
chainidsolver_coriolis.CartToJnt(q, q_dot, jntarraynull, wrenchnull, coriolis);
return 0;
}
//calculate gravity matrix G
int ChainDynParam::JntToGravity(const JntArray &q,JntArray &gravity)
{
//make a null matrix with the size of q_dotdot and a null wrench
SetToZero(jntarraynull);
//the calculation of coriolis matrix C
chainidsolver_gravity.CartToJnt(q, jntarraynull, jntarraynull, wrenchnull, gravity);
return 0;
}
ChainDynParam::~ChainDynParam()
{
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/path_circle.cpp | /***************************************************************************
tag: Erwin Aertbelien Mon May 10 19:10:36 CEST 2004 path_circle.cxx
path_circle.cxx - description
-------------------
begin : Mon May 10 2004
copyright : (C) 2004 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: path_circle.cpp,v 1.1.1.1.2.5 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
#include "path_circle.hpp"
#include "utilities/error.h"
namespace KDL {
Path_Circle::Path_Circle(const Frame& F_base_start,
const Vector& _V_base_center,
const Vector& V_base_p,
const Rotation& R_base_end,
double alpha,
RotationalInterpolation* _orient,
double _eqradius,
bool _aggregate) :
orient(_orient) ,
eqradius(_eqradius),
aggregate(_aggregate)
{
F_base_center.p = _V_base_center;
orient->SetStartEnd(F_base_start.M,R_base_end);
double oalpha = orient->Angle();
Vector x(F_base_start.p - F_base_center.p);
radius = x.Normalize();
if (radius < epsilon) throw Error_MotionPlanning_Circle_ToSmall();
Vector tmpv(V_base_p-F_base_center.p);
tmpv.Normalize();
Vector z( x * tmpv);
double n = z.Normalize();
if (n < epsilon) throw Error_MotionPlanning_Circle_No_Plane();
F_base_center.M = Rotation(x,z*x,z);
double dist = alpha*radius;
// See what has the slowest eq. motion, and adapt
// the other to this slower motion
// use eqradius to transform between rot and transl.
// the same as for lineair motion
if (oalpha*eqradius > dist) {
// rotational_interpolation is the limitation
pathlength = oalpha*eqradius;
scalerot = 1/eqradius;
scalelin = dist/pathlength;
} else {
// translation is the limitation
pathlength = dist;
scalerot = oalpha/pathlength;
scalelin = 1;
}
}
double Path_Circle::LengthToS(double length) {
return length/scalelin;
}
double Path_Circle::PathLength() {
return pathlength;
}
Frame Path_Circle::Pos(double s) const {
double p = s*scalelin / radius;
return Frame(orient->Pos(s*scalerot),
F_base_center*Vector(radius*cos(p),radius*sin(p),0)
);
}
Twist Path_Circle::Vel(double s,double sd) const {
double p = s*scalelin / radius;
double v = sd*scalelin / radius;
return Twist( F_base_center.M*Vector(-radius*sin(p)*v,radius*cos(p)*v,0),
orient->Vel(s*scalerot,sd*scalerot)
);
}
Twist Path_Circle::Acc(double s,double sd,double sdd) const {
double p = s*scalelin / radius;
double cp = cos(p);
double sp = sin(p);
double v = sd*scalelin / radius;
double a = sdd*scalelin / radius;
return Twist( F_base_center.M*Vector(
-radius*cp*v*v - radius*sp*a,
-radius*sp*v*v + radius*cp*a,
0
),
orient->Acc(s*scalerot,sd*scalerot,sdd*scalerot)
);
}
Path* Path_Circle::Clone() {
return new Path_Circle(
Pos(0),
F_base_center.p,
F_base_center.M.UnitY(),
orient->Pos(pathlength*scalerot),
pathlength*scalelin/radius/deg2rad,
orient->Clone(),
eqradius,
aggregate
);
}
Path_Circle::~Path_Circle() {
if (aggregate)
delete orient;
}
void Path_Circle::Write(std::ostream& os) {
os << "CIRCLE[ ";
os << " " << Pos(0) << std::endl;
os << " " << F_base_center.p << std::endl;
os << " " << F_base_center.M.UnitY() << std::endl;
os << " " << orient->Pos(pathlength*scalerot) << std::endl;
os << " " << pathlength*scalelin/radius/deg2rad << std::endl;
os << " ";orient->Write(os);
os << " " << eqradius;
os << "]"<< std::endl;
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/jntarray.cpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "jntarray.hpp"
namespace KDL
{
using namespace Eigen;
JntArray::JntArray()
{
}
JntArray::JntArray(unsigned int _size):
data(_size)
{
data.setZero();
}
JntArray::JntArray(const JntArray& arg):
data(arg.data)
{
}
JntArray& JntArray::operator = (const JntArray& arg)
{
data=arg.data;
return *this;
}
JntArray::~JntArray()
{
}
void JntArray::resize(unsigned int newSize)
{
data.resize(newSize);
}
double JntArray::operator()(unsigned int i,unsigned int j)const
{
assert(j==0);
return data(i);
}
double& JntArray::operator()(unsigned int i,unsigned int j)
{
assert(j==0);
return data(i);
}
unsigned int JntArray::rows()const
{
return data.rows();
}
unsigned int JntArray::columns()const
{
return data.cols();
}
void Add(const JntArray& src1,const JntArray& src2,JntArray& dest)
{
dest.data=src1.data+src2.data;
}
void Subtract(const JntArray& src1,const JntArray& src2,JntArray& dest)
{
dest.data=src1.data-src2.data;
}
void Multiply(const JntArray& src,const double& factor,JntArray& dest)
{
dest.data=factor*src.data;
}
void Divide(const JntArray& src,const double& factor,JntArray& dest)
{
dest.data=src.data/factor;
}
void MultiplyJacobian(const Jacobian& jac, const JntArray& src, Twist& dest)
{
Eigen::Matrix<double,6,1> t=jac.data.lazyProduct(src.data);
dest=Twist(Vector(t(0),t(1),t(2)),Vector(t(3),t(4),t(5)));
}
void SetToZero(JntArray& array)
{
array.data.setZero();
}
bool Equal(const JntArray& src1, const JntArray& src2,double eps)
{
if(src1.rows()!=src2.rows())
return false;
return src1.data.isApprox(src2.data,eps);
}
bool operator==(const JntArray& src1,const JntArray& src2){return Equal(src1,src2);};
//bool operator!=(const JntArray& src1,const JntArray& src2){return Equal(src1,src2);};
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolverpos_lma.cpp | /**
\file chainiksolverpos_lma.cpp
\brief computing inverse position kinematics using Levenberg-Marquardt.
*/
/**************************************************************************
begin : May 2012
copyright : (C) 2012 Erwin Aertbelien
email : firstname.lastname@mech.kuleuven.ac.be
History (only major changes)( AUTHOR-Description ) :
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#include "chainiksolverpos_lma.hpp"
#include <iostream>
namespace KDL {
template <typename Derived>
inline void Twist_to_Eigen(const KDL::Twist& t,Eigen::MatrixBase<Derived>& e) {
e(0)=t.vel.data[0];
e(1)=t.vel.data[1];
e(2)=t.vel.data[2];
e(3)=t.rot.data[0];
e(4)=t.rot.data[1];
e(5)=t.rot.data[2];
}
ChainIkSolverPos_LMA::ChainIkSolverPos_LMA(
const KDL::Chain& _chain,
const Eigen::Matrix<double,6,1>& _L,
double _eps,
int _maxiter,
double _eps_joints
) :
lastNrOfIter(0),
lastSV(_chain.getNrOfJoints()),
jac(6, _chain.getNrOfJoints()),
grad(_chain.getNrOfJoints()),
display_information(false),
maxiter(_maxiter),
eps(_eps),
eps_joints(_eps_joints),
L(_L.cast<ScalarType>()),
chain(_chain),
T_base_jointroot(_chain.getNrOfJoints()),
T_base_jointtip(_chain.getNrOfJoints()),
q(_chain.getNrOfJoints()),
A(_chain.getNrOfJoints(), _chain.getNrOfJoints()),
tmp(_chain.getNrOfJoints()),
ldlt(_chain.getNrOfJoints()),
svd(6, _chain.getNrOfJoints(),Eigen::ComputeThinU | Eigen::ComputeThinV),
diffq(_chain.getNrOfJoints()),
q_new(_chain.getNrOfJoints()),
original_Aii(_chain.getNrOfJoints())
{}
ChainIkSolverPos_LMA::ChainIkSolverPos_LMA(
const KDL::Chain& _chain,
double _eps,
int _maxiter,
double _eps_joints
) :
lastNrOfIter(0),
lastSV(_chain.getNrOfJoints()>6?6:_chain.getNrOfJoints()),
jac(6, _chain.getNrOfJoints()),
grad(_chain.getNrOfJoints()),
display_information(false),
maxiter(_maxiter),
eps(_eps),
eps_joints(_eps_joints),
chain(_chain),
T_base_jointroot(_chain.getNrOfJoints()),
T_base_jointtip(_chain.getNrOfJoints()),
q(_chain.getNrOfJoints()),
A(_chain.getNrOfJoints(), _chain.getNrOfJoints()),
ldlt(_chain.getNrOfJoints()),
svd(6, _chain.getNrOfJoints(),Eigen::ComputeThinU | Eigen::ComputeThinV),
diffq(_chain.getNrOfJoints()),
q_new(_chain.getNrOfJoints()),
original_Aii(_chain.getNrOfJoints())
{
L(0)=1;
L(1)=1;
L(2)=1;
L(3)=0.01;
L(4)=0.01;
L(5)=0.01;
}
ChainIkSolverPos_LMA::~ChainIkSolverPos_LMA() {}
void ChainIkSolverPos_LMA::compute_fwdpos(const VectorXq& q) {
using namespace KDL;
unsigned int jointndx=0;
T_base_head = Frame::Identity(); // frame w.r.t. base of head
for (unsigned int i=0;i<chain.getNrOfSegments();i++) {
const Segment& segment = chain.getSegment(i);
if (segment.getJoint().getType()!=Joint::None) {
T_base_jointroot[jointndx] = T_base_head;
T_base_head = T_base_head * segment.pose(q(jointndx));
T_base_jointtip[jointndx] = T_base_head;
jointndx++;
} else {
T_base_head = T_base_head * segment.pose(0.0);
}
}
}
void ChainIkSolverPos_LMA::compute_jacobian(const VectorXq& q) {
using namespace KDL;
unsigned int jointndx=0;
for (unsigned int i=0;i<chain.getNrOfSegments();i++) {
const Segment& segment = chain.getSegment(i);
if (segment.getJoint().getType()!=Joint::None) {
// compute twist of the end effector motion caused by joint [jointndx]; expressed in base frame, with vel. ref. point equal to the end effector
KDL::Twist t = ( T_base_jointroot[jointndx].M * segment.twist(q(jointndx),1.0) ).RefPoint( T_base_head.p - T_base_jointtip[jointndx].p);
jac(0,jointndx)=t[0];
jac(1,jointndx)=t[1];
jac(2,jointndx)=t[2];
jac(3,jointndx)=t[3];
jac(4,jointndx)=t[4];
jac(5,jointndx)=t[5];
jointndx++;
}
}
}
void ChainIkSolverPos_LMA::display_jac(const KDL::JntArray& jval) {
VectorXq q;
q = jval.data.cast<ScalarType>();
compute_fwdpos(q);
compute_jacobian(q);
svd.compute(jac);
std::cout << "Singular values : " << svd.singularValues().transpose()<<"\n";
}
int ChainIkSolverPos_LMA::CartToJnt(const KDL::JntArray& q_init, const KDL::Frame& T_base_goal, KDL::JntArray& q_out) {
using namespace KDL;
double v = 2;
double tau = 10;
double rho;
double lambda;
Twist t;
double delta_pos_norm;
Eigen::Matrix<ScalarType,6,1> delta_pos;
Eigen::Matrix<ScalarType,6,1> delta_pos_new;
q=q_init.data.cast<ScalarType>();
compute_fwdpos(q);
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos );
delta_pos=L.asDiagonal()*delta_pos;
delta_pos_norm = delta_pos.norm();
if (delta_pos_norm<eps) {
lastNrOfIter =0 ;
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos );
lastDifference = delta_pos.norm();
lastTransDiff = delta_pos.topRows(3).norm();
lastRotDiff = delta_pos.bottomRows(3).norm();
svd.compute(jac);
original_Aii = svd.singularValues();
lastSV = svd.singularValues();
q_out.data = q.cast<double>();
return 0;
}
compute_jacobian(q);
jac = L.asDiagonal()*jac;
lambda = tau;
double dnorm = 1;
for (unsigned int i=0;i<maxiter;++i) {
svd.compute(jac);
original_Aii = svd.singularValues();
for (unsigned int j=0;j<original_Aii.rows();++j) {
original_Aii(j) = original_Aii(j)/( original_Aii(j)*original_Aii(j)+lambda);
}
tmp = svd.matrixU().transpose()*delta_pos;
tmp = original_Aii.cwiseProduct(tmp);
diffq = svd.matrixV()*tmp;
grad = jac.transpose()*delta_pos;
if (display_information) {
std::cout << "------- iteration " << i << " ----------------\n"
<< " q = " << q.transpose() << "\n"
<< " weighted jac = \n" << jac << "\n"
<< " lambda = " << lambda << "\n"
<< " eigenvalues = " << svd.singularValues().transpose() << "\n"
<< " difference = " << delta_pos.transpose() << "\n"
<< " difference norm= " << delta_pos_norm << "\n"
<< " proj. on grad. = " << grad << "\n";
std::cout << std::endl;
}
dnorm = diffq.lpNorm<Eigen::Infinity>();
if (dnorm < eps_joints) {
lastDifference = delta_pos_norm;
lastNrOfIter = i;
lastSV = svd.singularValues();
q_out.data = q.cast<double>();
compute_fwdpos(q);
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos );
lastTransDiff = delta_pos.topRows(3).norm();
lastRotDiff = delta_pos.bottomRows(3).norm();
return -2;
}
if (grad.transpose()*grad < eps_joints*eps_joints ) {
compute_fwdpos(q);
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos );
lastDifference = delta_pos_norm;
lastTransDiff = delta_pos.topRows(3).norm();
lastRotDiff = delta_pos.bottomRows(3).norm();
lastSV = svd.singularValues();
lastNrOfIter = i;
q_out.data = q.cast<double>();
return -1;
}
q_new = q+diffq;
compute_fwdpos(q_new);
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos_new );
delta_pos_new = L.asDiagonal()*delta_pos_new;
double delta_pos_new_norm = delta_pos_new.norm();
rho = delta_pos_norm*delta_pos_norm - delta_pos_new_norm*delta_pos_new_norm;
rho /= diffq.transpose()*(lambda*diffq + grad);
if (rho > 0) {
q = q_new;
delta_pos = delta_pos_new;
delta_pos_norm = delta_pos_new_norm;
if (delta_pos_norm<eps) {
Twist_to_Eigen( diff( T_base_head, T_base_goal), delta_pos );
lastDifference = delta_pos_norm;
lastTransDiff = delta_pos.topRows(3).norm();
lastRotDiff = delta_pos.bottomRows(3).norm();
lastSV = svd.singularValues();
lastNrOfIter = i;
q_out.data = q.cast<double>();
return 0;
}
compute_jacobian(q_new);
jac = L.asDiagonal()*jac;
double tmp=2*rho-1;
lambda = lambda*max(1/3.0, 1-tmp*tmp*tmp);
v = 2;
} else {
lambda = lambda*v;
v = 2*v;
}
}
lastDifference = delta_pos_norm;
lastTransDiff = delta_pos.topRows(3).norm();
lastRotDiff = delta_pos.bottomRows(3).norm();
lastSV = svd.singularValues();
lastNrOfIter = maxiter;
q_out.data = q.cast<double>();
return -3;
}
};//namespace KDL
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/frames_io.hpp | /***************************************************************************
frames_io.h - description
-------------------------
begin : June 2006
copyright : (C) 2006 Erwin Aertbelien
email : firstname.lastname@mech.kuleuven.ac.be
History (only major changes)( AUTHOR-Description ) :
Ruben Smits - Added output for jacobian and jntarray 06/2007
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/**
//
// \file
// Defines routines for I/O of Frame and related objects.
// \verbatim
// Spaces, tabs and newlines do not have any importance.
// Comments are allowed C-style,C++-style, make/perl/csh -style
// Description of the I/O :
// Vector : OUTPUT : e.g. [10,20,30]
// INPUT :
// 1) [10,20,30]
// 2) Zero
// Twist : e.g. [1,2,3,4,5,6]
// where [1,2,3] is velocity vector
// where [4,5,6] is rotational velocity vector
// Wrench : e.g. [1,2,3,4,5,6]
// where [1,2,3] represents a force vector
// where [4,5,6] represents a torque vector
// Rotation : output :
// [1,2,3;
// 4,5,6;
// 7,8,9] cfr definition of Rotation object.
// input :
// 1) like the output
// 2) EulerZYX,EulerZYZ,RPY word followed by a vector, e.g. :
// Eulerzyx[10,20,30]
// (ANGLES are always expressed in DEGREES for I/O)
// (ANGELS are always expressed in RADIANS for internal representation)
// 3) Rot [1,2,3] [20] Rotates around axis [1,2,3] with an angle
// of 20 degrees.
// 4) Identity returns identity rotation matrix.
// Frames : output : [ Rotationmatrix positionvector ]
// e.g. [ [1,0,0;0,1,0;0,0,1] [1,2,3] ]
// Input :
// 1) [ Rotationmatrix positionvector ]
// 2) DH [ 10,10,50,30] Denavit-Hartenberg representation
// ( is in fact not the representation of a Frame, but more
// limited, cfr. documentation of Frame object.)
// \endverbatim
//
// \warning
// You can use iostream.h or iostream header files for file I/O,
// if one declares the define WANT_STD_IOSTREAM then the standard C++
// iostreams headers are included instead of the compiler-dependent version
//
*
****************************************************************************/
#ifndef FRAMES_IO_H
#define FRAMES_IO_H
#include "utilities/utility_io.h"
#include "frames.hpp"
#include "jntarray.hpp"
#include "jacobian.hpp"
namespace KDL {
//! width to be used when printing variables out with frames_io.h
//! global variable, can be changed.
// I/O to C++ stream.
std::ostream& operator << (std::ostream& os,const Vector& v);
std::ostream& operator << (std::ostream& os,const Rotation& R);
std::ostream& operator << (std::ostream& os,const Frame& T);
std::ostream& operator << (std::ostream& os,const Twist& T);
std::ostream& operator << (std::ostream& os,const Wrench& T);
std::ostream& operator << (std::ostream& os,const Vector2& v);
std::ostream& operator << (std::ostream& os,const Rotation2& R);
std::ostream& operator << (std::ostream& os,const Frame2& T);
std::istream& operator >> (std::istream& is,Vector& v);
std::istream& operator >> (std::istream& is,Rotation& R);
std::istream& operator >> (std::istream& is,Frame& T);
std::istream& operator >> (std::istream& os,Twist& T);
std::istream& operator >> (std::istream& os,Wrench& T);
std::istream& operator >> (std::istream& is,Vector2& v);
std::istream& operator >> (std::istream& is,Rotation2& R);
std::istream& operator >> (std::istream& is,Frame2& T);
} // namespace Frame
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/rotationalinertia.hpp | // Copyright (C) 2009 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_ROTATIONALINERTIA_HPP
#define KDL_ROTATIONALINERTIA_HPP
#include "frames.hpp"
//------- class for only the Rotational Inertia --------
namespace KDL
{
//Forward declaration
class RigidBodyInertia;
class RotationalInertia{
public:
explicit RotationalInertia(double Ixx=0,double Iyy=0,double Izz=0,double Ixy=0,double Ixz=0,double Iyz=0);
static inline RotationalInertia Zero(){
return RotationalInertia(0,0,0,0,0,0);
};
friend RotationalInertia operator*(double a, const RotationalInertia& I);
friend RotationalInertia operator+(const RotationalInertia& Ia, const RotationalInertia& Ib);
/**
* This function calculates the angular momentum resulting from a rotational velocity omega
*/
KDL::Vector operator*(const KDL::Vector& omega) const;
~RotationalInertia();
friend class RigidBodyInertia;
///Scalar product
friend RigidBodyInertia operator*(double a,const RigidBodyInertia& I);
///addition
friend RigidBodyInertia operator+(const RigidBodyInertia& Ia,const RigidBodyInertia& Ib);
///calculate spatial momentum
friend Wrench operator*(const RigidBodyInertia& I,const Twist& t);
///coordinate system transform Ia = T_a_b*Ib with T_a_b the frame from a to b
friend RigidBodyInertia operator*(const Frame& T,const RigidBodyInertia& I);
///base frame orientation change Ia = R_a_b*Ib with R_a_b the rotation for frame from a to b
friend RigidBodyInertia operator*(const Rotation& R,const RigidBodyInertia& I);
double data[9];
};
RotationalInertia operator*(double a, const RotationalInertia& I);
RotationalInertia operator+(const RotationalInertia& Ia, const RotationalInertia& Ib);
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/trajectory_stationary.hpp | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* LRL V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: trajectory_stationary.h 22 2004-09-21 08:58:54Z eaertbellocal $
* $Name: $
****************************************************************************/
#ifndef TRAJECTORY_STATIONARY_H
#define TRAJECTORY_STATIONARY_H
#include "trajectory.hpp"
namespace KDL {
/**
* Implements a "trajectory" of a stationary position
* for an amount of time.
* @ingroup Motion
*/
class Trajectory_Stationary : public Trajectory
{
double duration;
Frame pos;
public:
Trajectory_Stationary(double _duration,const Frame& _pos):
duration(_duration),pos(_pos) {}
virtual double Duration() const {
return duration;
}
virtual Frame Pos(double time) const {
return pos;
}
virtual Twist Vel(double time) const {
return Twist::Zero();
}
virtual Twist Acc(double time) const {
return Twist::Zero();
}
virtual void Write(std::ostream& os) const;
virtual Trajectory* Clone() const {
return new Trajectory_Stationary(duration,pos);
}
virtual ~Trajectory_Stationary() {}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/path_roundedcomposite.hpp | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:38 CET 2005 path_roundedcomposite.h
path_roundedcomposite.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: path_roundedcomposite.h,v 1.1.1.1.2.3 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_MOTION_ROUNDEDCOMPOSITE_H
#define KDL_MOTION_ROUNDEDCOMPOSITE_H
#include "path.hpp"
#include "path_composite.hpp"
#include "rotational_interpolation.hpp"
namespace KDL {
/**
* The specification of a path, composed of way-points with rounded corners.
*
* @ingroup Motion
*/
class Path_RoundedComposite : public Path
{
/** a Path_Composite is aggregated to hold the rounded trajectory
* with circles and lines
*/
Path_Composite* comp;
double radius;
double eqradius;
RotationalInterpolation* orient;
// cached from underlying path objects for generating the rounding :
Frame F_base_start;
Frame F_base_via;
//Frame F_base_end;
int nrofpoints;
bool aggregate;
Path_RoundedComposite(Path_Composite* comp,double radius,double eqradius,RotationalInterpolation* orient, bool aggregate, int nrofpoints);
public:
/**
* @param radius : radius of the rounding circles
* @param eqradius : equivalent radius to compare rotations/velocities
* @param orient : method of rotational_interpolation interpolation
* @param aggregate : if true, this object will own the _orient pointer, i.e. it will delete the _orient pointer
* when the destructor of this object is called.
*/
Path_RoundedComposite(double radius,double eqradius,RotationalInterpolation* orient, bool aggregate=true);
/**
* Adds a point to this rounded composite, between to adjecent points
* a Path_Line will be created, between two lines there will be
* rounding with the given radius with a Path_Circle
*
* The Error_MotionPlanning_Not_Feasible has a type (obtained by GetType) of:
* - 3101 if the eq. radius <= 0
* - 3102 if the first segment in a rounding has zero length.
* - 3103 if the second segment in a rounding has zero length.
* - 3104 if the angle between the first and the second segment is close to M_PI.
* (meaning that the segments are on top of each other)
* - 3105 if the distance needed for the rounding is larger then the first segment.
* - 3106 if the distance needed for the rounding is larger then the second segment.
*
* @param F_base_point the pose of a new via point.
* @warning Can throw Error_MotionPlanning_Not_Feasible object
* @TODO handle the case of error type 3105 and 3106 by skipping segments, such that the class could be applied
* with points that are very close to each other.
*/
void Add(const Frame& F_base_point);
/**
* to be called after the last line is added to finish up
* the work
*/
void Finish();
virtual double LengthToS(double length);
/**
* Returns the total path length of the trajectory
* (has dimension LENGTH)
* This is not always a physical length , ie when dealing with rotations
* that are dominant.
*/
virtual double PathLength();
/**
* Returns the Frame at the current path length s
*/
virtual Frame Pos(double s) const;
/**
* Returns the velocity twist at path length s theta and with
* derivative of s == sd
*/
virtual Twist Vel(double s,double sd) const;
/**
* Returns the acceleration twist at path length s and with
* derivative of s == sd, and 2nd derivative of s == sdd
*/
virtual Twist Acc(double s,double sd,double sdd) const;
/**
* virtual constructor, constructing by copying.
* In this case it returns the Clone() of the aggregated Path_Composite
* because this is all one ever will need.
*/
virtual Path* Clone();
/**
* Writes one of the derived objects to the stream
*/
virtual void Write(std::ostream& os);
/**
* returns the number of underlying segments.
*/
virtual int GetNrOfSegments();
/**
* returns a pointer to the underlying Path of the given segment number i.
* \param i segment number
* \return pointer to the underlying Path
* \warning The pointer is still owned by this class and is lifetime depends on the lifetime
* of this class.
*/
virtual Path* GetSegment(int i);
/**
* gets the length to the end of the given segment.
* \param i segment number
* \return length to the end of the segment, i.e. the value for s corresponding to the end of
* this segment.
*/
virtual double GetLengthToEndOfSegment(int i);
/**
* \param s [INPUT] path length variable for the composite.
* \param segment_number [OUTPUT] segments that corresponds to the path length variable s.
* \param inner_s [OUTPUT] path length to use within the segment.
*/
virtual void GetCurrentSegmentLocation(double s, int &segment_number, double& inner_s);
/**
* gets an identifier indicating the type of this Path object
*/
virtual IdentifierType getIdentifier() const {
return ID_ROUNDED_COMPOSITE;
}
virtual ~Path_RoundedComposite();
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/velocityprofile.hpp | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:38 CET 2005 velocityprofile.h
velocityprofile.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: velocityprofile.h,v 1.1.1.1.2.5 2003/07/24 13:26:15 psoetens Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_VELOCITYPROFILE_H
#define KDL_VELOCITYPROFILE_H
#include "utilities/utility.h"
#include "utilities/utility_io.h"
namespace KDL {
/**
* A VelocityProfile stores the velocity profile that
* is used within a trajectory. A velocity profile is the function that
* expresses position, velocity and acceleration of a point on a curve
* in function of time. It defines the how a point s moves on a path S.
* @ingroup Motion
*/
class VelocityProfile
{
public:
// trajectory parameters are set in constructor of
// derived class
virtual void SetProfile(double pos1,double pos2) = 0;
// sets a trajectory from pos1 to pos2 as fast as possible
virtual void SetProfileDuration(
double pos1,double pos2,double duration) = 0;
// Sets a trajectory from pos1 to pos2 in <duration> seconds.
// @post new.Duration() will not be shorter than the one obtained
// from SetProfile(pos1,pos2).
virtual double Duration() const = 0;
// returns the duration of the motion in [sec]
virtual double Pos(double time) const = 0;
// returns the position at <time> in the units of the input
// of the constructor of the derived class.
virtual double Vel(double time) const = 0;
// returns the velocity at <time> in the units of the input
// of the constructor of the derived class.
virtual double Acc(double time) const = 0;
// returns the acceleration at <time> in the units of the input
// of the constructor of the derived class.
virtual void Write(std::ostream& os) const = 0;
// Writes object to a stream.
static VelocityProfile* Read(std::istream& is);
// reads a VelocityProfile object from the stream and returns it.
virtual VelocityProfile* Clone() const = 0;
// returns copy of current VelocityProfile object. (virtual constructor)
virtual ~VelocityProfile() {}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/jntarrayvel.hpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_JNTARRAYVEL_HPP
#define KDL_JNTARRAYVEL_HPP
#include "utilities/utility.h"
#include "jntarray.hpp"
#include "framevel.hpp"
namespace KDL
{
// Equal is friend function, but default arguments for friends are forbidden (§8.3.6.4)
class JntArrayVel;
bool Equal(const JntArrayVel& src1,const JntArrayVel& src2,double eps=epsilon);
void Add(const JntArrayVel& src1,const JntArrayVel& src2,JntArrayVel& dest);
void Add(const JntArrayVel& src1,const JntArray& src2,JntArrayVel& dest);
void Subtract(const JntArrayVel& src1,const JntArrayVel& src2,JntArrayVel& dest);
void Subtract(const JntArrayVel& src1,const JntArray& src2,JntArrayVel& dest);
void Multiply(const JntArrayVel& src,const double& factor,JntArrayVel& dest);
void Multiply(const JntArrayVel& src,const doubleVel& factor,JntArrayVel& dest);
void Divide(const JntArrayVel& src,const double& factor,JntArrayVel& dest);
void Divide(const JntArrayVel& src,const doubleVel& factor,JntArrayVel& dest);
void SetToZero(JntArrayVel& array);
class JntArrayVel
{
public:
JntArray q;
JntArray qdot;
public:
JntArrayVel(){};
explicit JntArrayVel(unsigned int size);
JntArrayVel(const JntArray& q,const JntArray& qdot);
explicit JntArrayVel(const JntArray& q);
void resize(unsigned int newSize);
JntArray value()const;
JntArray deriv()const;
friend void Add(const JntArrayVel& src1,const JntArrayVel& src2,JntArrayVel& dest);
friend void Add(const JntArrayVel& src1,const JntArray& src2,JntArrayVel& dest);
friend void Subtract(const JntArrayVel& src1,const JntArrayVel& src2,JntArrayVel& dest);
friend void Subtract(const JntArrayVel& src1,const JntArray& src2,JntArrayVel& dest);
friend void Multiply(const JntArrayVel& src,const double& factor,JntArrayVel& dest);
friend void Multiply(const JntArrayVel& src,const doubleVel& factor,JntArrayVel& dest);
friend void Divide(const JntArrayVel& src,const double& factor,JntArrayVel& dest);
friend void Divide(const JntArrayVel& src,const doubleVel& factor,JntArrayVel& dest);
friend void SetToZero(JntArrayVel& array);
friend bool Equal(const JntArrayVel& src1,const JntArrayVel& src2,double eps);
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP
#define KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP
#include "chainiksolver.hpp"
#include "chainjnttojacsolver.hpp"
#include <Eigen/Core>
using namespace Eigen;
namespace KDL
{
/**
* Implementation of a inverse velocity kinematics algorithm based
* on the generalize pseudo inverse to calculate the velocity
* transformation from Cartesian to joint space of a general
* KDL::Chain. It uses a svd-calculation based on householders
* rotations.
*
* @ingroup KinematicFamily
*/
class ChainIkSolverVel_pinv_givens : public ChainIkSolverVel
{
public:
/**
* Constructor of the solver
*
* @param chain the chain to calculate the inverse velocity
* kinematics for
* @param eps if a singular value is below this value, its
* inverse is set to zero, default: 0.00001
* @param maxiter maximum iterations for the svd calculation,
* default: 150
*
*/
explicit ChainIkSolverVel_pinv_givens(const Chain& chain);
~ChainIkSolverVel_pinv_givens();
virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);
/**
* not (yet) implemented.
*
*/
virtual int CartToJnt(const JntArray& q_init, const FrameVel& v_in, JntArrayVel& q_out){return -1;};
private:
const Chain chain;
ChainJntToJacSolver jnt2jac;
Jacobian jac;
bool transpose,toggle;
unsigned int m,n;
MatrixXd jac_eigen,U,V,B;
VectorXd S,tempi,tempj,UY,SUY,qdot_eigen,v_in_eigen;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainfksolverpos_recursive.cpp | // Copyright (C) 2007 Francois Cauwe <francois at cauwe dot org>
// Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "chainfksolverpos_recursive.hpp"
#include <iostream>
namespace KDL {
ChainFkSolverPos_recursive::ChainFkSolverPos_recursive(const Chain& _chain):
chain(_chain)
{
}
int ChainFkSolverPos_recursive::JntToCart(const JntArray& q_in, Frame& p_out, int seg_nr) {
unsigned int segmentNr;
if(seg_nr<0)
segmentNr=chain.getNrOfSegments();
else
segmentNr = seg_nr;
p_out = Frame::Identity();
if(q_in.rows()!=chain.getNrOfJoints())
return -1;
else if(segmentNr>chain.getNrOfSegments())
return -1;
else{
int j=0;
for(unsigned int i=0;i<segmentNr;i++){
if(chain.getSegment(i).getJoint().getType()!=Joint::None){
p_out = p_out*chain.getSegment(i).pose(q_in(j));
j++;
}else{
p_out = p_out*chain.getSegment(i).pose(0.0);
}
}
return 0;
}
}
ChainFkSolverPos_recursive::~ChainFkSolverPos_recursive()
{
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/framevel.hpp | /*****************************************************************************
* \file
* This file contains the definition of classes for a
* Rall Algebra of (subset of) the classes defined in frames,
* i.e. classes that contain a pair (value,derivative) and define operations on that pair
* this classes are usefull for automatic differentiation ( <-> symbolic diff , <-> numeric diff)
* Defines VectorVel, RotationVel, FrameVel. Look at Frames.h for details on how to work
* with Frame objects.
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: rframes.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef KDL_FRAMEVEL_H
#define KDL_FRAMEVEL_H
#include "utilities/utility.h"
#include "utilities/rall1d.h"
#include "utilities/traits.h"
#include "frames.hpp"
namespace KDL {
typedef Rall1d<double> doubleVel;
IMETHOD doubleVel diff(const doubleVel& a,const doubleVel& b,double dt=1.0) {
return doubleVel((b.t-a.t)/dt,(b.grad-a.grad)/dt);
}
IMETHOD doubleVel addDelta(const doubleVel& a,const doubleVel&da,double dt=1.0) {
return doubleVel(a.t+da.t*dt,a.grad+da.grad*dt);
}
IMETHOD void random(doubleVel& F) {
random(F.t);
random(F.grad);
}
IMETHOD void posrandom(doubleVel& F) {
posrandom(F.t);
posrandom(F.grad);
}
}
template <>
struct Traits<KDL::doubleVel> {
typedef double valueType;
typedef KDL::doubleVel derivType;
};
namespace KDL {
class TwistVel;
class VectorVel;
class FrameVel;
class RotationVel;
// Equal is friend function, but default arguments for friends are forbidden (§8.3.6.4)
IMETHOD bool Equal(const VectorVel& r1,const VectorVel& r2,double eps=epsilon);
IMETHOD bool Equal(const Vector& r1,const VectorVel& r2,double eps=epsilon);
IMETHOD bool Equal(const VectorVel& r1,const Vector& r2,double eps=epsilon);
IMETHOD bool Equal(const RotationVel& r1,const RotationVel& r2,double eps=epsilon);
IMETHOD bool Equal(const Rotation& r1,const RotationVel& r2,double eps=epsilon);
IMETHOD bool Equal(const RotationVel& r1,const Rotation& r2,double eps=epsilon);
IMETHOD bool Equal(const FrameVel& r1,const FrameVel& r2,double eps=epsilon);
IMETHOD bool Equal(const Frame& r1,const FrameVel& r2,double eps=epsilon);
IMETHOD bool Equal(const FrameVel& r1,const Frame& r2,double eps=epsilon);
IMETHOD bool Equal(const TwistVel& a,const TwistVel& b,double eps=epsilon);
IMETHOD bool Equal(const Twist& a,const TwistVel& b,double eps=epsilon);
IMETHOD bool Equal(const TwistVel& a,const Twist& b,double eps=epsilon);
class VectorVel
// = TITLE
// An VectorVel is a Vector and its first derivative
// = CLASS TYPE
// Concrete
{
public:
Vector p; // position vector
Vector v; // velocity vector
public:
VectorVel():p(),v(){}
VectorVel(const Vector& _p,const Vector& _v):p(_p),v(_v) {}
explicit VectorVel(const Vector& _p):p(_p),v(Vector::Zero()) {}
Vector value() const { return p;}
Vector deriv() const { return v;}
IMETHOD VectorVel& operator = (const VectorVel& arg);
IMETHOD VectorVel& operator = (const Vector& arg);
IMETHOD VectorVel& operator += (const VectorVel& arg);
IMETHOD VectorVel& operator -= (const VectorVel& arg);
IMETHOD static VectorVel Zero();
IMETHOD void ReverseSign();
IMETHOD doubleVel Norm() const;
IMETHOD friend VectorVel operator + (const VectorVel& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator - (const VectorVel& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator + (const Vector& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator - (const Vector& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator + (const VectorVel& r1,const Vector& r2);
IMETHOD friend VectorVel operator - (const VectorVel& r1,const Vector& r2);
IMETHOD friend VectorVel operator * (const VectorVel& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator * (const VectorVel& r1,const Vector& r2);
IMETHOD friend VectorVel operator * (const Vector& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator * (const VectorVel& r1,double r2);
IMETHOD friend VectorVel operator * (double r1,const VectorVel& r2);
IMETHOD friend VectorVel operator * (const doubleVel& r1,const VectorVel& r2);
IMETHOD friend VectorVel operator * (const VectorVel& r2,const doubleVel& r1);
IMETHOD friend VectorVel operator*(const Rotation& R,const VectorVel& x);
IMETHOD friend VectorVel operator / (const VectorVel& r1,double r2);
IMETHOD friend VectorVel operator / (const VectorVel& r2,const doubleVel& r1);
IMETHOD friend void SetToZero(VectorVel& v);
IMETHOD friend bool Equal(const VectorVel& r1,const VectorVel& r2,double eps);
IMETHOD friend bool Equal(const Vector& r1,const VectorVel& r2,double eps);
IMETHOD friend bool Equal(const VectorVel& r1,const Vector& r2,double eps);
IMETHOD friend VectorVel operator - (const VectorVel& r);
IMETHOD friend doubleVel dot(const VectorVel& lhs,const VectorVel& rhs);
IMETHOD friend doubleVel dot(const VectorVel& lhs,const Vector& rhs);
IMETHOD friend doubleVel dot(const Vector& lhs,const VectorVel& rhs);
};
class RotationVel
// = TITLE
// An RotationVel is a Rotation and its first derivative, a rotation vector
// = CLASS TYPE
// Concrete
{
public:
Rotation R; // Rotation matrix
Vector w; // rotation vector
public:
RotationVel():R(),w() {}
explicit RotationVel(const Rotation& _R):R(_R),w(Vector::Zero()){}
RotationVel(const Rotation& _R,const Vector& _w):R(_R),w(_w){}
Rotation value() const { return R;}
Vector deriv() const { return w;}
IMETHOD RotationVel& operator = (const RotationVel& arg);
IMETHOD RotationVel& operator = (const Rotation& arg);
IMETHOD VectorVel UnitX() const;
IMETHOD VectorVel UnitY() const;
IMETHOD VectorVel UnitZ() const;
IMETHOD static RotationVel Identity();
IMETHOD RotationVel Inverse() const;
IMETHOD VectorVel Inverse(const VectorVel& arg) const;
IMETHOD VectorVel Inverse(const Vector& arg) const;
IMETHOD VectorVel operator*(const VectorVel& arg) const;
IMETHOD VectorVel operator*(const Vector& arg) const;
IMETHOD void DoRotX(const doubleVel& angle);
IMETHOD void DoRotY(const doubleVel& angle);
IMETHOD void DoRotZ(const doubleVel& angle);
IMETHOD static RotationVel RotX(const doubleVel& angle);
IMETHOD static RotationVel RotY(const doubleVel& angle);
IMETHOD static RotationVel RotZ(const doubleVel& angle);
IMETHOD static RotationVel Rot(const Vector& rotvec,const doubleVel& angle);
// rotvec has arbitrary norm
// rotation around a constant vector !
IMETHOD static RotationVel Rot2(const Vector& rotvec,const doubleVel& angle);
// rotvec is normalized.
// rotation around a constant vector !
IMETHOD friend RotationVel operator* (const RotationVel& r1,const RotationVel& r2);
IMETHOD friend RotationVel operator* (const Rotation& r1,const RotationVel& r2);
IMETHOD friend RotationVel operator* (const RotationVel& r1,const Rotation& r2);
IMETHOD friend bool Equal(const RotationVel& r1,const RotationVel& r2,double eps);
IMETHOD friend bool Equal(const Rotation& r1,const RotationVel& r2,double eps);
IMETHOD friend bool Equal(const RotationVel& r1,const Rotation& r2,double eps);
IMETHOD TwistVel Inverse(const TwistVel& arg) const;
IMETHOD TwistVel Inverse(const Twist& arg) const;
IMETHOD TwistVel operator * (const TwistVel& arg) const;
IMETHOD TwistVel operator * (const Twist& arg) const;
};
class FrameVel
// = TITLE
// An FrameVel is a Frame and its first derivative, a Twist vector
// = CLASS TYPE
// Concrete
// = CAVEATS
//
{
public:
RotationVel M;
VectorVel p;
public:
FrameVel(){}
explicit FrameVel(const Frame& _T):
M(_T.M),p(_T.p) {}
FrameVel(const Frame& _T,const Twist& _t):
M(_T.M,_t.rot),p(_T.p,_t.vel) {}
FrameVel(const RotationVel& _M,const VectorVel& _p):
M(_M),p(_p) {}
Frame value() const { return Frame(M.value(),p.value());}
Twist deriv() const { return Twist(p.deriv(),M.deriv());}
IMETHOD FrameVel& operator = (const Frame& arg);
IMETHOD FrameVel& operator = (const FrameVel& arg);
IMETHOD static FrameVel Identity();
IMETHOD FrameVel Inverse() const;
IMETHOD VectorVel Inverse(const VectorVel& arg) const;
IMETHOD VectorVel operator*(const VectorVel& arg) const;
IMETHOD VectorVel operator*(const Vector& arg) const;
IMETHOD VectorVel Inverse(const Vector& arg) const;
IMETHOD Frame GetFrame() const;
IMETHOD Twist GetTwist() const;
IMETHOD friend FrameVel operator * (const FrameVel& f1,const FrameVel& f2);
IMETHOD friend FrameVel operator * (const Frame& f1,const FrameVel& f2);
IMETHOD friend FrameVel operator * (const FrameVel& f1,const Frame& f2);
IMETHOD friend bool Equal(const FrameVel& r1,const FrameVel& r2,double eps);
IMETHOD friend bool Equal(const Frame& r1,const FrameVel& r2,double eps);
IMETHOD friend bool Equal(const FrameVel& r1,const Frame& r2,double eps);
IMETHOD TwistVel Inverse(const TwistVel& arg) const;
IMETHOD TwistVel Inverse(const Twist& arg) const;
IMETHOD TwistVel operator * (const TwistVel& arg) const;
IMETHOD TwistVel operator * (const Twist& arg) const;
};
//very similar to Wrench class.
class TwistVel
// = TITLE
// This class represents a TwistVel. This is a velocity and rotational velocity together
{
public:
VectorVel vel;
VectorVel rot;
public:
// = Constructors
TwistVel():vel(),rot() {};
TwistVel(const VectorVel& _vel,const VectorVel& _rot):vel(_vel),rot(_rot) {};
TwistVel(const Twist& p,const Twist& v):vel(p.vel, v.vel), rot( p.rot, v.rot) {};
TwistVel(const Twist& p):vel(p.vel), rot( p.rot) {};
Twist value() const {
return Twist(vel.value(),rot.value());
}
Twist deriv() const {
return Twist(vel.deriv(),rot.deriv());
}
// = Operators
IMETHOD TwistVel& operator-=(const TwistVel& arg);
IMETHOD TwistVel& operator+=(const TwistVel& arg);
// = External operators
IMETHOD friend TwistVel operator*(const TwistVel& lhs,double rhs);
IMETHOD friend TwistVel operator*(double lhs,const TwistVel& rhs);
IMETHOD friend TwistVel operator/(const TwistVel& lhs,double rhs);
IMETHOD friend TwistVel operator*(const TwistVel& lhs,const doubleVel& rhs);
IMETHOD friend TwistVel operator*(const doubleVel& lhs,const TwistVel& rhs);
IMETHOD friend TwistVel operator/(const TwistVel& lhs,const doubleVel& rhs);
IMETHOD friend TwistVel operator+(const TwistVel& lhs,const TwistVel& rhs);
IMETHOD friend TwistVel operator-(const TwistVel& lhs,const TwistVel& rhs);
IMETHOD friend TwistVel operator-(const TwistVel& arg);
IMETHOD friend void SetToZero(TwistVel& v);
// = Zero
static IMETHOD TwistVel Zero();
// = Reverse Sign
IMETHOD void ReverseSign();
// = Change Reference point
IMETHOD TwistVel RefPoint(const VectorVel& v_base_AB);
// Changes the reference point of the TwistVel.
// The VectorVel v_base_AB is expressed in the same base as the TwistVel
// The VectorVel v_base_AB is a VectorVel from the old point to
// the new point.
// Complexity : 6M+6A
// = Equality operators
// do not use operator == because the definition of Equal(.,.) is slightly
// different. It compares whether the 2 arguments are equal in an eps-interval
IMETHOD friend bool Equal(const TwistVel& a,const TwistVel& b,double eps);
IMETHOD friend bool Equal(const Twist& a,const TwistVel& b,double eps);
IMETHOD friend bool Equal(const TwistVel& a,const Twist& b,double eps);
// = Conversion to other entities
IMETHOD Twist GetTwist() const;
IMETHOD Twist GetTwistDot() const;
// = Friends
friend class RotationVel;
friend class FrameVel;
};
IMETHOD VectorVel diff(const VectorVel& a,const VectorVel& b,double dt=1.0) {
return VectorVel(diff(a.p,b.p,dt),diff(a.v,b.v,dt));
}
IMETHOD VectorVel addDelta(const VectorVel& a,const VectorVel&da,double dt=1.0) {
return VectorVel(addDelta(a.p,da.p,dt),addDelta(a.v,da.v,dt));
}
IMETHOD VectorVel diff(const RotationVel& a,const RotationVel& b,double dt = 1.0) {
return VectorVel(diff(a.R,b.R,dt),diff(a.w,b.w,dt));
}
IMETHOD RotationVel addDelta(const RotationVel& a,const VectorVel&da,double dt=1.0) {
return RotationVel(addDelta(a.R,da.p,dt),addDelta(a.w,da.v,dt));
}
IMETHOD TwistVel diff(const FrameVel& a,const FrameVel& b,double dt=1.0) {
return TwistVel(diff(a.M,b.M,dt),diff(a.p,b.p,dt));
}
IMETHOD FrameVel addDelta(const FrameVel& a,const TwistVel& da,double dt=1.0) {
return FrameVel(
addDelta(a.M,da.rot,dt),
addDelta(a.p,da.vel,dt)
);
}
IMETHOD void random(VectorVel& a) {
random(a.p);
random(a.v);
}
IMETHOD void random(TwistVel& a) {
random(a.vel);
random(a.rot);
}
IMETHOD void random(RotationVel& R) {
random(R.R);
random(R.w);
}
IMETHOD void random(FrameVel& F) {
random(F.M);
random(F.p);
}
IMETHOD void posrandom(VectorVel& a) {
posrandom(a.p);
posrandom(a.v);
}
IMETHOD void posrandom(TwistVel& a) {
posrandom(a.vel);
posrandom(a.rot);
}
IMETHOD void posrandom(RotationVel& R) {
posrandom(R.R);
posrandom(R.w);
}
IMETHOD void posrandom(FrameVel& F) {
posrandom(F.M);
posrandom(F.p);
}
#ifdef KDL_INLINE
#include "framevel.inl"
#endif
} // namespace
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/chainidsolver.hpp | // Copyright (C) 2009 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_CHAIN_IDSOLVER_HPP
#define KDL_CHAIN_IDSOLVER_HPP
#include "chain.hpp"
#include "frames.hpp"
#include "jntarray.hpp"
namespace KDL
{
typedef std::vector<Wrench> Wrenches;
/**
* \brief This <strong>abstract</strong> class encapsulates the inverse
* dynamics solver for a KDL::Chain.
*
*/
class ChainIdSolver
{
public:
/**
* Calculate inverse dynamics, from joint positions, velocity, acceleration, external forces
* to joint torques/forces.
*
* @param q input joint positions
* @param q_dot input joint velocities
* @param q_dotdot input joint accelerations
*
* @param torque output joint torques
*
* @return if < 0 something went wrong
*/
virtual int CartToJnt(const JntArray &q, const JntArray &q_dot, const JntArray &q_dotdot, const Wrenches& f_ext,JntArray &torques)=0;
// Need functions to return the manipulator mass, coriolis and gravity matrices - Lagrangian Formulation.
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/articulatedbodyinertia.cpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "articulatedbodyinertia.hpp"
#include <Eigen/Core>
using namespace Eigen;
namespace KDL{
ArticulatedBodyInertia::ArticulatedBodyInertia(const RigidBodyInertia& rbi)
{
this->M=Matrix3d::Identity()*rbi.m;
this->I=Map<const Matrix3d>(rbi.I.data);
this->H << 0,-rbi.h[2],rbi.h[1],
rbi.h[2],0,-rbi.h[0],
-rbi.h[1],rbi.h[0],0;
}
ArticulatedBodyInertia::ArticulatedBodyInertia(double m, const Vector& c, const RotationalInertia& Ic)
{
*this = RigidBodyInertia(m,c,Ic);
}
ArticulatedBodyInertia::ArticulatedBodyInertia(const Matrix3d& M, const Matrix3d& H, const Matrix3d& I)
{
this->M=M;
this->I=I;
this->H=H;
}
ArticulatedBodyInertia operator*(double a,const ArticulatedBodyInertia& I){
return ArticulatedBodyInertia(a*I.M,a*I.H,a*I.I);
}
ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia, const ArticulatedBodyInertia& Ib){
return ArticulatedBodyInertia(Ia.M+Ib.M,Ia.H+Ib.H,Ia.I+Ib.I);
}
ArticulatedBodyInertia operator+(const RigidBodyInertia& Ia, const ArticulatedBodyInertia& Ib){
return ArticulatedBodyInertia(Ia)+Ib;
}
ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia, const ArticulatedBodyInertia& Ib){
return ArticulatedBodyInertia(Ia.M-Ib.M,Ia.H-Ib.H,Ia.I-Ib.I);
}
ArticulatedBodyInertia operator-(const RigidBodyInertia& Ia, const ArticulatedBodyInertia& Ib){
return ArticulatedBodyInertia(Ia)-Ib;
}
Wrench operator*(const ArticulatedBodyInertia& I,const Twist& t){
Wrench result;
Vector3d::Map(result.force.data)=I.M*Vector3d::Map(t.vel.data)+I.H.transpose()*Vector3d::Map(t.rot.data);
Vector3d::Map(result.torque.data)=I.I*Vector3d::Map(t.rot.data)+I.H*Vector3d::Map(t.vel.data);
return result;
}
ArticulatedBodyInertia operator*(const Frame& T,const ArticulatedBodyInertia& I){
Frame X=T.Inverse();
//mb=ma
//hb=R*(h-m*r)
//Ib = R(Ia+r x h x + (h-m*r) x r x)R'
Map<Matrix3d> E(X.M.data);
Matrix3d rcross;
rcross << 0,-X.p[2],X.p[1],
X.p[2],0,-X.p[0],
-X.p[1],X.p[0],0;
Matrix3d HrM=I.H-rcross*I.M;
return ArticulatedBodyInertia(E*I.M*E.transpose(),E*HrM*E.transpose(),E*(I.I-rcross*I.H.transpose()+HrM*rcross)*E.transpose());
}
ArticulatedBodyInertia operator*(const Rotation& M,const ArticulatedBodyInertia& I){
Map<const Matrix3d> E(M.data);
return ArticulatedBodyInertia(E.transpose()*I.M*E,E.transpose()*I.H*E,E.transpose()*I.I*E);
}
ArticulatedBodyInertia ArticulatedBodyInertia::RefPoint(const Vector& p){
//mb=ma
//hb=R*(h-m*r)
//Ib = R(Ia+r x h x + (h-m*r) x r x)R'
Matrix3d rcross;
rcross << 0,-p[2],p[1],
p[2],0,-p[0],
-p[1],p[0],0;
Matrix3d HrM=this->H-rcross*this->M;
return ArticulatedBodyInertia(this->M,HrM,this->I-rcross*this->H.transpose()+HrM*rcross);
}
}//namespace
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/error.h | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:38 CET 2005 error.h
error.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/*****************************************************************************
* \file
* Defines the exception classes that can be thrown
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: error.h,v 1.1.1.1.2.2 2003/04/04 15:39:43 pissaris Exp $
* $Name: $
****************************************************************************/
#ifndef ERROR_H_84822 // to make it unique, a random number
#define ERROR_H_84822
#include "utility.h"
#include <string.h>
#include <string>
namespace KDL {
/**
* Base class for errors generated by ORO_Geometry
*/
class Error {
public:
/** Returns a description string describing the error.
* the returned pointer only garanteed to exists as long as
* the Error object exists.
*/
virtual ~Error() {}
virtual const char* Description() const {return "Unspecified Error\n";}
virtual int GetType() const {return 0;}
};
class Error_IO : public Error {
std::string msg;
int typenr;
public:
Error_IO(const std::string& _msg="Unspecified I/O Error",int typenr=0):msg(_msg) {}
virtual const char* Description() const {return msg.c_str();}
virtual int GetType() const {return typenr;}
};
class Error_BasicIO : public Error_IO {};
class Error_BasicIO_File : public Error_BasicIO {
public:
virtual const char* Description() const {return "Error while reading stream";}
virtual int GetType() const {return 1;}
};
class Error_BasicIO_Exp_Delim : public Error_BasicIO {
public:
virtual const char* Description() const {return "Expected Delimiter not encountered";}
virtual int GetType() const {return 2;}
};
class Error_BasicIO_Not_A_Space : public Error_BasicIO {
public:
virtual const char* Description() const {return "Expected space,tab or newline not encountered";}
virtual int GetType() const {return 3;}
};
class Error_BasicIO_Unexpected : public Error_BasicIO {
public:
virtual const char* Description() const {return "Unexpected character";}
virtual int GetType() const {return 4;}
};
class Error_BasicIO_ToBig : public Error_BasicIO {
public:
virtual const char* Description() const {return "Word that is read out of stream is bigger than maxsize";}
virtual int GetType() const {return 5;}
};
class Error_BasicIO_Not_Opened : public Error_BasicIO {
public:
virtual const char* Description() const {return "File cannot be opened";}
virtual int GetType() const {return 6;}
};
class Error_FrameIO : public Error_IO {};
class Error_Frame_Vector_Unexpected_id : public Error_FrameIO {
public:
virtual const char* Description() const {return "Unexpected identifier, expecting a vector (explicit or ZERO)";}
virtual int GetType() const {return 101;}
};
class Error_Frame_Frame_Unexpected_id : public Error_FrameIO {
public:
virtual const char* Description() const {return "Unexpected identifier, expecting a Frame (explicit or DH)";}
virtual int GetType() const {return 102;}
};
class Error_Frame_Rotation_Unexpected_id : public Error_FrameIO {
public:
virtual const char* Description() const {return "Unexpected identifier, expecting a Rotation (explicit or EULERZYX, EULERZYZ, RPY,ROT,IDENTITY)";}
virtual int GetType() const {return 103;}
};
class Error_ChainIO : public Error {};
class Error_Chain_Unexpected_id : public Error_ChainIO {
public:
virtual const char* Description() const {return "Unexpected identifier, expecting TRANS or ROT";}
virtual int GetType() const {return 201;}
};
//! Error_Redundancy indicates an error that occured during solving for redundancy.
class Error_RedundancyIO:public Error_IO {};
class Error_Redundancy_Illegal_Resolutiontype : public Error_RedundancyIO {
public:
virtual const char* Description() const {return "Illegal Resolutiontype is used in I/O with ResolutionTask";}
virtual int GetType() const {return 301;}
};
class Error_Redundancy:public Error {};
class Error_Redundancy_Unavoidable : public Error_Redundancy {
public:
virtual const char* Description() const {return "Joint limits cannot be avoided";}
virtual int GetType() const {return 1002;}
};
class Error_Redundancy_Low_Manip: public Error_Redundancy {
public:
virtual const char* Description() const {return "Manipulability is very low";}
virtual int GetType() const {return 1003;}
};
class Error_MotionIO : public Error {};
class Error_MotionIO_Unexpected_MotProf : public Error_MotionIO {
public:
virtual const char* Description() const { return "Wrong keyword while reading motion profile";}
virtual int GetType() const {return 2001;}
};
class Error_MotionIO_Unexpected_Traj : public Error_MotionIO {
public:
virtual const char* Description() const { return "Trajectory type keyword not known";}
virtual int GetType() const {return 2002;}
};
class Error_MotionPlanning : public Error {};
class Error_MotionPlanning_Circle_ToSmall : public Error_MotionPlanning {
public:
virtual const char* Description() const { return "Circle : radius is to small";}
virtual int GetType() const {return 3001;}
};
class Error_MotionPlanning_Circle_No_Plane : public Error_MotionPlanning {
public:
virtual const char* Description() const { return "Circle : Plane for motion is not properly defined";}
virtual int GetType() const {return 3002;}
};
class Error_MotionPlanning_Incompatible: public Error_MotionPlanning {
public:
virtual const char* Description() const { return "Acceleration of a rectangular velocityprofile cannot be used";}
virtual int GetType() const {return 3003;}
};
class Error_MotionPlanning_Not_Feasible: public Error_MotionPlanning {
int reason;
public:
Error_MotionPlanning_Not_Feasible(int _reason):reason(_reason) {}
virtual const char* Description() const {
return "Motion Profile with requested parameters is not feasible";
}
virtual int GetType() const {return 3100+reason;}
};
class Error_MotionPlanning_Not_Applicable: public Error_MotionPlanning {
public:
virtual const char* Description() const { return "Method is not applicable for this derived object";}
virtual int GetType() const {return 3004;}
};
//! Abstract subclass of all errors that can be thrown by Adaptive_Integrator
class Error_Integrator : public Error {};
//! Error_Stepsize_Underflow is thrown if the stepsize becomes to small
class Error_Stepsize_Underflow : public Error_Integrator {
public:
virtual const char* Description() const { return "Stepsize Underflow";}
virtual int GetType() const {return 4001;}
};
//! Error_To_Many_Steps is thrown if the number of steps needed to
//! integrate to the desired accuracy becomes to big.
class Error_To_Many_Steps : public Error_Integrator {
public:
virtual const char* Description() const { return "To many steps"; }
virtual int GetType() const {return 4002;}
};
//! Error_Stepsize_To_Small is thrown if the stepsize becomes to small
class Error_Stepsize_To_Small : public Error_Integrator {
public:
virtual const char* Description() const { return "Stepsize to small"; }
virtual int GetType() const {return 4003;}
};
class Error_Criterium : public Error {};
class Error_Criterium_Unexpected_id: public Error_Criterium {
public:
virtual const char* Description() const { return "Unexpected identifier while reading a criterium"; }
virtual int GetType() const {return 5001;}
};
class Error_Limits : public Error {};
class Error_Limits_Unexpected_id: public Error_Limits {
public:
virtual const char* Description() const { return "Unexpected identifier while reading a jointlimits"; }
virtual int GetType() const {return 6001;}
};
class Error_Not_Implemented: public Error {
public:
virtual const char* Description() const { return "The requested object/method/function is not implemented"; }
virtual int GetType() const {return 7000;}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/rall1d.h |
/*****************************************************************************
* \file
* class for automatic differentiation on scalar values and 1st
* derivatives .
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par Note
* VC6++ contains a bug, concerning the use of inlined friend functions
* in combination with namespaces. So, try to avoid inlined friend
* functions !
*
* \par History
* - $log$
*
* \par Release
* $Id: rall1d.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef Rall1D_H
#define Rall1D_H
#include <assert.h>
#include "utility.h"
namespace KDL {
/**
* Rall1d contains a value, and its gradient, and defines an algebraic structure on this pair.
* This template class has 3 template parameters :
* - T contains the type of the value.
* - V contains the type of the gradient (can be a vector-like type).
* - S defines a scalar type that can operate on Rall1d. This is the type that
* is used to give back values of Norm() etc.
*
* S is usefull when you recurse a Rall1d object into itself to create a 2nd, 3th, 4th,..
* derivatives. (e.g. Rall1d< Rall1d<double>, Rall1d<double>, double> ).
*
* S is always passed by value.
*
* \par Class Type
* Concrete implementation
*/
template <typename T,typename V=T,typename S=T>
class Rall1d
{
public:
typedef T valuetype;
typedef V gradienttype;
typedef S scalartype;
public :
T t; //!< value
V grad; //!< gradient
public :
INLINE Rall1d() {}
T value() const {
return t;
}
V deriv() const {
return grad;
}
explicit INLINE Rall1d(typename TI<T>::Arg c)
{t=T(c);SetToZero(grad);}
INLINE Rall1d(typename TI<T>::Arg tn, typename TI<V>::Arg afg):t(tn),grad(afg) {}
INLINE Rall1d(const Rall1d<T,V,S>& r):t(r.t),grad(r.grad) {}
//if one defines this constructor, it's better optimized then the
//automatically generated one ( this one set's up a loop to copy
// word by word.
INLINE T& Value() {
return t;
}
INLINE V& Gradient() {
return grad;
}
INLINE static Rall1d<T,V,S> Zero() {
Rall1d<T,V,S> tmp;
SetToZero(tmp);
return tmp;
}
INLINE static Rall1d<T,V,S> Identity() {
Rall1d<T,V,S> tmp;
SetToIdentity(tmp);
return tmp;
}
INLINE Rall1d<T,V,S>& operator =(S c)
{t=c;SetToZero(grad);return *this;}
INLINE Rall1d<T,V,S>& operator =(const Rall1d<T,V,S>& r)
{t=r.t;grad=r.grad;return *this;}
INLINE Rall1d<T,V,S>& operator /=(const Rall1d<T,V,S>& rhs)
{
grad = LinComb(rhs.t,grad,-t,rhs.grad) / (rhs.t*rhs.t);
t /= rhs.t;
return *this;
}
INLINE Rall1d<T,V,S>& operator *=(const Rall1d<T,V,S>& rhs)
{
LinCombR(rhs.t,grad,t,rhs.grad,grad);
t *= rhs.t;
return *this;
}
INLINE Rall1d<T,V,S>& operator +=(const Rall1d<T,V,S>& rhs)
{
grad +=rhs.grad;
t +=rhs.t;
return *this;
}
INLINE Rall1d<T,V,S>& operator -=(const Rall1d<T,V,S>& rhs)
{
grad -= rhs.grad;
t -= rhs.t;
return *this;
}
INLINE Rall1d<T,V,S>& operator /=(S rhs)
{
grad /= rhs;
t /= rhs;
return *this;
}
INLINE Rall1d<T,V,S>& operator *=(S rhs)
{
grad *= rhs;
t *= rhs;
return *this;
}
INLINE Rall1d<T,V,S>& operator +=(S rhs)
{
t += rhs;
return *this;
}
INLINE Rall1d<T,V,S>& operator -=(S rhs)
{
t -= rhs;
return *this;
}
// = operators
/* gives warnings on cygwin
template <class T2,class V2,class S2>
friend INLINE Rall1d<T2,V2,S2> operator /(const Rall1d<T2,V2,S2>& lhs,const Rall1d<T2,V2,S2>& rhs);
friend INLINE Rall1d<T,V,S> operator *(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs);
friend INLINE Rall1d<T,V,S> operator +(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs);
friend INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs);
friend INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> operator *(S s,const Rall1d<T,V,S>& v);
friend INLINE Rall1d<T,V,S> operator *(const Rall1d<T,V,S>& v,S s);
friend INLINE Rall1d<T,V,S> operator +(S s,const Rall1d<T,V,S>& v);
friend INLINE Rall1d<T,V,S> operator +(const Rall1d<T,V,S>& v,S s);
friend INLINE Rall1d<T,V,S> operator -(S s,const Rall1d<T,V,S>& v);
friend INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& v,S s);
friend INLINE Rall1d<T,V,S> operator /(S s,const Rall1d<T,V,S>& v);
friend INLINE Rall1d<T,V,S> operator /(const Rall1d<T,V,S>& v,S s);
// = Mathematical functions that operate on Rall1d objects
friend INLINE Rall1d<T,V,S> exp(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> log(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> sin(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> cos(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> tan(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> sinh(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> cosh(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> sqr(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> pow(const Rall1d<T,V,S>& arg,double m) ;
friend INLINE Rall1d<T,V,S> sqrt(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> atan(const Rall1d<T,V,S>& x);
friend INLINE Rall1d<T,V,S> hypot(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x);
friend INLINE Rall1d<T,V,S> asin(const Rall1d<T,V,S>& x);
friend INLINE Rall1d<T,V,S> acos(const Rall1d<T,V,S>& x);
friend INLINE Rall1d<T,V,S> abs(const Rall1d<T,V,S>& x);
friend INLINE S Norm(const Rall1d<T,V,S>& value) ;
friend INLINE Rall1d<T,V,S> tanh(const Rall1d<T,V,S>& arg);
friend INLINE Rall1d<T,V,S> atan2(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x);
// = Utility functions to improve performance
friend INLINE Rall1d<T,V,S> LinComb(S alfa,const Rall1d<T,V,S>& a,
const T& beta,const Rall1d<T,V,S>& b );
friend INLINE void LinCombR(S alfa,const Rall1d<T,V,S>& a,
const T& beta,const Rall1d<T,V,S>& b,Rall1d<T,V,S>& result );
// = Setting value of a Rall1d object to 0 or 1
friend INLINE void SetToZero(Rall1d<T,V,S>& value);
friend INLINE void SetToOne(Rall1d<T,V,S>& value);
// = Equality in an eps-interval
friend INLINE bool Equal(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x,double eps);
*/
};
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator /(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs)
{
return Rall1d<T,V,S>(lhs.t/rhs.t,(lhs.grad*rhs.t-lhs.t*rhs.grad)/(rhs.t*rhs.t));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator *(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs)
{
return Rall1d<T,V,S>(lhs.t*rhs.t,rhs.t*lhs.grad+lhs.t*rhs.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator +(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs)
{
return Rall1d<T,V,S>(lhs.t+rhs.t,lhs.grad+rhs.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& lhs,const Rall1d<T,V,S>& rhs)
{
return Rall1d<T,V,S>(lhs.t-rhs.t,lhs.grad-rhs.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& arg)
{
return Rall1d<T,V,S>(-arg.t,-arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator *(S s,const Rall1d<T,V,S>& v)
{
return Rall1d<T,V,S>(s*v.t,s*v.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator *(const Rall1d<T,V,S>& v,S s)
{
return Rall1d<T,V,S>(v.t*s,v.grad*s);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator +(S s,const Rall1d<T,V,S>& v)
{
return Rall1d<T,V,S>(s+v.t,v.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator +(const Rall1d<T,V,S>& v,S s)
{
return Rall1d<T,V,S>(v.t+s,v.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator -(S s,const Rall1d<T,V,S>& v)
{
return Rall1d<T,V,S>(s-v.t,-v.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator -(const Rall1d<T,V,S>& v,S s)
{
return Rall1d<T,V,S>(v.t-s,v.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator /(S s,const Rall1d<T,V,S>& v)
{
return Rall1d<T,V,S>(s/v.t,(-s*v.grad)/(v.t*v.t));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> operator /(const Rall1d<T,V,S>& v,S s)
{
return Rall1d<T,V,S>(v.t/s,v.grad/s);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> exp(const Rall1d<T,V,S>& arg)
{
T v;
v= (exp(arg.t));
return Rall1d<T,V,S>(v,v*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> log(const Rall1d<T,V,S>& arg)
{
T v;
v=(log(arg.t));
return Rall1d<T,V,S>(v,arg.grad/arg.t);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> sin(const Rall1d<T,V,S>& arg)
{
T v;
v=(sin(arg.t));
return Rall1d<T,V,S>(v,cos(arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> cos(const Rall1d<T,V,S>& arg)
{
T v;
v=(cos(arg.t));
return Rall1d<T,V,S>(v,-sin(arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> tan(const Rall1d<T,V,S>& arg)
{
T v;
v=(tan(arg.t));
return Rall1d<T,V,S>(v,arg.grad/sqr(cos(arg.t)));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> sinh(const Rall1d<T,V,S>& arg)
{
T v;
v=(sinh(arg.t));
return Rall1d<T,V,S>(v,cosh(arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> cosh(const Rall1d<T,V,S>& arg)
{
T v;
v=(cosh(arg.t));
return Rall1d<T,V,S>(v,sinh(arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> sqr(const Rall1d<T,V,S>& arg)
{
T v;
v=(arg.t*arg.t);
return Rall1d<T,V,S>(v,(2.0*arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> pow(const Rall1d<T,V,S>& arg,double m)
{
T v;
v=(pow(arg.t,m));
return Rall1d<T,V,S>(v,(m*v/arg.t)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> sqrt(const Rall1d<T,V,S>& arg)
{
T v;
v=sqrt(arg.t);
return Rall1d<T,V,S>(v, (0.5/v)*arg.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> atan(const Rall1d<T,V,S>& x)
{
T v;
v=(atan(x.t));
return Rall1d<T,V,S>(v,x.grad/(1.0+sqr(x.t)));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> hypot(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x)
{
T v;
v=(hypot(y.t,x.t));
return Rall1d<T,V,S>(v,(x.t/v)*x.grad+(y.t/v)*y.grad);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> asin(const Rall1d<T,V,S>& x)
{
T v;
v=(asin(x.t));
return Rall1d<T,V,S>(v,x.grad/sqrt(1.0-sqr(x.t)));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> acos(const Rall1d<T,V,S>& x)
{
T v;
v=(acos(x.t));
return Rall1d<T,V,S>(v,-x.grad/sqrt(1.0-sqr(x.t)));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> abs(const Rall1d<T,V,S>& x)
{
T v;
v=(Sign(x));
return Rall1d<T,V,S>(v*x,v*x.grad);
}
template <class T,class V,class S>
INLINE S Norm(const Rall1d<T,V,S>& value)
{
return Norm(value.t);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> tanh(const Rall1d<T,V,S>& arg)
{
T v(tanh(arg.t));
return Rall1d<T,V,S>(v,arg.grad/sqr(cosh(arg.t)));
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> atan2(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x)
{
T v(x.t*x.t+y.t*y.t);
return Rall1d<T,V,S>(atan2(y.t,x.t),(x.t*y.grad-y.t*x.grad)/v);
}
template <class T,class V,class S>
INLINE Rall1d<T,V,S> LinComb(S alfa,const Rall1d<T,V,S>& a,
const T& beta,const Rall1d<T,V,S>& b ) {
return Rall1d<T,V,S>(
LinComb(alfa,a.t,beta,b.t),
LinComb(alfa,a.grad,beta,b.grad)
);
}
template <class T,class V,class S>
INLINE void LinCombR(S alfa,const Rall1d<T,V,S>& a,
const T& beta,const Rall1d<T,V,S>& b,Rall1d<T,V,S>& result ) {
LinCombR(alfa, a.t, beta, b.t, result.t);
LinCombR(alfa, a.grad, beta, b.grad, result.grad);
}
template <class T,class V,class S>
INLINE void SetToZero(Rall1d<T,V,S>& value)
{
SetToZero(value.grad);
SetToZero(value.t);
}
template <class T,class V,class S>
INLINE void SetToIdentity(Rall1d<T,V,S>& value)
{
SetToIdentity(value.t);
SetToZero(value.grad);
}
template <class T,class V,class S>
INLINE bool Equal(const Rall1d<T,V,S>& y,const Rall1d<T,V,S>& x,double eps=epsilon)
{
return (Equal(x.t,y.t,eps)&&Equal(x.grad,y.grad,eps));
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/utility.cxx | /** @file utility.cpp
* @author Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
* @version
* ORO_Geometry V0.2
*
* @par history
* - changed layout of the comments to accomodate doxygen
*/
#include "utility.h"
namespace KDL {
int STREAMBUFFERSIZE=10000;
int MAXLENFILENAME = 255;
const double PI= 3.1415926535897932384626433832795;
const double deg2rad = 0.01745329251994329576923690768488;
const double rad2deg = 57.2957795130823208767981548141052;
double epsilon = 0.000001;
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/traits.h | #ifndef KDLPV_TRAITS_H
#define KDLPV_TRAITS_H
#include "utility.h"
// forwards declarations :
namespace KDL {
class Frame;
class Rotation;
class Vector;
class Twist;
class Wrench;
class FrameVel;
class RotationVel;
class VectorVel;
class TwistVel;
}
/**
* @brief Traits are traits classes to determine the type of a derivative of another type.
*
* For geometric objects the "geometric" derivative is chosen. For example the derivative of a Rotation
* matrix is NOT a 3x3 matrix containing the derivative of the elements of a rotation matrix. The derivative
* of the rotation matrix is a Vector corresponding the rotational velocity. Mostly used in template classes
* and routines to derive a correct type when needed.
*
* You can see this as a compile-time lookuptable to find the type of the derivative.
*
* Example
* \verbatim
Rotation R;
Traits<Rotation> dR;
\endverbatim
*/
template <typename T>
struct Traits {
typedef T valueType;
typedef T derivType;
};
template <>
struct Traits<KDL::Frame> {
typedef KDL::Frame valueType;
typedef KDL::Twist derivType;
};
template <>
struct Traits<KDL::Twist> {
typedef KDL::Twist valueType;
typedef KDL::Twist derivType;
};
template <>
struct Traits<KDL::Wrench> {
typedef KDL::Wrench valueType;
typedef KDL::Wrench derivType;
};
template <>
struct Traits<KDL::Rotation> {
typedef KDL::Rotation valueType;
typedef KDL::Vector derivType;
};
template <>
struct Traits<KDL::Vector> {
typedef KDL::Vector valueType;
typedef KDL::Vector derivType;
};
template <>
struct Traits<double> {
typedef double valueType;
typedef double derivType;
};
template <>
struct Traits<float> {
typedef float valueType;
typedef float derivType;
};
template <>
struct Traits<KDL::FrameVel> {
typedef KDL::Frame valueType;
typedef KDL::TwistVel derivType;
};
template <>
struct Traits<KDL::TwistVel> {
typedef KDL::Twist valueType;
typedef KDL::TwistVel derivType;
};
template <>
struct Traits<KDL::RotationVel> {
typedef KDL::Rotation valueType;
typedef KDL::VectorVel derivType;
};
template <>
struct Traits<KDL::VectorVel> {
typedef KDL::Vector valueType;
typedef KDL::VectorVel derivType;
};
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/kdl-config.h | /* Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be> */
/* Version: 1.0 */
/* Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be> */
/* Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be> */
/* URL: http://www.orocos.org/kdl */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Methods are inlined */
#define KDL_INLINE 1
/* Column width that is used form printing frames */
#define KDL_FRAME_WIDTH 12
/* Indices are checked when accessing members of the objects */
#define KDL_INDEX_CHECK 1
/* use KDL implementation for == operator */
#define KDL_USE_EQUAL 1
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/error_stack.h | /***************************************************************************
tag: Erwin Aertbelien Mon Jan 10 16:38:39 CET 2005 error_stack.h
error_stack.h - description
-------------------
begin : Mon January 10 2005
copyright : (C) 2005 Erwin Aertbelien
email : erwin.aertbelien@mech.kuleuven.ac.be
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
/**
* \file
* \author Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
* \version
* ORO_Geometry V0.2
*
* \par history
* - changed layout of the comments to accomodate doxygen
*/
#ifndef ERROR_STACK_H
#define ERROR_STACK_H
#include "utility.h"
#include "utility_io.h"
#include <string>
namespace KDL {
/*
* \todo
* IOTrace-routines store in static memory, should be in thread-local memory.
* pushes a description of the current routine on the IO-stack trace
*/
void IOTrace(const std::string& description);
//! pops a description of the IO-stack
void IOTracePop();
//! outputs the IO-stack to a stream to provide a better errormessage.
void IOTraceOutput(std::ostream& os);
//! outputs one element of the IO-stack to the buffer (maximally size chars)
//! returns empty string if no elements on the stack.
void IOTracePopStr(char* buffer,int size);
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_HH.cpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//Based on the svd of the KDL-0.2 library by Erwin Aertbelien
#include "svd_HH.hpp"
namespace KDL
{
inline double PYTHAG(double a,double b) {
double at,bt,ct;
at = fabs(a);
bt = fabs(b);
if (at > bt ) {
ct=bt/at;
return at*sqrt(1.0+ct*ct);
} else {
if (bt==0)
return 0.0;
else {
ct=at/bt;
return bt*sqrt(1.0+ct*ct);
}
}
}
inline double SIGN(double a,double b) {
return ((b) >= 0.0 ? fabs(a) : -fabs(a));
}
SVD_HH::SVD_HH(const Jacobian& jac):
tmp(jac.columns())
{
}
SVD_HH::~SVD_HH()
{
}
int SVD_HH::calculate(const Jacobian& jac,std::vector<JntArray>& U,JntArray& w,std::vector<JntArray>& v,int maxiter)
{
//get the rows/columns of the jacobian
const int rows = jac.rows();
const int cols = jac.columns();
int i(-1),its(-1),j(-1),jj(-1),k(-1),nm=0;
int ppi(0);
bool flag,maxarg1,maxarg2;
double anorm(0),c(0),f(0),h(0),s(0),scale(0),x(0),y(0),z(0),g(0);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
U[i](j)=jac(i,j);
if(rows>cols)
for(i=rows;i<cols;i++)
for(j=0;j<cols;j++)
U[i](j)=0;
/* Householder reduction to bidiagonal form. */
for (i=0;i<cols;i++) {
ppi=i+1;
tmp(i)=scale*g;
g=s=scale=0.0;
if (i<rows) {
for (k=i;k<rows;k++) scale += fabs(U[k](i));
if (scale) {
// multiply the i-th column by 1.0/scale, start from the i-th element
// sum of squares of column i, start from the i-th element
for (k=i;k<rows;k++) {
U[k](i) /= scale;
s += U[k](i)*U[k](i);
}
f=U[i](i); // f is the diag elem
g = -SIGN(sqrt(s),f);
h=f*g-s;
U[i](i)=f-g;
for (j=ppi;j<cols;j++) {
// dot product of columns i and j, starting from the i-th row
for (s=0.0,k=i;k<rows;k++) s += U[k](i)*U[k](j);
f=s/h;
// copy the scaled i-th column into the j-th column
for (k=i;k<rows;k++) U[k](j) += f*U[k](i);
}
for (k=i;k<rows;k++) U[k](i) *= scale;
}
}
// save singular value
w(i)=scale*g;
g=s=scale=0.0;
if ((i <rows) && (i+1 != cols)) {
// sum of row i, start from columns i+1
for (k=ppi;k<cols;k++) scale += fabs(U[i](k));
if (scale) {
for (k=ppi;k<cols;k++) {
U[i](k) /= scale;
s += U[i](k)*U[i](k);
}
f=U[i](ppi);
g = -SIGN(sqrt(s),f);
h=f*g-s;
U[i](ppi)=f-g;
for (k=ppi;k<cols;k++) tmp(k)=U[i](k)/h;
for (j=ppi;j<rows;j++) {
for (s=0.0,k=ppi;k<cols;k++) s += U[j](k)*U[i](k);
for (k=ppi;k<cols;k++) U[j](k) += s*tmp(k);
}
for (k=ppi;k<cols;k++) U[i](k) *= scale;
}
}
maxarg1=anorm;
maxarg2=(fabs(w(i))+fabs(tmp(i)));
anorm = maxarg1 > maxarg2 ? maxarg1 : maxarg2;
}
/* Accumulation of right-hand transformations. */
for (i=cols-1;i>=0;i--) {
if (i<cols-1) {
if (g) {
for (j=ppi;j<cols;j++) v[j](i)=(U[i](j)/U[i](ppi))/g;
for (j=ppi;j<cols;j++) {
for (s=0.0,k=ppi;k<cols;k++) s += U[i](k)*v[k](j);
for (k=ppi;k<cols;k++) v[k](j) += s*v[k](i);
}
}
for (j=ppi;j<cols;j++) v[i](j)=v[j](i)=0.0;
}
v[i](i)=1.0;
g=tmp(i);
ppi=i;
}
/* Accumulation of left-hand transformations. */
for (i=cols-1<rows-1 ? cols-1:rows-1;i>=0;i--) {
ppi=i+1;
g=w(i);
for (j=ppi;j<cols;j++) U[i](j)=0.0;
if (g) {
g=1.0/g;
for (j=ppi;j<cols;j++) {
for (s=0.0,k=ppi;k<rows;k++) s += U[k](i)*U[k](j);
f=(s/U[i](i))*g;
for (k=i;k<rows;k++) U[k](j) += f*U[k](i);
}
for (j=i;j<rows;j++) U[j](i) *= g;
} else {
for (j=i;j<rows;j++) U[j](i)=0.0;
}
++U[i](i);
}
/* Diagonalization of the bidiagonal form. */
for (k=cols-1;k>=0;k--) { /* Loop over singular values. */
for (its=1;its<=maxiter;its++) { /* Loop over allowed iterations. */
flag=true;
for (ppi=k;ppi>=0;ppi--) { /* Test for splitting. */
nm=ppi-1; /* Note that tmp[1] is always zero. */
if ((fabs(tmp(ppi))+anorm) == anorm) {
flag=false;
break;
}
if ((fabs(w(nm)+anorm) == anorm)) break;
}
if (flag) {
c=0.0; /* Cancellation of tmp[l], if l>1: */
s=1.0;
for (i=ppi;i<=k;i++) {
f=s*tmp(i);
tmp(i)=c*tmp(i);
if ((fabs(f)+anorm) == anorm) break;
g=w(i);
h=PYTHAG(f,g);
w(i)=h;
h=1.0/h;
c=g*h;
s=(-f*h);
for (j=0;j<rows;j++) {
y=U[j](nm);
z=U[j](i);
U[j](nm)=y*c+z*s;
U[j](i)=z*c-y*s;
}
}
}
z=w(k);
if (ppi == k) { /* Convergence. */
if (z < 0.0) { /* Singular value is made nonnegative. */
w(k) = -z;
for (j=0;j<cols;j++) v[j](k)=-v[j](k);
}
break;
}
x=w(ppi); /* Shift from bottom 2-by-2 minor: */
nm=k-1;
y=w(nm);
g=tmp(nm);
h=tmp(k);
f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
g=PYTHAG(f,1.0);
f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
/* Next QR transformation: */
c=s=1.0;
for (j=ppi;j<=nm;j++) {
i=j+1;
g=tmp(i);
y=w(i);
h=s*g;
g=c*g;
z=PYTHAG(f,h);
tmp(j)=z;
c=f/z;
s=h/z;
f=x*c+g*s;
g=g*c-x*s;
h=y*s;
y=y*c;
for (jj=0;jj<cols;jj++) {
x=v[jj](j);
z=v[jj](i);
v[jj](j)=x*c+z*s;
v[jj](i)=z*c-x*s;
}
z=PYTHAG(f,h);
w(j)=z;
if (z) {
z=1.0/z;
c=f*z;
s=h*z;
}
f=(c*g)+(s*y);
x=(c*y)-(s*g);
for (jj=0;jj<rows;jj++) {
y=U[jj](j);
z=U[jj](i);
U[jj](j)=y*c+z*s;
U[jj](i)=z*c-y*s;
}
}
tmp(ppi)=0.0;
tmp(k)=f;
w(k)=x;
}
}
if (its == maxiter)
return (-2);
else
return (0);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_HH.cpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "svd_eigen_HH.hpp"
namespace KDL{
int svd_eigen_HH(const MatrixXd& A,MatrixXd& U,VectorXd& S,MatrixXd& V,VectorXd& tmp,int maxiter,double epsilon)
{
//get the rows/columns of the matrix
const int rows = A.rows();
const int cols = A.cols();
U.setZero();
U.topLeftCorner(rows,cols)=A;
int i(-1),its(-1),j(-1),jj(-1),k(-1),nm=0;
int ppi(0);
bool flag,maxarg1,maxarg2;
double anorm(0),c(0),f(0),h(0),s(0),scale(0),x(0),y(0),z(0),g(0);
/* Householder reduction to bidiagonal form. */
for (i=0;i<cols;i++) {
ppi=i+1;
tmp(i)=scale*g;
g=s=scale=0.0;
if (i<rows) {
// compute the sum of the i-th column, starting from the i-th row
for (k=i;k<rows;k++) scale += fabs(U(k,i));
if (fabs(scale)>epsilon) {
// multiply the i-th column by 1.0/scale, start from the i-th element
// sum of squares of column i, start from the i-th element
for (k=i;k<rows;k++) {
U(k,i) /= scale;
s += U(k,i)*U(k,i);
}
f=U(i,i); // f is the diag elem
if (!(s>=0)) return -3;
g = -SIGN(sqrt(s),f);
h=f*g-s;
U(i,i)=f-g;
for (j=ppi;j<cols;j++) {
// dot product of columns i and j, starting from the i-th row
for (s=0.0,k=i;k<rows;k++) s += U(k,i)*U(k,j);
if (!(h!=0)) return -4;
f=s/h;
// copy the scaled i-th column into the j-th column
for (k=i;k<rows;k++) U(k,j) += f*U(k,i);
}
for (k=i;k<rows;k++) U(k,i) *= scale;
}
}
// save singular value
S(i)=scale*g;
g=s=scale=0.0;
if ((i <rows) && (i+1 != cols)) {
// sum of row i, start from columns i+1
for (k=ppi;k<cols;k++) scale += fabs(U(i,k));
if (fabs(scale)>epsilon) {
for (k=ppi;k<cols;k++) {
U(i,k) /= scale;
s += U(i,k)*U(i,k);
}
f=U(i,ppi);
if (!(s>=0)) return -5;
g = -SIGN(sqrt(s),f);
h=f*g-s;
U(i,ppi)=f-g;
if (!(h!=0)) return -6;
for (k=ppi;k<cols;k++) tmp(k)=U(i,k)/h;
for (j=ppi;j<rows;j++) {
for (s=0.0,k=ppi;k<cols;k++) s += U(j,k)*U(i,k);
for (k=ppi;k<cols;k++) U(j,k) += s*tmp(k);
}
for (k=ppi;k<cols;k++) U(i,k) *= scale;
}
}
maxarg1=anorm;
maxarg2=(fabs(S(i))+fabs(tmp(i)));
anorm = maxarg1 > maxarg2 ? maxarg1 : maxarg2;
}
/* Accumulation of right-hand transformations. */
for (i=cols-1;i>=0;i--) {
if (i<cols-1) {
if (fabs(g)>epsilon) {
if (!(U(i,ppi)!=0)) return -7;
for (j=ppi;j<cols;j++) V(j,i)=(U(i,j)/U(i,ppi))/g;
for (j=ppi;j<cols;j++) {
for (s=0.0,k=ppi;k<cols;k++) s += U(i,k)*V(k,j);
for (k=ppi;k<cols;k++) V(k,j) += s*V(k,i);
}
}
for (j=ppi;j<cols;j++) V(i,j)=V(j,i)=0.0;
}
V(i,i)=1.0;
g=tmp(i);
ppi=i;
}
/* Accumulation of left-hand transformations. */
for (i=cols-1<rows-1 ? cols-1:rows-1;i>=0;i--) {
ppi=i+1;
g=S(i);
for (j=ppi;j<cols;j++) U(i,j)=0.0;
if (fabs(g)>epsilon) {
g=1.0/g;
for (j=ppi;j<cols;j++) {
for (s=0.0,k=ppi;k<rows;k++) s += U(k,i)*U(k,j);
if (!(U(i,i)!=0)) return -8;
f=(s/U(i,i))*g;
for (k=i;k<rows;k++) U(k,j) += f*U(k,i);
}
for (j=i;j<rows;j++) U(j,i) *= g;
} else {
for (j=i;j<rows;j++) U(j,i)=0.0;
}
++U(i,i);
}
/* Diagonalization of the bidiagonal form. */
for (k=cols-1;k>=0;k--) { /* Loop over singular values. */
for (its=1;its<=maxiter;its++) { /* Loop over allowed iterations. */
flag=true;
for (ppi=k;ppi>=0;ppi--) { /* Test for splitting. */
nm=ppi-1; /* Note that tmp[1] is always zero. */
if ((fabs(tmp(ppi))+anorm) == anorm) {
flag=false;
break;
}
if ((fabs(S(nm)+anorm) == anorm)) break;
}
if (flag) {
c=0.0; /* Cancellation of tmp[l], if l>1: */
s=1.0;
for (i=ppi;i<=k;i++) {
f=s*tmp(i);
tmp(i)=c*tmp(i);
if ((fabs(f)+anorm) == anorm) break;
g=S(i);
h=PYTHAG(f,g);
S(i)=h;
if (!(h!=0)) return -9;
h=1.0/h;
c=g*h;
s=(-f*h);
for (j=0;j<rows;j++) {
y=U(j,nm);
z=U(j,i);
U(j,nm)=y*c+z*s;
U(j,i)=z*c-y*s;
}
}
}
z=S(k);
if (ppi == k) { /* Convergence. */
if (z < 0.0) { /* Singular value is made nonnegative. */
S(k) = -z;
for (j=0;j<cols;j++) V(j,k)=-V(j,k);
}
break;
}
x=S(ppi); /* Shift from bottom 2-by-2 minor: */
nm=k-1;
y=S(nm);
g=tmp(nm);
h=tmp(k);
if (!(h!=0&&y!=0)) return -10;
f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
g=PYTHAG(f,1.0);
if (!(x!=0)) return -11;
if (!((f+SIGN(g,f))!=0)) return -12;
f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
/* Next QR transformation: */
c=s=1.0;
for (j=ppi;j<=nm;j++) {
i=j+1;
g=tmp(i);
y=S(i);
h=s*g;
g=c*g;
z=PYTHAG(f,h);
tmp(j)=z;
if (!(z!=0)) return -13;
c=f/z;
s=h/z;
f=x*c+g*s;
g=g*c-x*s;
h=y*s;
y=y*c;
for (jj=0;jj<cols;jj++) {
x=V(jj,j);
z=V(jj,i);
V(jj,j)=x*c+z*s;
V(jj,i)=z*c-x*s;
}
z=PYTHAG(f,h);
S(j)=z;
if (fabs(z)>epsilon) {
z=1.0/z;
c=f*z;
s=h*z;
}
f=(c*g)+(s*y);
x=(c*y)-(s*g);
for (jj=0;jj<rows;jj++) {
y=U(jj,j);
z=U(jj,i);
U(jj,j)=y*c+z*s;
U(jj,i)=z*c-y*s;
}
}
tmp(ppi)=0.0;
tmp(k)=f;
S(k)=x;
}
}
//Sort eigen values:
for (i=0; i<cols; i++){
double S_max = S(i);
int i_max = i;
for (j=i+1; j<cols; j++){
double Sj = S(j);
if (Sj > S_max){
S_max = Sj;
i_max = j;
}
}
if (i_max != i){
/* swap eigenvalues */
double tmp = S(i);
S(i)=S(i_max);
S(i_max)=tmp;
/* swap eigenvectors */
U.col(i).swap(U.col(i_max));
V.col(i).swap(V.col(i_max));
}
}
if (its == maxiter)
return (-2);
else
return (0);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/utility_io.h | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: utility_io.h,v 1.1.1.1.2.3 2003/06/26 15:23:59 psoetens Exp $
* $Name: $
*
* \file utility_io.h
* Included by most lrl-files to provide some general
* functions and macro definitions related to file/stream I/O.
*/
#ifndef KDL_UTILITY_IO_H_84822
#define KDL_UTILITY_IO_H_84822
//#include <kdl/kdl-config.h>
// Standard includes
#include <iostream>
#include <iomanip>
#include <fstream>
namespace KDL {
/**
* checks validity of basic io of is
*/
void _check_istream(std::istream& is);
/**
* Eats characters of the stream until the character delim is encountered
* @param is a stream
* @param delim eat until this character is encountered
*/
void Eat(std::istream& is, int delim );
/**
* Eats characters of the stream as long as they satisfy the description in descript
* @param is a stream
* @param descript description string. A sequence of spaces, tabs,
* new-lines and comments is regarded as 1 space in the description string.
*/
void Eat(std::istream& is,const char* descript);
/**
* Eats a word of the stream delimited by the letters in delim or space(tabs...)
* @param is a stream
* @param delim a string containing the delimmiting characters
* @param storage for returning the word
* @param maxsize a word can be maximally maxsize-1 long.
*/
void EatWord(std::istream& is,const char* delim,char* storage,int maxsize);
/**
* Eats characters of the stream until the character delim is encountered
* similar to Eat(is,delim) but spaces at the end are not read.
* @param is a stream
* @param delim eat until this character is encountered
*/
void EatEnd( std::istream& is, int delim );
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/error_stack.cxx | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: error_stack.cpp,v 1.1.1.1.2.1 2003/02/24 13:13:06 psoetens Exp $
* $Name: $
****************************************************************************/
#include "error_stack.h"
#include <stack>
#include <vector>
#include <string>
#include <cstring>
namespace KDL {
// Trace of the call stack of the I/O routines to help user
// interprete error messages from I/O
typedef std::stack<std::string> ErrorStack;
ErrorStack errorstack;
// should be in Thread Local Storage if this gets multithreaded one day...
void IOTrace(const std::string& description) {
errorstack.push(description);
}
void IOTracePop() {
errorstack.pop();
}
void IOTraceOutput(std::ostream& os) {
while (!errorstack.empty()) {
os << errorstack.top().c_str() << std::endl;
errorstack.pop();
}
}
void IOTracePopStr(char* buffer,int size) {
if (errorstack.empty()) {
*buffer = 0;
return;
}
strncpy(buffer,errorstack.top().c_str(),size);
errorstack.pop();
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_HH.hpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//Based on the svd of the KDL-0.2 library by Erwin Aertbelien
#ifndef SVD_EIGEN_HH_HPP
#define SVD_EIGEN_HH_HPP
#include <Eigen/Core>
#include <algorithm>
using namespace Eigen;
namespace KDL
{
inline double PYTHAG(double a,double b) {
double at,bt,ct;
at = fabs(a);
bt = fabs(b);
if (at > bt ) {
ct=bt/at;
return at*sqrt(1.0+ct*ct);
} else {
if (bt==0)
return 0.0;
else {
ct=at/bt;
return bt*sqrt(1.0+ct*ct);
}
}
}
inline double SIGN(double a,double b) {
return ((b) >= 0.0 ? fabs(a) : -fabs(a));
}
/**
* svd calculation of eigen matrices
*
* @param A matrix<double>(mxn)
* @param U matrix<double>(mxn)
* @param S vector<double> n
* @param V matrix<double>(nxn)
* @param tmp vector<double> n
* @param maxiter defaults to 150
*
* @return -2 if maxiter exceeded, 0 otherwise
*/
int svd_eigen_HH(const MatrixXd& A,MatrixXd& U,VectorXd& S,MatrixXd& V,VectorXd& tmp,int maxiter=150,double epsilon=1e-300);
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/rallNd.h | #ifndef RALLND_H
#define RALLND_H
#include "rall1d.h"
#include "rall1d_io.h"
#include "rall2d.h"
#include "rall2d_io.h"
/**
* The Rall1d class allows for a 24-line implementation of rall numbers
* generalized to the Nth derivative !
* The efficiency is not very good for high derivatives.
* This could be improved by also using Rall2d
*
template <int N>
class RallNd :
public Rall1d< RallNd<N-1>, RallNd<N-1>, double >
{
public:
RallNd() {}
RallNd(const Rall1d< RallNd<N-1>, RallNd<N-1>,double>& arg) :
Rall1d< RallNd<N-1>, RallNd<N-1>,double>(arg) {}
RallNd(double value,double d[]) {
this->t = RallNd<N-1>(value,d);
this->grad = RallNd<N-1>(d[0],&d[1]);
}
};
template <>
class RallNd<1> : public Rall1d<double> {
public:
RallNd() {}
RallNd(const Rall1d<double>& arg) :
Rall1d<double,double,double>(arg) {}
RallNd(double value,double d[]) {
t = value;
grad = d[0];
}
};
*/
/**
* to be checked..
*/
/**
* Als je tot 3de orde een efficiente berekening kan doen,
* dan kan je tot een willekeurige orde alles efficient berekenen
* 0 1 2 3
* ==> 1 2 3 4
* ==> 3 4 5 6
* 4 5 6 7
*
* de aangeduide berekeningen zijn niet noodzakelijk, en er is dan niets
* verniet berekend in de recursieve implementatie.
* of met 2de orde over 1ste order : kan ook efficient :
* 0 1
* ==>1 2
* 2 3
*/
// N>2:
template <int N>
class RallNd :
public Rall2d< RallNd<N-2>, RallNd<N-2>, double >
{
public:
RallNd() {}
RallNd(const Rall2d< RallNd<N-2>, RallNd<N-2>,double>& arg) :
Rall2d< RallNd<N-2>, RallNd<N-2>,double>(arg) {}
RallNd(double value,double d[]) {
this->t = RallNd<N-2>(value,d); // 0 1 2
this->d = RallNd<N-2>(d[0],&d[1]); // 1 2 3 iseigenlijk niet nodig
this->dd = RallNd<N-2>(d[1],&d[2]); // 2 3 4
}
};
template <>
class RallNd<2> : public Rall2d<double> {
public:
RallNd() {}* (dwz. met evenveel numerieke operaties als een
RallNd(const Rall2d<double>& arg) :
Rall2d<double>(arg) {}
RallNd(double value,double d[]) {
t = value;
d = d[0];
dd= d[1];
}
};
template <>
class RallNd<1> : public Rall1d<double> {
public:
RallNd() {}
RallNd(const Rall1d<double>& arg) :
Rall1d<double>(arg) {}
RallNd(double value,double d[]) {
t = value;
grad = d[0];
}
};
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/rall2d_io.h | /*****************************************************************************
* \file
* provides I/O operations on Rall1d
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: rall2d_io.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef Rall2d_IO_H
#define Rall2d_IO_H
#include "utility_io.h"
#include "rall2d.h"
namespace KDL {
template <class T,class V,class S>
std::ostream& operator << (std::ostream& os,const Rall2d<T,V,S>& r)
{
os << "Rall2d(" << r.t <<"," << r.d <<","<<r.dd<<")";
return os;
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/utility_io.cxx | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: utility_io.cpp,v 1.1.1.1.2.4 2003/06/26 15:23:59 psoetens Exp $
* $Name: $
* \todo
* make IO routines more robust against the differences between DOS/UNIX end-of-line style.
****************************************************************************/
#include "utility_io.h"
#include "error.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
namespace KDL {
//
// _functions are private functions
//
void _check_istream(std::istream& is)
{
if ((!is.good())&&(is.eof()) )
{
throw Error_BasicIO_File();
}
}
// Eats until the end of the line
int _EatUntilEndOfLine( std::istream& is, int* countp=NULL) {
int ch;
int count;
count = 0;
do {
ch = is.get();
count++;
_check_istream(is);
} while (ch!='\n');
if (countp!=NULL) *countp = count;
return ch;
}
// Eats until the end of the comment
int _EatUntilEndOfComment( std::istream& is, int* countp=NULL) {
int ch;
int count;
count = 0;
int prevch;
ch = 0;
do {
prevch = ch;
ch = is.get();
count++;
_check_istream(is);
if ((prevch=='*')&&(ch=='/')) {
break;
}
} while (true);
if (countp!=NULL) *countp = count;
ch = is.get();
return ch;
}
// Eats space-like characters and comments
// possibly returns the number of space-like characters eaten.
int _EatSpace( std::istream& is,int* countp=NULL) {
int ch;
int count;
count=-1;
do {
_check_istream(is);
ch = is.get();
count++;
if (ch == '#') {
ch = _EatUntilEndOfLine(is,&count);
}
if (ch == '/') {
ch = is.get();
if (ch == '/') {
ch = _EatUntilEndOfLine(is,&count);
} else if (ch == '*') {
ch = _EatUntilEndOfComment(is,&count);
} else {
is.putback(ch);
ch = '/';
}
}
} while ((ch==' ')||(ch=='\n')||(ch=='\t'));
if (countp!=NULL) *countp = count;
return ch;
}
// Eats whites, returns, tabs and the delim character
// Checks wether delim char. is encountered.
void Eat( std::istream& is, int delim )
{
int ch;
ch=_EatSpace(is);
if (ch != delim) {
throw Error_BasicIO_Exp_Delim();
}
ch=_EatSpace(is);
is.putback(ch);
}
// Eats whites, returns, tabs and the delim character
// Checks wether delim char. is encountered.
// EatEnd does not eat all space-like char's at the end.
void EatEnd( std::istream& is, int delim )
{
int ch;
ch=_EatSpace(is);
if (ch != delim) {
throw Error_BasicIO_Exp_Delim();
}
}
// For each space in descript, this routine eats whites,tabs, and newlines (at least one)
// There should be no consecutive spaces in the description.
// for each letter in descript, its reads the corresponding letter in the output
// the routine is case insensitive.
// Simple routine, enough for our purposes.
// works with ASCII chars
inline char Upper(char ch)
{
/*if (('a'<=ch)&&(ch<='z'))
return (ch-'a'+'A');
else
return ch;
*/
return toupper(ch);
}
void Eat(std::istream& is,const char* descript)
{
// eats whites before word
char ch;
char chdescr;
ch=_EatSpace(is);
is.putback(ch);
const char* p;
p = descript;
while ((*p)!=0) {
chdescr = (char)Upper(*p);
if (chdescr==' ') {
int count=0;
ch=_EatSpace(is,&count);
is.putback(ch);
if (count==0) {
throw Error_BasicIO_Not_A_Space();
}
} else {
ch=(char)is.get();
if (chdescr!=Upper(ch)) {
throw Error_BasicIO_Unexpected();
}
}
p++;
}
}
void EatWord(std::istream& is,const char* delim,char* storage,int maxsize)
{
int ch;
char* p;
int size;
// eat white before word
ch=_EatSpace(is);
p = storage;
size=0;
int count = 0;
while ((count==0)&&(strchr(delim,ch)==NULL)) {
*p = (char) toupper(ch);
++p;
if (size==maxsize) {
throw Error_BasicIO_ToBig();
}
_check_istream(is);
++size;
//ch = is.get();
ch =_EatSpace(is,&count);
}
*p=0;
is.putback(ch);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_Macie.hpp | // Copyright (C) 2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//implementation of svd according to (Maciejewski and Klein,1989)
//and (Braun, Ulrey, Maciejewski and Siegel,2002)
/**
* \file svd_eigen_Macie.hpp
* provides Maciejewski's implementation for SVD.
*/
#ifndef SVD_BOOST_MACIE
#define SVD_BOOST_MACIE
#include <Eigen/Core>
using namespace Eigen;
namespace KDL
{
/**
* svd_eigen_Macie provides Maciejewski implementation for SVD.
*
* computes the singular value decomposition of a matrix A, such that
* A=U*Sm*V
*
* (Maciejewski and Klein,1989) and (Braun, Ulrey, Maciejewski and Siegel,2002)
*
* \param A [INPUT] is an \f$m \times n\f$-matrix, where \f$ m \geq n \f$.
* \param S [OUTPUT] is an \f$n\f$-vector, representing the diagonal elements of the diagonal matrix Sm.
* \param U [INPUT/OUTPUT] is an \f$m \times m\f$ orthonormal matrix.
* \param V [INPUT/OUTPUT] is an \f$n \times n\f$ orthonormal matrix.
* \param B [TEMPORARY] is an \f$m \times n\f$ matrix used for temporary storage.
* \param tempi [TEMPORARY] is an \f$m\f$ vector used for temporary storage.
* \param thresshold [INPUT] Thresshold to determine orthogonality.
* \param toggle [INPUT] toggle this boolean variable on each call of this routine.
* \return number of sweeps.
*/
int svd_eigen_Macie(const MatrixXd& A,MatrixXd& U,VectorXd& S, MatrixXd& V,
MatrixXd& B, VectorXd& tempi,
double treshold,bool toggle)
{
bool rotate = true;
unsigned int sweeps=0;
unsigned int rotations=0;
if(toggle){
//Calculate B from new A and previous V
B=A.lazyProduct(V);
while(rotate){
rotate=false;
rotations=0;
//Perform rotations between columns of B
for(unsigned int i=0;i<B.cols();i++){
for(unsigned int j=i+1;j<B.cols();j++){
//calculate plane rotation
double p = B.col(i).dot(B.col(j));
double qi =B.col(i).dot(B.col(i));
double qj = B.col(j).dot(B.col(j));
double q=qi-qj;
double alpha = pow(p,2.0)/(qi*qj);
//if columns are orthogonal with precision
//treshold, don't perform rotation and continue
if(alpha<treshold)
continue;
rotations++;
double c = sqrt(4*pow(p,2.0)+pow(q,2.0));
double cos,sin;
if(q>=0){
cos=sqrt((c+q)/(2*c));
sin=p/(c*cos);
}else{
if(p<0)
sin=-sqrt((c-q)/(2*c));
else
sin=sqrt((c-q)/(2*c));
cos=p/(c*sin);
}
//Apply plane rotation to columns of B
tempi = cos*B.col(i) + sin*B.col(j);
B.col(j) = - sin*B.col(i) + cos*B.col(j);
B.col(i) = tempi;
//Apply plane rotation to columns of V
tempi.head(V.rows()) = cos*V.col(i) + sin*V.col(j);
V.col(j) = - sin*V.col(i) + cos*V.col(j);
V.col(i) = tempi.head(V.rows());
rotate=true;
}
}
//Only calculate new U and S if there were any rotations
if(rotations!=0){
for(unsigned int i=0;i<U.rows();i++) {
if(i<B.cols()){
double si=sqrt(B.col(i).dot(B.col(i)));
if(si==0)
U.col(i) = B.col(i);
else
U.col(i) = B.col(i)/si;
S(i)=si;
}
else
U.col(i) = 0*tempi;
}
sweeps++;
}
}
return sweeps;
}else{
//Calculate B from new A and previous U'
B = U.transpose().lazyProduct(A);
while(rotate){
rotate=false;
rotations=0;
//Perform rotations between rows of B
for(unsigned int i=0;i<B.cols();i++){
for(unsigned int j=i+1;j<B.cols();j++){
//calculate plane rotation
double p = B.row(i).dot(B.row(j));
double qi = B.row(i).dot(B.row(i));
double qj = B.row(j).dot(B.row(j));
double q=qi-qj;
double alpha = pow(p,2.0)/(qi*qj);
//if columns are orthogonal with precision
//treshold, don't perform rotation and
//continue
if(alpha<treshold)
continue;
rotations++;
double c = sqrt(4*pow(p,2.0)+pow(q,2.0));
double cos,sin;
if(q>=0){
cos=sqrt((c+q)/(2*c));
sin=p/(c*cos);
}else{
if(p<0)
sin=-sqrt((c-q)/(2*c));
else
sin=sqrt((c-q)/(2*c));
cos=p/(c*sin);
}
//Apply plane rotation to rows of B
tempi.head(B.cols()) = cos*B.row(i) + sin*B.row(j);
B.row(j) = - sin*B.row(i) + cos*B.row(j);
B.row(i) = tempi.head(B.cols());
//Apply plane rotation to rows of U
tempi.head(U.rows()) = cos*U.col(i) + sin*U.col(j);
U.col(j) = - sin*U.col(i) + cos*U.col(j);
U.col(i) = tempi.head(U.rows());
rotate=true;
}
}
//Only calculate new U and S if there were any rotations
if(rotations!=0){
for(unsigned int i=0;i<V.rows();i++) {
double si=sqrt(B.row(i).dot(B.row(i)));
if(si==0)
V.col(i) = B.row(i);
else
V.col(i) = B.row(i)/si;
S(i)=si;
}
sweeps++;
}
}
return sweeps;
}
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/utility.h | /*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: utility.h,v 1.1.1.1.2.4 2003/07/18 14:58:36 psoetens Exp $
* $Name: $
* \file
* Included by most lrl-files to provide some general
* functions and macro definitions.
*
* \par history
* - changed layout of the comments to accomodate doxygen
*/
#ifndef KDL_UTILITY_H
#define KDL_UTILITY_H
#include "kdl-config.h"
#include <cstdlib>
#include <cassert>
#include <cmath>
/////////////////////////////////////////////////////////////
// configurable options for the frames library.
#ifdef KDL_INLINE
#ifdef _MSC_VER
// Microsoft Visual C
#define IMETHOD __forceinline
#else
// Some other compiler, e.g. gcc
#define IMETHOD inline
#endif
#else
#define IMETHOD
#endif
//! turn on or off frames bounds checking. If turned on, assert() can still
//! be turned off with -DNDEBUG.
#ifdef KDL_INDEX_CHECK
#define FRAMES_CHECKI(a) assert(a)
#else
#define FRAMES_CHECKI(a)
#endif
namespace KDL {
#ifdef __GNUC__
// so that sin,cos can be overloaded and complete
// resolution of overloaded functions work.
using ::sin;
using ::cos;
using ::exp;
using ::log;
using ::sin;
using ::cos;
using ::tan;
using ::sinh;
using ::cosh;
using ::pow;
using ::sqrt;
using ::atan;
using ::hypot;
using ::asin;
using ::acos;
using ::tanh;
using ::atan2;
#endif
#ifndef __GNUC__
//only real solution : get Rall1d and varia out of namespaces.
#pragma warning (disable:4786)
inline double sin(double a) {
return ::sin(a);
}
inline double cos(double a) {
return ::cos(a);
}
inline double exp(double a) {
return ::exp(a);
}
inline double log(double a) {
return ::log(a);
}
inline double tan(double a) {
return ::tan(a);
}
inline double cosh(double a) {
return ::cosh(a);
}
inline double sinh(double a) {
return ::sinh(a);
}
inline double sqrt(double a) {
return ::sqrt(a);
}
inline double atan(double a) {
return ::atan(a);
}
inline double acos(double a) {
return ::acos(a);
}
inline double asin(double a) {
return ::asin(a);
}
inline double tanh(double a) {
return ::tanh(a);
}
inline double pow(double a,double b) {
return ::pow(a,b);
}
inline double atan2(double a,double b) {
return ::atan2(a,b);
}
#endif
/**
* Auxiliary class for argument types (Trait-template class )
*
* Is used to pass doubles by value, and arbitrary objects by const reference.
* This is TWICE as fast (2 x less memory access) and avoids bugs in VC6++ concerning
* the assignment of the result of intrinsic functions to const double&-typed variables,
* and optimization on.
*/
template <class T>
class TI
{
public:
typedef const T& Arg; //!< Arg is used for passing the element to a function.
};
template <>
class TI<double> {
public:
typedef double Arg;
};
template <>
class TI<int> {
public:
typedef int Arg;
};
/**
* /note linkage
* Something fishy about the difference between C++ and C
* in C++ const values default to INTERNAL linkage, in C they default
* to EXTERNAL linkage. Here the constants should have EXTERNAL linkage
* because they, for at least some of them, can be changed by the user.
* If you want to explicitly declare internal linkage, use "static".
*/
//!
extern int STREAMBUFFERSIZE;
//! maximal length of a file name
extern int MAXLENFILENAME;
//! the value of pi
extern const double PI;
//! the value pi/180
extern const double deg2rad;
//! the value 180/pi
extern const double rad2deg;
//! default precision while comparing with Equal(..,..) functions. Initialized at 0.0000001.
extern double epsilon;
//! the number of derivatives used in the RN-... objects.
extern int VSIZE;
#ifndef _MFC_VER
#undef max
inline double max(double a,double b) {
if (b<a)
return a;
else
return b;
}
#undef min
inline double min(double a,double b) {
if (b<a)
return b;
else
return a;
}
#endif
#ifdef _MSC_VER
//#pragma inline_depth( 255 )
//#pragma inline_recursion( on )
#define INLINE __forceinline
//#define INLINE inline
#else
#define INLINE inline
#endif
inline double LinComb(double alfa,double a,
double beta,double b ) {
return alfa*a+beta*b;
}
inline void LinCombR(double alfa,double a,
double beta,double b,double& result ) {
result=alfa*a+beta*b;
}
//! to uniformly set double, RNDouble,Vector,... objects to zero in template-classes
inline void SetToZero(double& arg) {
arg=0;
}
//! to uniformly set double, RNDouble,Vector,... objects to the identity element in template-classes
inline void SetToIdentity(double& arg) {
arg=1;
}
inline double sign(double arg) {
return (arg<0)?(-1):(1);
}
inline double sqr(double arg) { return arg*arg;}
inline double Norm(double arg) {
return fabs( (double)arg );
}
#if defined __WIN32__ && !defined __GNUC__
inline double hypot(double y,double x) { return ::_hypot(y,x);}
inline double abs(double x) { return ::fabs(x);}
#endif
// compares whether 2 doubles are equal in an eps-interval.
// Does not check whether a or b represents numbers
// On VC6, if a/b is -INF, it returns false;
inline bool Equal(double a,double b,double eps=epsilon)
{
double tmp=(a-b);
return ((eps>tmp)&& (tmp>-eps) );
}
inline void random(double& a) {
a = 1.98*rand()/(double)RAND_MAX -0.99;
}
inline void posrandom(double& a) {
a = 0.001+0.99*rand()/(double)RAND_MAX;
}
inline double diff(double a,double b,double dt) {
return (b-a)/dt;
}
//inline float diff(float a,float b,double dt) {
//return (b-a)/dt;
//}
inline double addDelta(double a,double da,double dt) {
return a+da*dt;
}
//inline float addDelta(float a,float da,double dt) {
// return a+da*dt;
//}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/header.txt | /***************************************************************************
XXXXXX - description
-------------------------
begin : June 2006
copyright : (C) 2006 Erwin Aertbelien
email : firstname.lastname@mech.kuleuven.ac.be
History (only major changes)( AUTHOR-Description ) :
***************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/rall1d_io.h | /*****************************************************************************
* \file
* provides I/O operations on Rall1d
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: rall1d_io.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef Rall_IO_H
#define Rall_IO_H
#include "utility_io.h"
#include "rall1d.h"
namespace KDL {
template <class T,class V,class S>
inline std::ostream& operator << (std::ostream& os,const Rall1d<T,V,S>& r)
{
os << "Rall1d(" << r.t <<"," << r.grad <<")";
return os;
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/rall2d.h |
/*****************************************************************************
* \file
* class for automatic differentiation on scalar values and 1st
* derivatives and 2nd derivative.
*
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* ORO_Geometry V0.2
*
* \par Note
* VC6++ contains a bug, concerning the use of inlined friend functions
* in combination with namespaces. So, try to avoid inlined friend
* functions !
*
* \par History
* - $log$
*
* \par Release
* $Id: rall2d.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $
* $Name: $
****************************************************************************/
#ifndef Rall2D_H
#define Rall2D_H
#include <math.h>
#include <assert.h>
#include "utility.h"
namespace KDL {
/**
* Rall2d contains a value, and its gradient and its 2nd derivative, and defines an algebraic
* structure on this pair.
* This template class has 3 template parameters :
* - T contains the type of the value.
* - V contains the type of the gradient (can be a vector-like type).
* - S defines a scalar type that can operate on Rall1d. This is the type that
* is used to give back values of Norm() etc.
*
* S is usefull when you recurse a Rall1d object into itself to create a 2nd, 3th, 4th,..
* derivatives. (e.g. Rall1d< Rall1d<double>, Rall1d<double>, double> ).
*
* S is always passed by value.
*
* \par Class Type
* Concrete implementation
*/
template <class T,class V=T,class S=T>
class Rall2d
{
public :
T t; //!< value
V d; //!< 1st derivative
V dd; //!< 2nd derivative
public :
// = Constructors
INLINE Rall2d() {}
explicit INLINE Rall2d(typename TI<T>::Arg c)
{t=c;SetToZero(d);SetToZero(dd);}
INLINE Rall2d(typename TI<T>::Arg tn,const V& afg):t(tn),d(afg) {SetToZero(dd);}
INLINE Rall2d(typename TI<T>::Arg tn,const V& afg,const V& afg2):t(tn),d(afg),dd(afg2) {}
// = Copy Constructor
INLINE Rall2d(const Rall2d<T,V,S>& r):t(r.t),d(r.d),dd(r.dd) {}
//if one defines this constructor, it's better optimized then the
//automatically generated one ( that one set's up a loop to copy
// word by word.
// = Member functions to access internal structures :
INLINE T& Value() {
return t;
}
INLINE V& D() {
return d;
}
INLINE V& DD() {
return dd;
}
INLINE static Rall2d<T,V,S> Zero() {
Rall2d<T,V,S> tmp;
SetToZero(tmp);
return tmp;
}
INLINE static Rall2d<T,V,S> Identity() {
Rall2d<T,V,S> tmp;
SetToIdentity(tmp);
return tmp;
}
// = assignment operators
INLINE Rall2d<T,V,S>& operator =(S c)
{t=c;SetToZero(d);SetToZero(dd);return *this;}
INLINE Rall2d<T,V,S>& operator =(const Rall2d<T,V,S>& r)
{t=r.t;d=r.d;dd=r.dd;return *this;}
INLINE Rall2d<T,V,S>& operator /=(const Rall2d<T,V,S>& rhs)
{
t /= rhs.t;
d = (d-t*rhs.d)/rhs.t;
dd= (dd - S(2)*d*rhs.d-t*rhs.dd)/rhs.t;
return *this;
}
INLINE Rall2d<T,V,S>& operator *=(const Rall2d<T,V,S>& rhs)
{
t *= rhs.t;
d = (d*rhs.t+t*rhs.d);
dd = (dd*rhs.t+S(2)*d*rhs.d+t*rhs.dd);
return *this;
}
INLINE Rall2d<T,V,S>& operator +=(const Rall2d<T,V,S>& rhs)
{
t +=rhs.t;
d +=rhs.d;
dd+=rhs.dd;
return *this;
}
INLINE Rall2d<T,V,S>& operator -=(const Rall2d<T,V,S>& rhs)
{
t -= rhs.t;
d -= rhs.d;
dd -= rhs.dd;
return *this;
}
INLINE Rall2d<T,V,S>& operator /=(S rhs)
{
t /= rhs;
d /= rhs;
dd /= rhs;
return *this;
}
INLINE Rall2d<T,V,S>& operator *=(S rhs)
{
t *= rhs;
d *= rhs;
dd *= rhs;
return *this;
}
INLINE Rall2d<T,V,S>& operator -=(S rhs)
{
t -= rhs;
return *this;
}
INLINE Rall2d<T,V,S>& operator +=(S rhs)
{
t += rhs;
return *this;
}
// = Operators between Rall2d objects
/*
friend INLINE Rall2d<T,V,S> operator /(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs);
friend INLINE Rall2d<T,V,S> operator *(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs);
friend INLINE Rall2d<T,V,S> operator +(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs);
friend INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs);
friend INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> operator *(S s,const Rall2d<T,V,S>& v);
friend INLINE Rall2d<T,V,S> operator *(const Rall2d<T,V,S>& v,S s);
friend INLINE Rall2d<T,V,S> operator +(S s,const Rall2d<T,V,S>& v);
friend INLINE Rall2d<T,V,S> operator +(const Rall2d<T,V,S>& v,S s);
friend INLINE Rall2d<T,V,S> operator -(S s,const Rall2d<T,V,S>& v);
friend INLINE INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& v,S s);
friend INLINE Rall2d<T,V,S> operator /(S s,const Rall2d<T,V,S>& v);
friend INLINE Rall2d<T,V,S> operator /(const Rall2d<T,V,S>& v,S s);
// = Mathematical functions that operate on Rall2d objects
friend INLINE Rall2d<T,V,S> exp(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> log(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> sin(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> cos(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> tan(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> sinh(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> cosh(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> tanh(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> sqr(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> pow(const Rall2d<T,V,S>& arg,double m) ;
friend INLINE Rall2d<T,V,S> sqrt(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> asin(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> acos(const Rall2d<T,V,S>& arg);
friend INLINE Rall2d<T,V,S> atan(const Rall2d<T,V,S>& x);
friend INLINE Rall2d<T,V,S> atan2(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x);
friend INLINE Rall2d<T,V,S> abs(const Rall2d<T,V,S>& x);
friend INLINE Rall2d<T,V,S> hypot(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x);
// returns sqrt(y*y+x*x), but is optimized for accuracy and speed.
friend INLINE S Norm(const Rall2d<T,V,S>& value) ;
// returns Norm( value.Value() ).
// = Some utility functions to improve performance
// (should also be declared on primitive types to improve uniformity
friend INLINE Rall2d<T,V,S> LinComb(S alfa,const Rall2d<T,V,S>& a,
TI<T>::Arg beta,const Rall2d<T,V,S>& b );
friend INLINE void LinCombR(S alfa,const Rall2d<T,V,S>& a,
TI<T>::Arg beta,const Rall2d<T,V,S>& b,Rall2d<T,V,S>& result );
// = Setting value of a Rall2d object to 0 or 1
friend INLINE void SetToZero(Rall2d<T,V,S>& value);
friend INLINE void SetToOne(Rall2d<T,V,S>& value);
// = Equality in an eps-interval
friend INLINE bool Equal(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x,double eps);
*/
};
// = Operators between Rall2d objects
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator /(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs)
{
Rall2d<T,V,S> tmp;
tmp.t = lhs.t/rhs.t;
tmp.d = (lhs.d-tmp.t*rhs.d)/rhs.t;
tmp.dd= (lhs.dd-S(2)*tmp.d*rhs.d-tmp.t*rhs.dd)/rhs.t;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator *(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs)
{
Rall2d<T,V,S> tmp;
tmp.t = lhs.t*rhs.t;
tmp.d = (lhs.d*rhs.t+lhs.t*rhs.d);
tmp.dd = (lhs.dd*rhs.t+S(2)*lhs.d*rhs.d+lhs.t*rhs.dd);
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator +(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs)
{
return Rall2d<T,V,S>(lhs.t+rhs.t,lhs.d+rhs.d,lhs.dd+rhs.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& lhs,const Rall2d<T,V,S>& rhs)
{
return Rall2d<T,V,S>(lhs.t-rhs.t,lhs.d-rhs.d,lhs.dd-rhs.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& arg)
{
return Rall2d<T,V,S>(-arg.t,-arg.d,-arg.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator *(S s,const Rall2d<T,V,S>& v)
{
return Rall2d<T,V,S>(s*v.t,s*v.d,s*v.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator *(const Rall2d<T,V,S>& v,S s)
{
return Rall2d<T,V,S>(v.t*s,v.d*s,v.dd*s);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator +(S s,const Rall2d<T,V,S>& v)
{
return Rall2d<T,V,S>(s+v.t,v.d,v.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator +(const Rall2d<T,V,S>& v,S s)
{
return Rall2d<T,V,S>(v.t+s,v.d,v.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator -(S s,const Rall2d<T,V,S>& v)
{
return Rall2d<T,V,S>(s-v.t,-v.d,-v.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator -(const Rall2d<T,V,S>& v,S s)
{
return Rall2d<T,V,S>(v.t-s,v.d,v.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator /(S s,const Rall2d<T,V,S>& rhs)
{
Rall2d<T,V,S> tmp;
tmp.t = s/rhs.t;
tmp.d = (-tmp.t*rhs.d)/rhs.t;
tmp.dd= (-S(2)*tmp.d*rhs.d-tmp.t*rhs.dd)/rhs.t;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> operator /(const Rall2d<T,V,S>& v,S s)
{
return Rall2d<T,V,S>(v.t/s,v.d/s,v.dd/s);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> exp(const Rall2d<T,V,S>& arg)
{
Rall2d<T,V,S> tmp;
tmp.t = exp(arg.t);
tmp.d = tmp.t*arg.d;
tmp.dd = tmp.d*arg.d+tmp.t*arg.dd;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> log(const Rall2d<T,V,S>& arg)
{
Rall2d<T,V,S> tmp;
tmp.t = log(arg.t);
tmp.d = arg.d/arg.t;
tmp.dd = (arg.dd-tmp.d*arg.d)/arg.t;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> sin(const Rall2d<T,V,S>& arg)
{
T v1 = sin(arg.t);
T v2 = cos(arg.t);
return Rall2d<T,V,S>(v1,v2*arg.d,v2*arg.dd - (v1*arg.d)*arg.d );
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> cos(const Rall2d<T,V,S>& arg)
{
T v1 = cos(arg.t);
T v2 = -sin(arg.t);
return Rall2d<T,V,S>(v1,v2*arg.d, v2*arg.dd - (v1*arg.d)*arg.d);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> tan(const Rall2d<T,V,S>& arg)
{
T v1 = tan(arg.t);
T v2 = S(1)+sqr(v1);
return Rall2d<T,V,S>(v1,v2*arg.d, v2*(arg.dd+(S(2)*v1*sqr(arg.d))));
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> sinh(const Rall2d<T,V,S>& arg)
{
T v1 = sinh(arg.t);
T v2 = cosh(arg.t);
return Rall2d<T,V,S>(v1,v2*arg.d,v2*arg.dd + (v1*arg.d)*arg.d );
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> cosh(const Rall2d<T,V,S>& arg)
{
T v1 = cosh(arg.t);
T v2 = sinh(arg.t);
return Rall2d<T,V,S>(v1,v2*arg.d,v2*arg.dd + (v1*arg.d)*arg.d );
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> tanh(const Rall2d<T,V,S>& arg)
{
T v1 = tanh(arg.t);
T v2 = S(1)-sqr(v1);
return Rall2d<T,V,S>(v1,v2*arg.d, v2*(arg.dd-(S(2)*v1*sqr(arg.d))));
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> sqr(const Rall2d<T,V,S>& arg)
{
return Rall2d<T,V,S>(arg.t*arg.t,
(S(2)*arg.t)*arg.d,
S(2)*(sqr(arg.d)+arg.t*arg.dd)
);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> pow(const Rall2d<T,V,S>& arg,double m)
{
Rall2d<T,V,S> tmp;
tmp.t = pow(arg.t,m);
T v2 = (m/arg.t)*tmp.t;
tmp.d = v2*arg.d;
tmp.dd = (S((m-1))/arg.t)*tmp.d*arg.d + v2*arg.dd;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> sqrt(const Rall2d<T,V,S>& arg)
{
/* By inversion of sqr(x) :*/
Rall2d<T,V,S> tmp;
tmp.t = sqrt(arg.t);
tmp.d = (S(0.5)/tmp.t)*arg.d;
tmp.dd = (S(0.5)*arg.dd-sqr(tmp.d))/tmp.t;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> asin(const Rall2d<T,V,S>& arg)
{
/* By inversion of sin(x) */
Rall2d<T,V,S> tmp;
tmp.t = asin(arg.t);
T v = cos(tmp.t);
tmp.d = arg.d/v;
tmp.dd = (arg.dd+arg.t*sqr(tmp.d))/v;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> acos(const Rall2d<T,V,S>& arg)
{
/* By inversion of cos(x) */
Rall2d<T,V,S> tmp;
tmp.t = acos(arg.t);
T v = -sin(tmp.t);
tmp.d = arg.d/v;
tmp.dd = (arg.dd+arg.t*sqr(tmp.d))/v;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> atan(const Rall2d<T,V,S>& x)
{
/* By inversion of tan(x) */
Rall2d<T,V,S> tmp;
tmp.t = atan(x.t);
T v = S(1)+sqr(x.t);
tmp.d = x.d/v;
tmp.dd = x.dd/v-(S(2)*x.t)*sqr(tmp.d);
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> atan2(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x)
{
Rall2d<T,V,S> tmp;
tmp.t = atan2(y.t,x.t);
T v = sqr(y.t)+sqr(x.t);
tmp.d = (x.t*y.d-x.d*y.t)/v;
tmp.dd = ( x.t*y.dd-x.dd*y.t-S(2)*(x.t*x.d+y.t*y.d)*tmp.d ) / v;
return tmp;
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> abs(const Rall2d<T,V,S>& x)
{
T v(Sign(x));
return Rall2d<T,V,S>(v*x,v*x.d,v*x.dd);
}
template <class T,class V,class S>
INLINE Rall2d<T,V,S> hypot(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x)
{
Rall2d<T,V,S> tmp;
tmp.t = hypot(y.t,x.t);
tmp.d = (x.t*x.d+y.t*y.d)/tmp.t;
tmp.dd = (sqr(x.d)+x.t*x.dd+sqr(y.d)+y.t*y.dd-sqr(tmp.d))/tmp.t;
return tmp;
}
// returns sqrt(y*y+x*x), but is optimized for accuracy and speed.
template <class T,class V,class S>
INLINE S Norm(const Rall2d<T,V,S>& value)
{
return Norm(value.t);
}
// returns Norm( value.Value() ).
// (should also be declared on primitive types to improve uniformity
template <class T,class V,class S>
INLINE Rall2d<T,V,S> LinComb(S alfa,const Rall2d<T,V,S>& a,
const T& beta,const Rall2d<T,V,S>& b ) {
return Rall2d<T,V,S>(
LinComb(alfa,a.t,beta,b.t),
LinComb(alfa,a.d,beta,b.d),
LinComb(alfa,a.dd,beta,b.dd)
);
}
template <class T,class V,class S>
INLINE void LinCombR(S alfa,const Rall2d<T,V,S>& a,
const T& beta,const Rall2d<T,V,S>& b,Rall2d<T,V,S>& result ) {
LinCombR(alfa, a.t, beta, b.t, result.t);
LinCombR(alfa, a.d, beta, b.d, result.d);
LinCombR(alfa, a.dd, beta, b.dd, result.dd);
}
template <class T,class V,class S>
INLINE void SetToZero(Rall2d<T,V,S>& value)
{
SetToZero(value.t);
SetToZero(value.d);
SetToZero(value.dd);
}
template <class T,class V,class S>
INLINE void SetToIdentity(Rall2d<T,V,S>& value)
{
SetToZero(value.d);
SetToIdentity(value.t);
SetToZero(value.dd);
}
template <class T,class V,class S>
INLINE bool Equal(const Rall2d<T,V,S>& y,const Rall2d<T,V,S>& x,double eps=epsilon)
{
return (Equal(x.t,y.t,eps)&&
Equal(x.d,y.d,eps)&&
Equal(x.dd,y.dd,eps)
);
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src | apollo_public_repos/apollo-platform/ros/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_HH.hpp | // Copyright (C) 2007 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef KDL_SVD_HH_HPP
#define KDL_SVD_HH_HPP
#include "../jacobian.hpp"
#include "../jntarray.hpp"
#include <vector>
namespace KDL
{
class SVD_HH
{
public:
SVD_HH(const Jacobian& jac);
~SVD_HH();
int calculate(const Jacobian& jac,std::vector<JntArray>& U,
JntArray& w,std::vector<JntArray>& v,int maxiter);
private:
JntArray tmp;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rosmaster)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
if(CATKIN_ENABLE_TESTING)
catkin_add_nosetests(test)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/package.xml | <package>
<name>rosmaster</name>
<version>1.11.21</version>
<description>
ROS <a href="http://ros.org/wiki/Master">Master</a> implementation.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/rosmaster</url>
<author>Ken Conley</author>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<run_depend>rosgraph</run_depend>
<export>
<rosdoc config="rosdoc.yaml"/>
<architecture_independent/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/rosdoc.yaml | - builder: epydoc
config: epydoc.config
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/setup.py | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['rosmaster'],
package_dir={'': 'src'},
scripts=['scripts/rosmaster'],
requires=['roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosmaster/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rosmaster-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rosmaster
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
1.11.20 (2016-06-27)
--------------------
1.11.19 (2016-04-18)
--------------------
1.11.18 (2016-03-17)
--------------------
1.11.17 (2016-03-11)
--------------------
1.11.16 (2015-11-09)
--------------------
* add `-w` and `-t` options (`#687 <https://github.com/ros/ros_comm/pull/687>`_)
1.11.15 (2015-10-13)
--------------------
1.11.14 (2015-09-19)
--------------------
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
1.11.10 (2014-12-22)
--------------------
* fix closing sockets properly on node shutdown (`#495 <https://github.com/ros/ros_comm/issues/495>`_)
1.11.9 (2014-08-18)
-------------------
1.11.8 (2014-08-04)
-------------------
1.11.7 (2014-07-18)
-------------------
1.11.6 (2014-07-10)
-------------------
1.11.5 (2014-06-24)
-------------------
1.11.4 (2014-06-16)
-------------------
* Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#427 <https://github.com/ros/ros_comm/issues/427>`_, `#429 <https://github.com/ros/ros_comm/issues/429>`_)
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_)
1.11.0 (2014-03-04)
-------------------
1.10.0 (2014-02-11)
-------------------
1.9.54 (2014-01-27)
-------------------
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
* check for CATKIN_ENABLE_TESTING to enable configure without tests
1.9.46 (2013-06-18)
-------------------
1.9.45 (2013-06-06)
-------------------
1.9.44 (2013-03-21)
-------------------
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
1.9.41 (2013-01-24)
-------------------
1.9.40 (2013-01-13)
-------------------
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/epydoc.config | [epydoc]
name: rosmaster
modules: rosmaster
inheritance: included
url: http://ros.org/wiki/rosmaster
frames: no
private: no
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/test/test_rosmaster_validators.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import unittest
import time
class TestRosmasterValidators(unittest.TestCase):
def test_ParameterInvalid(self):
# not really testing anything here other than typos
from rosmaster.validators import ParameterInvalid
self.assert_(isinstance(ParameterInvalid('param'), Exception))
def test_validators(self):
from rosmaster.validators import ParameterInvalid
from rosmaster.validators import non_empty
contextes = ['', '/', '/foo']
for context in contextes:
valid = ['foo', 1, [1]]
for v in valid:
non_empty('param-name')(v, context)
invalid = ['', 0, []]
for i in invalid:
try:
non_empty('param-name-foo')(i, context)
except ParameterInvalid as e:
self.assert_('param-name-foo' in str(e))
from rosmaster.validators import non_empty_str
valid = ['foo', 'f', u'f']
for v in valid:
non_empty_str('param-name')(v, context)
invalid = ['', 1, ['foo']]
for i in invalid:
try:
non_empty_str('param-name-bar')(i, context)
except ParameterInvalid as e:
self.assert_('param-name-bar' in str(e))
from rosmaster.validators import not_none
valid = ['foo', 'f', 1, False, 0, '']
for v in valid:
not_none('param-name')(v, context)
invalid = [None]
for i in invalid:
try:
not_none('param-name-charlie')(i, context)
except ParameterInvalid as e:
self.assert_('param-name-charlie' in str(e))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/test/test_rosmaster_registrations.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import unittest
import time
# mock of subscription tests
class ThreadPoolMock(object):
def queue_task(*args): pass
class TestRosmasterRegistrations(unittest.TestCase):
def test_NodeRef_services(self):
from rosmaster.registrations import NodeRef, Registrations
n = NodeRef('n1', 'http://localhost:1234')
# test services
n.add(Registrations.SERVICE, 'add_two_ints')
self.failIf(n.is_empty())
self.assert_('add_two_ints' in n.services)
self.assertEquals(['add_two_ints'], n.services)
n.add(Registrations.SERVICE, 'add_three_ints')
self.failIf(n.is_empty())
self.assert_('add_three_ints' in n.services)
self.assert_('add_two_ints' in n.services)
n.remove(Registrations.SERVICE, 'add_two_ints')
self.assert_('add_three_ints' in n.services)
self.assertEquals(['add_three_ints'], n.services)
self.failIf('add_two_ints' in n.services)
self.failIf(n.is_empty())
n.remove(Registrations.SERVICE, 'add_three_ints')
self.failIf('add_three_ints' in n.services)
self.failIf('add_two_ints' in n.services)
self.assertEquals([], n.services)
self.assert_(n.is_empty())
def test_NodeRef_subs(self):
from rosmaster.registrations import NodeRef, Registrations
n = NodeRef('n1', 'http://localhost:1234')
# test topic suscriptions
n.add(Registrations.TOPIC_SUBSCRIPTIONS, 'topic1')
self.failIf(n.is_empty())
self.assert_('topic1' in n.topic_subscriptions)
self.assertEquals(['topic1'], n.topic_subscriptions)
n.add(Registrations.TOPIC_SUBSCRIPTIONS, 'topic2')
self.failIf(n.is_empty())
self.assert_('topic2' in n.topic_subscriptions)
self.assert_('topic1' in n.topic_subscriptions)
n.remove(Registrations.TOPIC_SUBSCRIPTIONS, 'topic1')
self.assert_('topic2' in n.topic_subscriptions)
self.assertEquals(['topic2'], n.topic_subscriptions)
self.failIf('topic1' in n.topic_subscriptions)
self.failIf(n.is_empty())
n.remove(Registrations.TOPIC_SUBSCRIPTIONS, 'topic2')
self.failIf('topic2' in n.topic_subscriptions)
self.failIf('topic1' in n.topic_subscriptions)
self.assertEquals([], n.topic_subscriptions)
self.assert_(n.is_empty())
def test_NodeRef_pubs(self):
from rosmaster.registrations import NodeRef, Registrations
n = NodeRef('n1', 'http://localhost:1234')
# test topic publications
n.add(Registrations.TOPIC_PUBLICATIONS, 'topic1')
self.failIf(n.is_empty())
self.assert_('topic1' in n.topic_publications)
self.assertEquals(['topic1'], n.topic_publications)
n.add(Registrations.TOPIC_PUBLICATIONS, 'topic2')
self.failIf(n.is_empty())
self.assert_('topic2' in n.topic_publications)
self.assert_('topic1' in n.topic_publications)
n.remove(Registrations.TOPIC_PUBLICATIONS, 'topic1')
self.assert_('topic2' in n.topic_publications)
self.assertEquals(['topic2'], n.topic_publications)
self.failIf('topic1' in n.topic_publications)
self.failIf(n.is_empty())
n.remove(Registrations.TOPIC_PUBLICATIONS, 'topic2')
self.failIf('topic2' in n.topic_publications)
self.failIf('topic1' in n.topic_publications)
self.assertEquals([], n.topic_publications)
self.assert_(n.is_empty())
def test_NodeRef_base(self):
import rosmaster.exceptions
from rosmaster.registrations import NodeRef, Registrations
n = NodeRef('n1', 'http://localhost:1234')
self.assertEquals('http://localhost:1234', n.api)
self.assertEquals([], n.param_subscriptions)
self.assertEquals([], n.topic_subscriptions)
self.assertEquals([], n.topic_publications)
self.assertEquals([], n.services)
self.assert_(n.is_empty())
try:
n.add(12345, 'topic')
self.fail("should have failed with invalid type")
except rosmaster.exceptions.InternalException: pass
try:
n.remove(12345, 'topic')
self.fail("should have failed with invalid type")
except rosmaster.exceptions.InternalException: pass
n.add(Registrations.TOPIC_PUBLICATIONS, 'topic1')
n.add(Registrations.TOPIC_PUBLICATIONS, 'topic2')
n.add(Registrations.TOPIC_SUBSCRIPTIONS, 'topic2')
n.add(Registrations.TOPIC_SUBSCRIPTIONS, 'topic3')
n.add(Registrations.PARAM_SUBSCRIPTIONS, 'topic4')
n.add(Registrations.SERVICE, 'serv')
self.failIf(n.is_empty())
n.clear()
self.assert_(n.is_empty())
def test_NodeRef_param_subs(self):
from rosmaster.registrations import NodeRef, Registrations
n = NodeRef('n1', 'http://localhost:1234')
# test param suscriptions
n.add(Registrations.PARAM_SUBSCRIPTIONS, 'param1')
self.failIf(n.is_empty())
self.assert_('param1' in n.param_subscriptions)
self.assertEquals(['param1'], n.param_subscriptions)
n.add(Registrations.PARAM_SUBSCRIPTIONS, 'param2')
self.failIf(n.is_empty())
self.assert_('param2' in n.param_subscriptions)
self.assert_('param1' in n.param_subscriptions)
n.remove(Registrations.PARAM_SUBSCRIPTIONS, 'param1')
self.assert_('param2' in n.param_subscriptions)
self.assertEquals(['param2'], n.param_subscriptions)
self.failIf('param1' in n.param_subscriptions)
self.failIf(n.is_empty())
n.remove(Registrations.PARAM_SUBSCRIPTIONS, 'param2')
self.failIf('param2' in n.param_subscriptions)
self.failIf('param1' in n.param_subscriptions)
self.assertEquals([], n.param_subscriptions)
self.assert_(n.is_empty())
## subroutine of registration tests that test topic/param type Reg objects
## @param r Registrations: initialized registrations object to test
def _subtest_Registrations_basic(self, r):
#NOTE: no real difference between topic and param names, so tests are reusable
# - note that we've updated node1's API
r.register('topic1', 'node1', 'http://node1:5678')
self.assert_('topic1' in r) # test contains
self.assert_(r.has_key('topic1')) # test contains
self.assertEquals(['topic1'], [k for k in r.iterkeys()])
self.assertEquals(['http://node1:5678'], r.get_apis('topic1'))
self.assertEquals([('node1', 'http://node1:5678')], r['topic1'])
self.failIf(not r) #test nonzero
self.assertEquals(None, r.get_service_api('topic1')) #make sure no contamination
self.assertEquals([['topic1', ['node1']]], r.get_state())
r.register('topic1', 'node2', 'http://node2:5678')
self.assertEquals(['topic1'], [k for k in r.iterkeys()])
self.assertEquals(['topic1'], [k for k in r.iterkeys()])
self.assertEquals(2, len(r.get_apis('topic1')))
self.assert_('http://node1:5678' in r.get_apis('topic1'))
self.assert_('http://node2:5678' in r.get_apis('topic1'))
self.assertEquals(2, len(r['topic1']))
self.assert_(('node1', 'http://node1:5678') in r['topic1'], r['topic1'])
self.assert_(('node2', 'http://node2:5678') in r['topic1'])
self.assertEquals([['topic1', ['node1', 'node2']]], r.get_state())
# TODO: register second topic
r.register('topic2', 'node3', 'http://node3:5678')
self.assert_('topic2' in r) # test contains
self.assert_(r.has_key('topic2')) # test contains
self.assert_('topic1' in [k for k in r.iterkeys()])
self.assert_('topic2' in [k for k in r.iterkeys()])
self.assertEquals(['http://node3:5678'], r.get_apis('topic2'))
self.assertEquals([('node3', 'http://node3:5678')], r['topic2'])
self.failIf(not r) #test nonzero
self.assert_(['topic1', ['node1', 'node2']] in r.get_state(), r.get_state())
self.assert_(['topic2', ['node3']] in r.get_state(), r.get_state())
# Unregister
# - fail if node is not registered
code, _, val = r.unregister('topic1', 'node3', 'http://node3:5678')
self.assertEquals(0, val)
# - fail if topic is not registered by that node
code, _, val = r.unregister('topic2', 'node2', 'http://node2:5678')
self.assertEquals(0, val)
# - fail if URI does not match
code, _, val = r.unregister('topic2', 'node2', 'http://fakenode2:5678')
self.assertEquals(0, val)
# - unregister node2
code, _, val = r.unregister('topic1', 'node1', 'http://node1:5678')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.assert_('topic1' in r) # test contains
self.assert_(r.has_key('topic1'))
self.assert_('topic1' in [k for k in r.iterkeys()])
self.assert_('topic2' in [k for k in r.iterkeys()])
self.assertEquals(['http://node2:5678'], r.get_apis('topic1'))
self.assertEquals([('node2', 'http://node2:5678')], r['topic1'])
self.failIf(not r) #test nonzero
self.assert_(['topic1', ['node2']] in r.get_state())
self.assert_(['topic2', ['node3']] in r.get_state())
code, _, val = r.unregister('topic1', 'node2', 'http://node2:5678')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.failIf('topic1' in r) # test contains
self.failIf(r.has_key('topic1'))
self.assertEquals(['topic2'], [k for k in r.iterkeys()])
self.assertEquals([], r.get_apis('topic1'))
self.assertEquals([], r['topic1'])
self.failIf(not r) #test nonzero
self.assertEquals([['topic2', ['node3']]], r.get_state())
# clear out last reg
code, _, val = r.unregister('topic2', 'node3', 'http://node3:5678')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.failIf('topic2' in r) # test contains
self.assert_(not r)
self.assertEquals([], r.get_state())
def test_Registrations(self):
import rosmaster.exceptions
from rosmaster.registrations import Registrations
types = [Registrations.TOPIC_SUBSCRIPTIONS,
Registrations.TOPIC_PUBLICATIONS,
Registrations.SERVICE,
Registrations.PARAM_SUBSCRIPTIONS]
# test enums
self.assertEquals(4, len(set(types)))
try:
r = Registrations(-1)
self.fail("Registrations accepted invalid type")
except rosmaster.exceptions.InternalException: pass
for t in types:
r = Registrations(t)
self.assertEquals(t, r.type)
self.assert_(not r) #test nonzero
self.failIf('topic1' in r) #test contains
self.failIf(r.has_key('topic1')) #test has_key
self.failIf([k for k in r.iterkeys()]) #no keys
self.assertEquals(None, r.get_service_api('non-existent'))
# Test topic subs
r = Registrations(Registrations.TOPIC_SUBSCRIPTIONS)
self._subtest_Registrations_basic(r)
r = Registrations(Registrations.TOPIC_PUBLICATIONS)
self._subtest_Registrations_basic(r)
r = Registrations(Registrations.PARAM_SUBSCRIPTIONS)
self._subtest_Registrations_basic(r)
r = Registrations(Registrations.SERVICE)
self._subtest_Registrations_services(r)
def test_RegistrationManager_services(self):
from rosmaster.registrations import Registrations, RegistrationManager
rm = RegistrationManager(ThreadPoolMock())
self.assertEquals(None, rm.get_node('caller1'))
# do an unregister first, before service_api is initialized
code, msg, val = rm.unregister_service('s1', 'caller1', 'rosrpc://one:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
rm.register_service('s1', 'caller1', 'http://one:1234', 'rosrpc://one:1234')
self.assert_(rm.services.has_key('s1'))
self.assertEquals('rosrpc://one:1234', rm.services.get_service_api('s1'))
self.assertEquals('http://one:1234', rm.get_node('caller1').api)
self.assertEquals([['s1', ['caller1']]], rm.services.get_state())
# - verify that changed caller_api updates ref
rm.register_service('s1', 'caller1', 'http://oneB:1234', 'rosrpc://one:1234')
self.assert_(rm.services.has_key('s1'))
self.assertEquals('rosrpc://one:1234', rm.services.get_service_api('s1'))
self.assertEquals('http://oneB:1234', rm.get_node('caller1').api)
self.assertEquals([['s1', ['caller1']]], rm.services.get_state())
# - verify that changed service_api updates ref
rm.register_service('s1', 'caller1', 'http://oneB:1234', 'rosrpc://oneB:1234')
self.assert_(rm.services.has_key('s1'))
self.assertEquals('rosrpc://oneB:1234', rm.services.get_service_api('s1'))
self.assertEquals('http://oneB:1234', rm.get_node('caller1').api)
self.assertEquals([['s1', ['caller1']]], rm.services.get_state())
rm.register_service('s2', 'caller2', 'http://two:1234', 'rosrpc://two:1234')
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
# - unregister should be noop if service api does not match
code, msg, val = rm.unregister_service('s2', 'caller2', 'rosrpc://b:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
self.assert_(rm.services.has_key('s2'))
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
self.assertEquals('rosrpc://two:1234', rm.services.get_service_api('s2'))
# - unregister should be noop if service is unknown
code, msg, val = rm.unregister_service('unknown', 'caller2', 'rosrpc://two:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
self.assert_(rm.services.has_key('s2'))
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
self.assertEquals('rosrpc://two:1234', rm.services.get_service_api('s2'))
# - unregister should clear all knowledge of caller2
code,msg, val = rm.unregister_service('s2', 'caller2', 'rosrpc://two:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.assert_(rm.services.has_key('s1'))
self.failIf(rm.services.has_key('s2'))
self.assertEquals(None, rm.get_node('caller2'))
code, msg, val = rm.unregister_service('s1', 'caller1', 'rosrpc://oneB:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.assert_(not rm.services.__nonzero__())
self.failIf(rm.services.has_key('s1'))
self.assertEquals(None, rm.get_node('caller1'))
def test_RegistrationManager_topic_pub(self):
from rosmaster.registrations import Registrations, RegistrationManager
rm = RegistrationManager(ThreadPoolMock())
self.subtest_RegistrationManager(rm, rm.publishers, rm.register_publisher, rm.unregister_publisher)
def test_RegistrationManager_topic_sub(self):
from rosmaster.registrations import Registrations, RegistrationManager
rm = RegistrationManager(ThreadPoolMock())
self.subtest_RegistrationManager(rm, rm.subscribers, rm.register_subscriber, rm.unregister_subscriber)
def test_RegistrationManager_param_sub(self):
from rosmaster.registrations import Registrations, RegistrationManager
rm = RegistrationManager(ThreadPoolMock())
self.subtest_RegistrationManager(rm, rm.param_subscribers, rm.register_param_subscriber, rm.unregister_param_subscriber)
def subtest_RegistrationManager(self, rm, r, register, unregister):
self.assertEquals(None, rm.get_node('caller1'))
register('key1', 'caller1', 'http://one:1234')
self.assert_(r.has_key('key1'))
self.assertEquals('http://one:1234', rm.get_node('caller1').api)
self.assertEquals([['key1', ['caller1']]], r.get_state())
# - verify that changed caller_api updates ref
register('key1', 'caller1', 'http://oneB:1234')
self.assert_(r.has_key('key1'))
self.assertEquals('http://oneB:1234', rm.get_node('caller1').api)
self.assertEquals([['key1', ['caller1']]], r.get_state())
register('key2', 'caller2', 'http://two:1234')
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
# - unregister should be noop if caller api does not match
code, msg, val = unregister('key2', 'caller2', 'http://b:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
# - unregister should be noop if key is unknown
code, msg, val = unregister('unknown', 'caller2', 'http://two:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
self.assert_(r.has_key('key2'))
self.assertEquals('http://two:1234', rm.get_node('caller2').api)
# - unregister should be noop if unknown node
code, msg, val = rm.unregister_publisher('key2', 'unknown', 'http://unknown:1')
self.assertEquals(1, code)
self.assertEquals(0, val)
self.assert_(r.has_key('key2'))
# - unregister should clear all knowledge of caller2
code,msg, val = unregister('key2', 'caller2', 'http://two:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.assert_(r.has_key('key1'))
self.failIf(r.has_key('key2'))
self.assertEquals(None, rm.get_node('caller2'))
code, msg, val = unregister('key1', 'caller1', 'http://oneB:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.assert_(not r.__nonzero__())
self.failIf(r.has_key('key1'))
self.assertEquals(None, rm.get_node('caller1'))
def test_RegistrationManager_base(self):
import rosmaster.exceptions
from rosmaster.registrations import Registrations, RegistrationManager
threadpool = ThreadPoolMock()
rm = RegistrationManager(threadpool)
self.assert_(isinstance(rm.services, Registrations))
self.assertEquals(Registrations.SERVICE, rm.services.type)
self.assert_(isinstance(rm.param_subscribers, Registrations))
self.assertEquals(Registrations.PARAM_SUBSCRIPTIONS, rm.param_subscribers.type)
self.assert_(isinstance(rm.subscribers, Registrations))
self.assertEquals(Registrations.TOPIC_SUBSCRIPTIONS, rm.subscribers.type)
self.assert_(isinstance(rm.subscribers, Registrations))
self.assertEquals(Registrations.TOPIC_PUBLICATIONS, rm.publishers.type)
self.assert_(isinstance(rm.publishers, Registrations))
#test auto-clearing of registrations if node API changes
rm.register_publisher('pub1', 'caller1', 'http://one:1')
rm.register_publisher('pub1', 'caller2', 'http://two:1')
rm.register_publisher('pub1', 'caller3', 'http://three:1')
rm.register_subscriber('sub1', 'caller1', 'http://one:1')
rm.register_subscriber('sub1', 'caller2', 'http://two:1')
rm.register_subscriber('sub1', 'caller3', 'http://three:1')
rm.register_param_subscriber('p1', 'caller1', 'http://one:1')
rm.register_param_subscriber('p1', 'caller2', 'http://two:1')
rm.register_param_subscriber('p1', 'caller3', 'http://three:1')
rm.register_service('s1', 'caller1', 'http://one:1', 'rosrpc://one:1')
self.assertEquals('http://one:1', rm.get_node('caller1').api)
self.assertEquals('http://two:1', rm.get_node('caller2').api)
self.assertEquals('http://three:1', rm.get_node('caller3').api)
# - first, make sure that changing rosrpc URI does not erase state
rm.register_service('s1', 'caller1', 'http://one:1', 'rosrpc://oneB:1')
n = rm.get_node('caller1')
self.assertEquals(['pub1'], n.topic_publications)
self.assertEquals(['sub1'], n.topic_subscriptions)
self.assertEquals(['p1'], n.param_subscriptions)
self.assertEquals(['s1'], n.services)
self.assert_('http://one:1' in rm.publishers.get_apis('pub1'))
self.assert_('http://one:1' in rm.subscribers.get_apis('sub1'))
self.assert_('http://one:1' in rm.param_subscribers.get_apis('p1'))
self.assert_('http://one:1' in rm.services.get_apis('s1'))
# - also, make sure unregister does not erase state if API changed
rm.unregister_publisher('pub1', 'caller1', 'http://not:1')
self.assert_('http://one:1' in rm.publishers.get_apis('pub1'))
rm.unregister_subscriber('sub1', 'caller1', 'http://not:1')
self.assert_('http://one:1' in rm.subscribers.get_apis('sub1'))
rm.unregister_param_subscriber('p1', 'caller1', 'http://not:1')
self.assert_('http://one:1' in rm.param_subscribers.get_apis('p1'))
rm.unregister_service('sub1', 'caller1', 'rosrpc://not:1')
self.assert_('http://one:1' in rm.services.get_apis('s1'))
# erase caller1 sub/srvs/params via register_publisher
rm.register_publisher('pub1', 'caller1', 'http://newone:1')
self.assertEquals('http://newone:1', rm.get_node('caller1').api)
# - check node ref
n = rm.get_node('caller1')
self.assertEquals(['pub1'], n.topic_publications)
self.assertEquals([], n.services)
self.assertEquals([], n.topic_subscriptions)
self.assertEquals([], n.param_subscriptions)
# - checks publishers
self.assert_('http://newone:1' in rm.publishers.get_apis('pub1'))
# - checks subscribers
self.assert_(rm.subscribers.has_key('sub1'))
self.failIf('http://one:1' in rm.subscribers.get_apis('sub1'))
# - checks param subscribers
self.assert_(rm.param_subscribers.has_key('p1'))
self.failIf('http://one:1' in rm.param_subscribers.get_apis('p1'))
# erase caller2 pub/sub/params via register_service
# - initial state
self.assert_('http://two:1' in rm.publishers.get_apis('pub1'))
self.assert_('http://two:1' in rm.subscribers.get_apis('sub1'))
self.assert_('http://two:1' in rm.param_subscribers.get_apis('p1'))
# - change ownership of s1 to caller2
rm.register_service('s1', 'caller2', 'http://two:1', 'rosrpc://two:1')
self.assert_('http://two:1' in rm.services.get_apis('s1'))
self.assert_('http://two:1' in rm.publishers.get_apis('pub1'))
self.assert_('http://two:1' in rm.subscribers.get_apis('sub1'))
self.assert_('http://two:1' in rm.param_subscribers.get_apis('p1'))
rm.register_service('s1', 'caller2', 'http://newtwo:1', 'rosrpc://newtwo:1')
self.assertEquals('http://newone:1', rm.get_node('caller1').api)
# - check node ref
n = rm.get_node('caller2')
self.assertEquals([], n.topic_publications)
self.assertEquals(['s1'], n.services)
self.assertEquals([], n.topic_subscriptions)
self.assertEquals([], n.param_subscriptions)
# - checks publishers
self.assert_(rm.publishers.has_key('pub1'))
self.failIf('http://two:1' in rm.publishers.get_apis('pub1'))
# - checks subscribers
self.assert_(rm.subscribers.has_key('sub1'))
self.failIf('http://two:1' in rm.subscribers.get_apis('sub1'))
self.assertEquals([['sub1', ['caller3']]], rm.subscribers.get_state())
# - checks param subscribers
self.assert_(rm.param_subscribers.has_key('p1'))
self.failIf('http://two:1' in rm.param_subscribers.get_apis('p1'))
self.assertEquals([['p1', ['caller3']]], rm.param_subscribers.get_state())
def test_Registrations_unregister_all(self):
import rosmaster.exceptions
from rosmaster.registrations import Registrations
r = Registrations(Registrations.TOPIC_SUBSCRIPTIONS)
for k in ['topic1', 'topic1b', 'topic1c', 'topic1d']:
r.register(k, 'node1', 'http://node1:5678')
r.register('topic2', 'node2', 'http://node2:5678')
r.unregister_all('node1')
self.failIf(not r)
for k in ['topic1', 'topic1b', 'topic1c', 'topic1d']:
self.failIf(r.has_key(k))
self.assertEquals(['topic2'], [k for k in r.iterkeys()])
r = Registrations(Registrations.TOPIC_PUBLICATIONS)
for k in ['topic1', 'topic1b', 'topic1c', 'topic1d']:
r.register(k, 'node1', 'http://node1:5678')
r.register('topic2', 'node2', 'http://node2:5678')
r.unregister_all('node1')
self.failIf(not r)
for k in ['topic1', 'topic1b', 'topic1c', 'topic1d']:
self.failIf(r.has_key(k))
self.assertEquals(['topic2'], [k for k in r.iterkeys()])
r = Registrations(Registrations.PARAM_SUBSCRIPTIONS)
r.register('param2', 'node2', 'http://node2:5678')
for k in ['param1', 'param1b', 'param1c', 'param1d']:
r.register(k, 'node1', 'http://node1:5678')
r.unregister_all('node1')
self.failIf(not r)
for k in ['param1', 'param1b', 'param1c', 'param1d']:
self.failIf(r.has_key(k))
self.assertEquals(['param2'], [k for k in r.iterkeys()])
r = Registrations(Registrations.SERVICE)
for k in ['service1', 'service1b', 'service1c', 'service1d']:
r.register(k, 'node1', 'http://node1:5678', 'rosrpc://node1:1234')
r.register('service2', 'node2', 'http://node2:5678', 'rosrpc://node2:1234')
r.unregister_all('node1')
self.failIf(not r)
for k in ['service1', 'service1b', 'service1c', 'service1d']:
self.failIf(r.has_key(k))
self.assertEquals(None, r.get_service_api(k))
self.assertEquals(['service2'], [k for k in r.iterkeys()])
self.assertEquals('rosrpc://node2:1234', r.get_service_api('service2'))
def _subtest_Registrations_services(self, r):
import rosmaster.exceptions
# call methods that use service_api_map, make sure they are guarded against lazy-init
self.assertEquals(None, r.get_service_api('s1'))
r.unregister_all('node1')
# do an unregister first, before service_api is initialized
code, msg, val = r.unregister('s1', 'caller1', None, 'rosrpc://one:1234')
self.assertEquals(1, code)
self.assertEquals(0, val)
try:
r.register('service1', 'node1', 'http://node1:5678')
self.fail("should require service_api")
except rosmaster.exceptions.InternalException: pass
r.register('service1', 'node1', 'http://node1:5678', 'rosrpc://node1:1234')
self.assert_('service1' in r) # test contains
self.assert_(r.has_key('service1')) # test contains
self.assertEquals(['service1'], [k for k in r.iterkeys()])
self.assertEquals(['http://node1:5678'], r.get_apis('service1'))
self.assertEquals('rosrpc://node1:1234', r.get_service_api('service1'))
self.assertEquals([('node1', 'http://node1:5678')], r['service1'])
self.failIf(not r) #test nonzero
self.assertEquals([['service1', ['node1']]], r.get_state())
r.register('service1', 'node2', 'http://node2:5678', 'rosrpc://node2:1234')
self.assertEquals(['service1'], [k for k in r.iterkeys()])
self.assertEquals('rosrpc://node2:1234', r.get_service_api('service1'))
self.assertEquals(['http://node2:5678'], r.get_apis('service1'))
self.assertEquals([('node2', 'http://node2:5678')], r['service1'])
self.assertEquals([['service1', ['node2']]], r.get_state())
# register a second service
r.register('service2', 'node3', 'http://node3:5678', 'rosrpc://node3:1234')
self.assertEquals('rosrpc://node3:1234', r.get_service_api('service2'))
self.assertEquals(2, len(r.get_state()))
self.assert_(['service2', ['node3']] in r.get_state(), r.get_state())
self.assert_(['service1', ['node2']] in r.get_state())
# register a third service, second service for node2
r.register('service1b', 'node2', 'http://node2:5678', 'rosrpc://node2:1234')
self.assertEquals(3, len(r.get_state()))
self.assert_(['service2', ['node3']] in r.get_state())
self.assert_(['service1b', ['node2']] in r.get_state())
self.assert_(['service1', ['node2']] in r.get_state())
# Unregister
try:
r.unregister('service1', 'node2', 'http://node2:1234')
self.fail("service_api param must be specified")
except rosmaster.exceptions.InternalException: pass
# - fail if service is not known
code, _, val = r.unregister('unknown', 'node2', 'http://node2:5678', 'rosprc://node2:1234')
self.assertEquals(0, val)
# - fail if node is not registered
code, _, val = r.unregister('service1', 'node3', 'http://node3:5678', 'rosrpc://node3:1234')
self.assertEquals(0, val)
# - fail if service API is different
code, _, val = r.unregister('service1', 'node2', 'http://node2b:5678', 'rosrpc://node3:1234')
self.assertEquals(0, val)
# - unregister service2
code, _, val = r.unregister('service2', 'node3', 'http://node3:5678', 'rosrpc://node3:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.failIf('service2' in r) # test contains
self.failIf(r.has_key('service2'))
self.assert_('service1' in [k for k in r.iterkeys()])
self.assert_('service1b' in [k for k in r.iterkeys()])
self.assertEquals([], r.get_apis('service2'))
self.assertEquals([], r['service2'])
self.failIf(not r) #test nonzero
self.assertEquals(2, len(r.get_state()))
self.failIf(['service2', ['node3']] in r.get_state())
# - unregister node2
code, _, val = r.unregister('service1', 'node2', 'http://node2:5678', 'rosrpc://node2:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.failIf('service1' in r) # test contains
self.failIf(r.has_key('service1'))
self.assertEquals(['service1b'], [k for k in r.iterkeys()])
self.assertEquals([], r.get_apis('service1'))
self.assertEquals([], r['service1'])
self.failIf(not r) #test nonzero
self.assertEquals([['service1b', ['node2']]], r.get_state())
code, _, val = r.unregister('service1b', 'node2', 'http://node2:5678', 'rosrpc://node2:1234')
self.assertEquals(1, code)
self.assertEquals(1, val)
self.failIf('service1' in r) # test contains
self.failIf(r.has_key('service1'))
self.assertEquals([], [k for k in r.iterkeys()])
self.assertEquals([], r.get_apis('service1'))
self.assertEquals([], r['service1'])
self.assert_(not r) #test nonzero
self.assertEquals([], r.get_state())
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/test/test_rosmaster_paramserver.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import unittest
import time
import random
import datetime
from rosgraph.names import make_global_ns, ns_join
# mock of subscription tests
class ThreadPoolMock(object):
def queue_task(*args): pass
## Unit tests for rosmaster.paramserver module
class TestRospyParamServer(unittest.TestCase):
def test_compute_param_updates(self):
from rosmaster.registrations import Registrations
from rosmaster.paramserver import compute_param_updates
# spec requires that subscriptions always have a trailing slash
tests = [
# [correct val], (subscribers, param_key, param_value)
([],({}, '/foo', 1)),
([],({'/bar': 'barapi'}, '/foo/', 1)),
([],({'/bar/': 'barapi'}, '/foo/', 1)),
# make sure that it's robust to aliases
([('fooapi', '/foo/', 1)], ({'/foo/': 'fooapi'}, '/foo', 1)),
([('fooapi', '/foo/', 1)], ({'/foo/': 'fooapi'}, '/foo/', 1)),
# check namespace subscription
([('fooapi', '/foo/val/', 1)], ({'/foo/': 'fooapi'}, '/foo/val', 1)),
# check against dictionary param values
([],({'/bar/': 'barapi'}, '/foo/', {'bar': 2})),
([('fooapi', '/foo/val/', 1)], ({'/foo/val/': 'fooapi'}, '/foo', {'val' : 1})),
([('fooapi', '/foo/bar/val/', 1)], ({'/foo/bar/val/': 'fooapi'}, '/foo', {'bar' : {'val' : 1}})),
([('fooapi', '/foo/bar/', {'val': 1})], ({'/foo/bar/': 'fooapi'}, '/foo', {'bar' : {'val' : 1}})),
([('fooapi', '/foo/', {'bar':{'val': 1}})], ({'/foo/': 'fooapi'}, '/foo', {'bar' : {'val' : 1}})),
([('fooapi', '/foo/', {'bar': 1, 'baz': 2}), ('foobazapi', '/foo/baz/', 2)],
({'/foo/': 'fooapi', '/foo/baz/': 'foobazapi'}, '/foo', {'bar' : 1, 'baz': 2})),
([('foobarapi', '/foo/bar/', 1), ('foobazapi', '/foo/baz/', 2)],
({'/foo/bar/': 'foobarapi', '/foo/baz/': 'foobazapi'}, '/foo', {'bar' : 1, 'baz': 2})),
# deletion of higher level tree
([('delapi', '/del/bar/', {})],
({'/del/bar/': 'delapi'}, '/del', {})),
]
for correct, args in tests:
reg = Registrations(Registrations.PARAM_SUBSCRIPTIONS)
reg.map = args[0]
param_key = args[1]
param_val = args[2]
val = compute_param_updates(reg, param_key, param_val)
self.assertEquals(len(correct), len(val), "Failed: \n%s \nreturned \n%s\nvs correct\n%s"%(str(args), str(val), str(correct)))
for c in correct:
self.assert_(c in val, "Failed: \n%s \ndid not include \n%s. \nIt returned \n%s"%(str(args), c, val))
def notify_task(self, updates):
self.last_update = updates
def test_subscribe_param_simple(self):
from rosmaster.registrations import RegistrationManager
from rosmaster.paramserver import ParamDictionary
# setup node and subscriber data
reg_manager = RegistrationManager(ThreadPoolMock())
param_server = ParamDictionary(reg_manager)
# subscribe to parameter that has not been set yet
self.last_update = None
self.assertEquals({}, param_server.subscribe_param('/foo', ('node1', 'http://node1:1')))
param_server.set_param('/foo', 1, notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1:1')], '/foo/', 1), ], self.last_update)
# resubscribe
self.assertEquals(1, param_server.subscribe_param('/foo', ('node1', 'http://node1:1')))
param_server.set_param('/foo', 2, notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1:1')], '/foo/', 2), ], self.last_update)
# resubscribe (test canonicalization of parameter name)
self.assertEquals(2, param_server.subscribe_param('/foo/', ('node1', 'http://node1:1')))
param_server.set_param('/foo', 'resub2', notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1:1')], '/foo/', 'resub2'), ], self.last_update)
# change the URI
self.assertEquals('resub2', param_server.subscribe_param('/foo', ('node1', 'http://node1b:1')))
self.assertEquals('http://node1b:1', reg_manager.get_node('node1').api)
param_server.set_param('/foo', 3, notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1b:1')], '/foo/', 3), ], self.last_update)
# multiple subscriptions to same param
self.assertEquals(3, param_server.subscribe_param('/foo', ('node2', 'http://node2:2')))
self.assertEquals('http://node2:2', reg_manager.get_node('node2').api)
param_server.set_param('/foo', 4, notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1b:1'), ('node2', 'http://node2:2')], '/foo/', 4), ], self.last_update)
def test_subscribe_param_tree(self):
from rosmaster.registrations import RegistrationManager
from rosmaster.paramserver import ParamDictionary
# setup node and subscriber data
reg_manager = RegistrationManager(ThreadPoolMock())
param_server = ParamDictionary(reg_manager)
# Test Parameter Tree Subscriptions
# simple case - subscribe and set whole tree
gains = {'p': 'P', 'i': 'I', 'd' : 'D'}
self.assertEquals({}, param_server.subscribe_param('/gains', ('ptnode', 'http://ptnode:1')))
param_server.set_param('/gains', gains.copy(), notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/', gains), ], self.last_update)
# - test with trailing slash
param_server.set_param('/gains/', gains.copy(), notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/', gains), ], self.last_update)
# change params within tree
param_server.set_param('/gains/p', 'P2', notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/p/', 'P2'), ], self.last_update)
param_server.set_param('/gains/i', 'I2', notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/i/', 'I2'), ], self.last_update)
# test overlapping subscriptions
self.assertEquals('P2', param_server.subscribe_param('/gains/p', ('ptnode2', 'http://ptnode2:2')))
param_server.set_param('/gains', gains.copy(), notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/', gains), \
([('ptnode2', 'http://ptnode2:2')], '/gains/p/', 'P'), \
], self.last_update)
# - retest with trailing slash on subscribe
self.last_update = None
self.assertEquals('P', param_server.subscribe_param('/gains/p/', ('ptnode2', 'http://ptnode2:2')))
param_server.set_param('/gains', gains.copy(), notify_task=self.notify_task)
self.assertEquals([([('ptnode', 'http://ptnode:1')], '/gains/', gains), \
([('ptnode2', 'http://ptnode2:2')], '/gains/p/', 'P'), \
], self.last_update)
# test with overlapping (change to sub param)
param_server.set_param('/gains/p', 'P3', notify_task=self.notify_task)
# - this is a bit overtuned as a more optimal ps could use one update
ptnode2 = ([('ptnode2', 'http://ptnode2:2')], '/gains/p/', 'P3')
ptnode = ([('ptnode', 'http://ptnode:1')], '/gains/p/', 'P3')
self.assertTrue(len(self.last_update) == 2)
self.assertTrue(ptnode2 in self.last_update)
self.assertTrue(ptnode in self.last_update)
# virtual deletion: subscribe to subparam, parameter tree reset
self.last_update = None
param_server.set_param('/gains2', gains.copy(), notify_task=self.notify_task)
self.assertEquals('P', param_server.subscribe_param('/gains2/p/', ('ptnode3', 'http://ptnode3:3')))
# - erase the sub parameters
param_server.set_param('/gains2', {}, notify_task=self.notify_task)
self.assertEquals([([('ptnode3', 'http://ptnode3:3')], '/gains2/p/', {}), ], self.last_update)
#Final test: test subscription to entire tree
self.last_update = None
param_server.delete_param('/gains')
param_server.delete_param('/gains2')
self.assertEquals({}, param_server.get_param('/'))
self.assertEquals({}, param_server.subscribe_param('/', ('allnode', 'http://allnode:1')))
param_server.set_param('/one', 1, notify_task=self.notify_task)
self.assertEquals([([('allnode', 'http://allnode:1')], '/one/', 1), ], self.last_update)
param_server.set_param('/two', 2, notify_task=self.notify_task)
self.assertEquals([([('allnode', 'http://allnode:1')], '/two/', 2), ], self.last_update)
param_server.set_param('/foo/bar', 'bar', notify_task=self.notify_task)
self.assertEquals([([('allnode', 'http://allnode:1')], '/foo/bar/', 'bar'), ], self.last_update)
# verify that subscribe_param works with parameter deletion
def test_subscribe_param_deletion(self):
from rosmaster.registrations import RegistrationManager
from rosmaster.paramserver import ParamDictionary
# setup node and subscriber data
reg_manager = RegistrationManager(ThreadPoolMock())
param_server = ParamDictionary(reg_manager)
# subscription to then delete parameter
self.assertEquals({}, param_server.subscribe_param('/foo', ('node1', 'http://node1:1')))
param_server.set_param('/foo', 1, notify_task=self.notify_task)
param_server.delete_param('/foo', notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1:1')], '/foo/', {}), ], self.last_update)
# subscribe to and delete whole tree
gains = {'p': 'P', 'i': 'I', 'd' : 'D'}
self.assertEquals({}, param_server.subscribe_param('/gains', ('deltree', 'http://deltree:1')))
param_server.set_param('/gains', gains.copy(), notify_task=self.notify_task)
param_server.delete_param('/gains', notify_task=self.notify_task)
self.assertEquals([([('deltree', 'http://deltree:1')], '/gains/', {}), ], self.last_update)
# subscribe to and delete params within subtree
self.assertEquals({}, param_server.subscribe_param('/gains2', ('deltree2', 'http://deltree2:2')))
param_server.set_param('/gains2', gains.copy(), notify_task=self.notify_task)
param_server.delete_param('/gains2/p', notify_task=self.notify_task)
self.assertEquals([([('deltree2', 'http://deltree2:2')], '/gains2/p/', {}), ], self.last_update)
param_server.delete_param('/gains2/i', notify_task=self.notify_task)
self.assertEquals([([('deltree2', 'http://deltree2:2')], '/gains2/i/', {}), ], self.last_update)
param_server.delete_param('/gains2', notify_task=self.notify_task)
self.assertEquals([([('deltree2', 'http://deltree2:2')], '/gains2/', {}), ], self.last_update)
# delete parent tree
k = '/ns1/ns2/ns3/key'
self.assertEquals({}, param_server.subscribe_param(k, ('del_parent', 'http://del_parent:1')))
param_server.set_param(k, 1, notify_task=self.notify_task)
param_server.delete_param('/ns1/ns2', notify_task=self.notify_task)
self.assertEquals([([('del_parent', 'http://del_parent:1')], '/ns1/ns2/ns3/key/', {}), ], self.last_update)
def test_unsubscribe_param(self):
from rosmaster.registrations import RegistrationManager
from rosmaster.paramserver import ParamDictionary
# setup node and subscriber data
reg_manager = RegistrationManager(ThreadPoolMock())
param_server = ParamDictionary(reg_manager)
# basic test
self.last_update = None
self.assertEquals({}, param_server.subscribe_param('/foo', ('node1', 'http://node1:1')))
param_server.set_param('/foo', 1, notify_task=self.notify_task)
self.assertEquals([([('node1', 'http://node1:1')], '/foo/', 1), ], self.last_update)
# - return value is actually generated by Registrations
code, msg, val = param_server.unsubscribe_param('/foo', ('node1', 'http://node1:1'))
self.assertEquals(1, code)
self.assertEquals(1, val)
self.last_update = None
param_server.set_param('/foo', 2, notify_task=self.notify_task)
self.assertEquals(None, self.last_update)
# - repeat the unsubscribe
code, msg, val = param_server.unsubscribe_param('/foo', ('node1', 'http://node1:1'))
self.assertEquals(1, code)
self.assertEquals(0, val)
self.last_update = None
param_server.set_param('/foo', 2, notify_task=self.notify_task)
self.assertEquals(None, self.last_update)
# verify that stale unsubscribe has no effect on active subscription
self.last_update = None
self.assertEquals({}, param_server.subscribe_param('/bar', ('barnode', 'http://barnode:1')))
param_server.set_param('/bar', 3, notify_task=self.notify_task)
self.assertEquals([([('barnode', 'http://barnode:1')], '/bar/', 3), ], self.last_update)
code, msg, val = param_server.unsubscribe_param('/foo', ('barnode', 'http://notbarnode:1'))
self.assertEquals(1, code)
self.assertEquals(0, val)
param_server.set_param('/bar', 4, notify_task=self.notify_task)
self.assertEquals([([('barnode', 'http://barnode:1')], '/bar/', 4), ], self.last_update)
def _set_param(self, ctx, my_state, test_vals, param_server):
ctx = make_global_ns(ctx)
for type, vals in test_vals:
try:
caller_id = ns_join(ctx, "node")
count = 0
for val in vals:
key = ns_join(caller_id, "%s-%s"%(type,count))
param_server.set_param(key, val)
self.assert_(param_server.has_param(key))
true_key = ns_join(ctx, key)
my_state[true_key] = val
count += 1
except Exception:
assert "getParam failed on type[%s], val[%s]"%(type,val)
#self._check_param_state(my_state)
def _check_param_state(self, param_server, my_state):
for (k, v) in my_state.items():
assert param_server.has_param(k)
#print "verifying parameter %s"%k
try:
v2 = param_server.get_param(k)
except:
raise Exception("Exception raised while calling param_server.get_param(%s): %s"%(k, traceback.format_exc()))
self.assertEquals(v, v2)
param_names = my_state.keys()
ps_param_names = param_server.get_param_names()
assert not set(param_names) ^ set(ps_param_names), "parameter server keys do not match local: %s"%(set(param_names)^set(ps_param_names))
# test_has_param: test has_param API
def test_has_param(self):
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
self.failIf(param_server.has_param('/new_param'))
param_server.set_param('/new_param', 1)
self.assert_(param_server.has_param('/new_param'))
# test with param in sub-namespace
self.failIf(param_server.has_param('/sub/sub2/new_param2'))
# - verify that parameter tree does not exist yet (#587)
for k in ['/sub/sub2/', '/sub/sub2', '/sub/', '/sub']:
self.failIf(param_server.has_param(k))
param_server.set_param('/sub/sub2/new_param2', 1)
self.assert_(param_server.has_param('/sub/sub2/new_param2'))
# - verify that parameter tree now exists (#587)
for k in ['/sub/sub2/', '/sub/sub2', '/sub/', '/sub']:
self.assert_(param_server.has_param(k))
## test ^param naming, i.e. upwards-looking get access
## @param self
def test_search_param(self):
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
caller_id = '/node'
# vals are mostly identical, save some randomness. we want
# identical structure in order to stress lookup rules
val1 = { 'level1_p1': random.randint(0, 10000),
'level1_p2' : { 'level2_p2': random.randint(0, 10000) }}
val2 = { 'level1_p1': random.randint(0, 10000),
'level1_p2' : { 'level2_p2': random.randint(0, 10000) }}
val3 = { 'level1_p1': random.randint(0, 10000),
'level1_p2' : { 'level2_p2': random.randint(0, 10000) }}
val4 = { 'level1_p1': random.randint(0, 10000),
'level1_p2' : { 'level2_p2': random.randint(0, 10000) }}
full_dict = {}
# test invalid input
for k in ['', None, '~param']:
try:
param_server.search_param('/level1/level2', k)
self.fail("param_server search should have failed on [%s]"%k)
except ValueError: pass
for ns in ['', None, 'relative', '~param']:
try:
param_server.search_param(ns, 'param')
self.fail("param_server search should have failed on %s"%k)
except ValueError: pass
# set the val parameter at four levels so we can validate search
# - set val1
self.failIf(param_server.has_param('/level1/param'))
self.failIf(param_server.search_param('/level1/node', 'param'))
param_server.set_param('/level1/param', val1)
# - test param on val1
for ns in ['/level1/node', '/level1/level2/node', '/level1/level2/level3/node']:
self.assertEquals('/level1/param', param_server.search_param(ns, 'param'), "failed with ns[%s]"%ns)
self.assertEquals('/level1/param/', param_server.search_param(ns, 'param/'))
self.assertEquals('/level1/param/level1_p1', param_server.search_param(ns, 'param/level1_p1'))
self.assertEquals('/level1/param/level1_p2/level2_p2', param_server.search_param(ns, 'param/level1_p2/level2_p2'))
self.assertEquals(None, param_server.search_param('/root', 'param'))
self.assertEquals(None, param_server.search_param('/root', 'param/'))
# - set val2
self.failIf(param_server.has_param('/level1/level2/param'))
param_server.set_param('/level1/level2/param', val2)
# - test param on val2
for ns in ['/level1/level2/node', '/level1/level2/level3/node', '/level1/level2/level3/level4/node']:
self.assertEquals('/level1/level2/param', param_server.search_param(ns, 'param'))
self.assertEquals('/level1/level2/param/', param_server.search_param(ns, 'param/'))
self.assertEquals('/level1/param', param_server.search_param('/level1/node', 'param'))
self.assertEquals('/level1/param/', param_server.search_param('/level1/node', 'param/'))
self.assertEquals(None, param_server.search_param('/root', 'param'))
# - set val3
self.failIf(param_server.has_param('/level1/level2/level3/param'))
param_server.set_param('/level1/level2/level3/param', val3)
# - test param on val3
for ns in ['/level1/level2/level3/node', '/level1/level2/level3/level4/node']:
self.assertEquals('/level1/level2/level3/param', param_server.search_param(ns, 'param'))
self.assertEquals('/level1/level2/param', param_server.search_param('/level1/level2/node', 'param'))
self.assertEquals('/level1/param', param_server.search_param('/level1/node', 'param'))
# test subparams before we set val4 on the root
# - test looking for param/sub_param
self.assertEquals(None, param_server.search_param('/root', 'param'))
self.assertEquals(None, param_server.search_param('/root', 'param/level1_p1'))
self.assertEquals(None, param_server.search_param('/not/level1/level2/level3/level4/node', 'param/level1_p1'))
tests = [
('/level1/node', '/level1/param/'),
('/level1/level2/', '/level1/level2/param/'),
('/level1/level2', '/level1/level2/param/'),
('/level1/level2/node', '/level1/level2/param/'),
('/level1/level2/notlevel3', '/level1/level2/param/'),
('/level1/level2/notlevel3/node', '/level1/level2/param/'),
('/level1/level2/level3/level4', '/level1/level2/level3/param/'),
('/level1/level2/level3/level4/', '/level1/level2/level3/param/'),
('/level1/level2/level3/level4/node', '/level1/level2/level3/param/'),
]
for ns, pbase in tests:
self.assertEquals(pbase+'level1_p1',
param_server.search_param(ns, 'param/level1_p1'))
retval = param_server.search_param(ns, 'param/level1_p2/level2_p2')
self.assertEquals(pbase+'level1_p2/level2_p2', retval,
"failed with ns[%s] pbase[%s]: %s"%(ns, pbase, retval))
# - set val4 on the root
self.failIf(param_server.has_param('/param'))
param_server.set_param('/param', val4)
self.assertEquals('/param', param_server.search_param('/root', 'param'))
self.assertEquals('/param', param_server.search_param('/notlevel1/node', 'param'))
self.assertEquals('/level1/param', param_server.search_param('/level1/node', 'param'))
self.assertEquals('/level1/param', param_server.search_param('/level1', 'param'))
self.assertEquals('/level1/param', param_server.search_param('/level1/', 'param'))
# make sure that partial match works
val5 = { 'level1_p1': random.randint(0, 10000),
'level1_p2' : { }}
self.failIf(param_server.has_param('/partial1/param'))
param_server.set_param('/partial1/param', val5)
self.assertEquals('/partial1/param', param_server.search_param('/partial1', 'param'))
self.assertEquals('/partial1/param/level1_p1',
param_server.search_param('/partial1', 'param/level1_p1'))
# - this is the important check, should return key even if it doesn't exist yet based on stem match
self.assertEquals('/partial1/param/non_existent',
param_server.search_param('/partial1', 'param/non_existent'))
self.assertEquals('/partial1/param/level1_p2/non_existent',
param_server.search_param('/partial1', 'param/level1_p2/non_existent'))
# test_get_param: test basic getParam behavior. Value encoding verified separately by testParamValues
def test_get_param(self):
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
val = random.randint(0, 10000)
full_dict = {}
# very similar to has param sequence
self.failIf(param_server.has_param('/new_param'))
self.failIf(param_server.has_param('/new_param/'))
self.assertGetParamFail(param_server, '/new_param')
param_server.set_param('/new_param', val)
full_dict['new_param'] = val
self.assertEquals(val, param_server.get_param('/new_param'))
self.assertEquals(val, param_server.get_param('/new_param/'))
# - test homonym
self.assertEquals(val, param_server.get_param('/new_param//'))
# test full get
self.assertEquals(full_dict, param_server.get_param('/'))
# test with param in sub-namespace
val = random.randint(0, 10000)
self.failIf(param_server.has_param('/sub/sub2/new_param2'))
self.assertGetParamFail(param_server, '/sub/sub2/new_param2')
param_server.set_param('/sub/sub2/new_param2', val)
full_dict['sub'] = {'sub2': { 'new_param2': val }}
self.assertEquals(val, param_server.get_param('/sub/sub2/new_param2'))
# - test homonym
self.assertEquals(val, param_server.get_param('/sub///sub2/new_param2/'))
# test full get
self.assertEquals(full_dict, param_server.get_param('/'))
# test that parameter server namespace-get (#587)
val1 = random.randint(0, 10000)
val2 = random.randint(0, 10000)
val3 = random.randint(0, 10000)
for k in ['/gains/P', '/gains/I', '/gains/D', '/gains']:
self.assertGetParamFail(param_server, k)
self.failIf(param_server.has_param(k))
param_server.set_param('/gains/P', val1)
param_server.set_param('/gains/I', val2)
param_server.set_param('/gains/D', val3)
pid = {'P': val1, 'I': val2, 'D': val3}
full_dict['gains'] = pid
self.assertEquals(pid,
param_server.get_param('/gains'))
self.assertEquals(pid,
param_server.get_param('/gains/'))
self.assertEquals(full_dict,
param_server.get_param('/'))
self.failIf(param_server.has_param('/ns/gains/P'))
self.failIf(param_server.has_param('/ns/gains/I'))
self.failIf(param_server.has_param('/ns/gains/D'))
self.failIf(param_server.has_param('/ns/gains'))
param_server.set_param('/ns/gains/P', val1)
param_server.set_param('/ns/gains/I', val2)
param_server.set_param('/ns/gains/D', val3)
full_dict['ns'] = {'gains': pid}
self.assertEquals(pid,
param_server.get_param('/ns/gains'))
self.assertEquals({'gains': pid},
param_server.get_param('/ns/'))
self.assertEquals({'gains': pid},
param_server.get_param('/ns'))
self.assertEquals(full_dict,
param_server.get_param('/'))
def test_delete_param(self):
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
try:
param_server.delete_param('/fake')
self.fail("delete_param of non-existent should have failed")
except: pass
try:
param_server.delete_param('/')
self.fail("delete_param of root should have failed")
except: pass
param_server.set_param('/foo', 'foo')
param_server.set_param('/bar', 'bar')
self.assert_(param_server.has_param('/foo'))
self.assert_(param_server.has_param('/bar'))
param_server.delete_param('/foo')
self.failIf(param_server.has_param('/foo'))
# - test with trailing slash
param_server.delete_param('/bar/')
self.failIf(param_server.has_param('/bar'))
# test with namespaces
param_server.set_param("/sub/key/x", 1)
param_server.set_param("/sub/key/y", 2)
try:
param_server.delete_param('/sub/key/z')
self.fail("delete_param of non-existent should have failed")
except: pass
try:
param_server.delete_param('/sub/sub2/z')
self.fail("delete_param of non-existent should have failed")
except: pass
self.assert_(param_server.has_param('/sub/key/x'))
self.assert_(param_server.has_param('/sub/key/y'))
self.assert_(param_server.has_param('/sub/key'))
param_server.delete_param('/sub/key')
self.failIf(param_server.has_param('/sub/key'))
self.failIf(param_server.has_param('/sub/key/x'))
self.failIf(param_server.has_param('/sub/key/y'))
# test with namespaces (dictionary vals)
param_server.set_param('/sub2', {'key': { 'x' : 1, 'y' : 2}})
self.assert_(param_server.has_param('/sub2/key/x'))
self.assert_(param_server.has_param('/sub2/key/y'))
self.assert_(param_server.has_param('/sub2/key'))
param_server.delete_param('/sub2/key')
self.failIf(param_server.has_param('/sub2/key'))
self.failIf(param_server.has_param('/sub2/key/x'))
self.failIf(param_server.has_param('/sub2/key/y'))
# test with namespaces: treat value as if its a namespace
# - try to get the dictionary-of-dictionary code to fail
# by descending a value key as if it is a namespace
param_server.set_param('/a', 'b')
self.assert_(param_server.has_param('/a'))
try:
param_server.delete_param('/a/b/c')
self.fail_("should have raised key error")
except: pass
# test_set_param: test basic set_param behavior. Value encoding verified separately by testParamValues
def test_set_param(self):
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
caller_id = '/node'
val = random.randint(0, 10000)
# verify error behavior with root
try:
param_server.set_param('/', 1)
self.fail("ParamDictionary allowed root to be set to non-dictionary")
except: pass
# very similar to has param sequence
self.failIf(param_server.has_param('/new_param'))
param_server.set_param('/new_param', val)
self.assertEquals(val, param_server.get_param('/new_param'))
self.assertEquals(val, param_server.get_param('/new_param/'))
self.assert_(param_server.has_param('/new_param'))
# test with param in sub-namespace
val = random.randint(0, 10000)
self.failIf(param_server.has_param('/sub/sub2/new_param2'))
param_server.set_param('/sub/sub2/new_param2', val)
self.assertEquals(val, param_server.get_param('/sub/sub2/new_param2'))
# test with param type mutation
vals = ['a', {'a': 'b'}, 1, 1., 'foo', {'c': 'd'}, 4, {'a': {'b': 'c'}}, 3]
for v in vals:
param_server.set_param('/multi/multi_param', v)
self.assertEquals(v, param_server.get_param('/multi/multi_param'))
# - set value within subtree that mutates higher level value
param_server.set_param('/multi2/multi_param', 1)
self.assertEquals(1, param_server.get_param('/multi2/multi_param'))
param_server.set_param('/multi2/multi_param/a', 2)
self.assertEquals(2, param_server.get_param('/multi2/multi_param/a'))
self.assertEquals({'a': 2}, param_server.get_param('/multi2/multi_param/'))
param_server.set_param('/multi2/multi_param/a/b', 3)
self.assertEquals(3, param_server.get_param('/multi2/multi_param/a/b'))
self.assertEquals({'b': 3}, param_server.get_param('/multi2/multi_param/a/'))
self.assertEquals({'a': {'b': 3}}, param_server.get_param('/multi2/multi_param/'))
# test that parameter server namespace-set (#587)
self.failIf(param_server.has_param('/gains/P'))
self.failIf(param_server.has_param('/gains/I'))
self.failIf(param_server.has_param('/gains/D'))
self.failIf(param_server.has_param('/gains'))
pid = {'P': random.randint(0, 10000), 'I': random.randint(0, 10000), 'D': random.randint(0, 10000)}
param_server.set_param('/gains', pid)
self.assertEquals(pid, param_server.get_param('/gains'))
self.assertEquals(pid['P'], param_server.get_param('/gains/P'))
self.assertEquals(pid['I'], param_server.get_param('/gains/I'))
self.assertEquals(pid['D'], param_server.get_param('/gains/D'))
subns = {'gains1': pid, 'gains2': pid}
param_server.set_param('/ns', subns)
self.assertEquals(pid['P'], param_server.get_param('/ns/gains1/P'))
self.assertEquals(pid['I'], param_server.get_param('/ns/gains1/I'))
self.assertEquals(pid['D'], param_server.get_param('/ns/gains1/D'))
self.assertEquals(pid, param_server.get_param('/ns/gains1'))
self.assertEquals(pid, param_server.get_param('/ns/gains2'))
self.assertEquals(subns, param_server.get_param('/ns/'))
# test empty dictionary set
param_server.set_param('/ns', {})
# - param should still exist
self.assert_(param_server.has_param('/ns/'))
# - value should remain dictionary
self.assertEquals({}, param_server.get_param('/ns/'))
# - value2 below /ns/ should be erased
self.failIf(param_server.has_param('/ns/gains1'))
self.failIf(param_server.has_param('/ns/gains1/P'))
# verify that root can be set and that it erases all values
param_server.set_param('/', {})
self.failIf(param_server.has_param('/new_param'))
param_server.set_param('/', {'foo': 1, 'bar': 2, 'baz': {'a': 'a'}})
self.assertEquals(1, param_server.get_param('/foo'))
self.assertEquals(1, param_server.get_param('/foo/'))
self.assertEquals(2, param_server.get_param('/bar'))
self.assertEquals(2, param_server.get_param('/bar/'))
self.assertEquals('a', param_server.get_param('/baz/a'))
self.assertEquals('a', param_server.get_param('/baz/a/'))
# test_param_values: test storage of all XML-RPC compatible types"""
def test_param_values(self):
import math
from rosmaster.paramserver import ParamDictionary
param_server = ParamDictionary(None)
test_vals = [
['int', [0, 1024, 2147483647, -2147483647]],
['boolean', [True, False]],
#no longer testing null char
#['string', ['', '\0', 'x', 'hello', ''.join([chr(n) for n in range(0, 255)])]],
['unicode-string', [u'', u'hello', u'Andr\302\202'.encode('utf-8'), u'\377\376A\000n\000d\000r\000\202\000'.encode('utf-16')]],
['string-easy-ascii', [chr(n) for n in range(32, 128)]],
#['string-mean-ascii-low', [chr(n) for n in range(9, 10)]], #separate for easier book-keeping
#['string-mean-ascii-low', [chr(n) for n in range(1, 31)]], #separate for easier book-keeping
#['string-mean-signed', [chr(n) for n in range(129, 256)]],
['string', ['', 'x', 'hello-there', 'new\nline', 'tab\t']],
['double', [0.0, math.pi, -math.pi, 3.4028235e+38, -3.4028235e+38]],
#TODO: microseconds?
['datetime', [datetime.datetime(2005, 12, 6, 12, 13, 14), datetime.datetime(1492, 12, 6, 12, 13, 14)]],
['array', [[], [1, 2, 3], ['a', 'b', 'c'], [0.0, 0.1, 0.2, 2.0, 2.1, -4.0],
[1, 'a', True], [[1, 2, 3], ['a', 'b', 'c'], [1.0, 2.1, 3.2]]]
],
]
print("Putting parameters onto the server")
# put our params into the parameter server
contexts = ['', 'scope1', 'scope/subscope1', 'scope/sub1/sub2']
my_state = {}
failures = []
for ctx in contexts:
self._set_param(ctx, my_state, test_vals, param_server)
self._check_param_state(param_server, my_state)
print("Deleting all of our parameters")
# delete all of our parameters
count = 0
for key in list(my_state.keys()):
count += 1
param_server.delete_param(key)
del my_state[key]
# far too intensive to check every time
if count % 50 == 0:
self._check_param_state(param_server, my_state)
self._check_param_state(param_server, my_state)
def assertGetParamFail(self, param_server, param):
try:
param_server.get_param(param)
self.fail("get_param[%s] did not raise KeyError"%(param))
except KeyError: pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/scripts/rosmaster | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import rosmaster
rosmaster.rosmaster_main()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/util.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Utility routines for rosmaster.
"""
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
_proxies = {} #cache ServerProxys
def xmlrpcapi(uri):
"""
@return: instance for calling remote server or None if not a valid URI
@rtype: xmlrpc.client.ServerProxy
"""
if uri is None:
return None
uriValidate = urlparse(uri)
if not uriValidate[0] or not uriValidate[1]:
return None
if not uri in _proxies:
_proxies[uri] = ServerProxy(uri)
return _proxies[uri]
def remove_server_proxy(uri):
if uri in _proxies:
del _proxies[uri]
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/threadpool.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Internal threadpool library for zenmaster.
Adapted from U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871}
Added a 'marker' to tasks so that multiple tasks with the same
marker are not executed. As we are using the thread pool for i/o
tasks, the marker is set to the i/o name. This prevents a slow i/o
for gobbling up all of our threads
"""
import threading, logging, traceback
from time import sleep
class MarkedThreadPool(object):
"""Flexible thread pool class. Creates a pool of threads, then
accepts tasks that will be dispatched to the next available
thread."""
def __init__(self, numThreads):
"""Initialize the thread pool with numThreads workers."""
self.__threads = []
self.__resizeLock = threading.Condition(threading.Lock())
self.__taskLock = threading.Condition(threading.Lock())
self.__tasks = []
self.__markers = set()
self.__isJoining = False
self.set_thread_count(numThreads)
def set_thread_count(self, newNumThreads):
""" External method to set the current pool size. Acquires
the resizing lock, then calls the internal version to do real
work."""
# Can't change the thread count if we're shutting down the pool!
if self.__isJoining:
return False
self.__resizeLock.acquire()
try:
self.__set_thread_count_nolock(newNumThreads)
finally:
self.__resizeLock.release()
return True
def __set_thread_count_nolock(self, newNumThreads):
"""Set the current pool size, spawning or terminating threads
if necessary. Internal use only; assumes the resizing lock is
held."""
# If we need to grow the pool, do so
while newNumThreads > len(self.__threads):
newThread = ThreadPoolThread(self)
self.__threads.append(newThread)
newThread.start()
# If we need to shrink the pool, do so
while newNumThreads < len(self.__threads):
self.__threads[0].go_away()
del self.__threads[0]
def get_thread_count(self):
"""@return: number of threads in the pool."""
self.__resizeLock.acquire()
try:
return len(self.__threads)
finally:
self.__resizeLock.release()
def queue_task(self, marker, task, args=None, taskCallback=None):
"""Insert a task into the queue. task must be callable;
args and taskCallback can be None."""
if self.__isJoining == True:
return False
if not callable(task):
return False
self.__taskLock.acquire()
try:
self.__tasks.append((marker, task, args, taskCallback))
return True
finally:
self.__taskLock.release()
def remove_marker(self, marker):
"""Remove the marker from the currently executing tasks. Only one
task with the given marker can be executed at a given time"""
if marker is None:
return
self.__taskLock.acquire()
try:
self.__markers.remove(marker)
finally:
self.__taskLock.release()
def get_next_task(self):
""" Retrieve the next task from the task queue. For use
only by ThreadPoolThread objects contained in the pool."""
self.__taskLock.acquire()
try:
retval = None
for marker, task, args, callback in self.__tasks:
# unmarked or not currently executing
if marker is None or marker not in self.__markers:
retval = (marker, task, args, callback)
break
if retval:
# add the marker so we don't do any similar tasks
self.__tasks.remove(retval)
if marker is not None:
self.__markers.add(marker)
return retval
else:
return (None, None, None, None)
finally:
self.__taskLock.release()
def join_all(self, wait_for_tasks = True, wait_for_threads = True):
""" Clear the task queue and terminate all pooled threads,
optionally allowing the tasks and threads to finish."""
# Mark the pool as joining to prevent any more task queueing
self.__isJoining = True
# Wait for tasks to finish
if wait_for_tasks:
while self.__tasks != []:
sleep(.1)
# Tell all the threads to quit
self.__resizeLock.acquire()
try:
self.__set_thread_count_nolock(0)
self.__isJoining = True
# Wait until all threads have exited
if wait_for_threads:
for t in self.__threads:
t.join()
del t
# Reset the pool for potential reuse
self.__isJoining = False
finally:
self.__resizeLock.release()
class ThreadPoolThread(threading.Thread):
"""
Pooled thread class.
"""
threadSleepTime = 0.1
def __init__(self, pool):
"""Initialize the thread and remember the pool."""
threading.Thread.__init__(self)
self.setDaemon(True) #don't block program exit
self.__pool = pool
self.__isDying = False
def run(self):
"""
Until told to quit, retrieve the next task and execute
it, calling the callback if any.
"""
while self.__isDying == False:
marker, cmd, args, callback = self.__pool.get_next_task()
# If there's nothing to do, just sleep a bit
if cmd is None:
sleep(ThreadPoolThread.threadSleepTime)
else:
try:
try:
result = cmd(*args)
finally:
self.__pool.remove_marker(marker)
if callback is not None:
callback(result)
except Exception as e:
logging.getLogger('rosmaster.threadpool').error(traceback.format_exc())
def go_away(self):
""" Exit the run loop next time through."""
self.__isDying = True
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/validators.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""Internal-use Python decorators for parameter validation"""
from rosgraph.names import resolve_name, ANYTYPE
TYPE_SEPARATOR = '/'
ROSRPC = "rosrpc://"
def isstring(s):
"""Small helper version to check an object is a string in a way that works
for both Python 2 and 3
"""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
class ParameterInvalid(Exception):
"""Exception that is raised when a parameter fails validation checks"""
def __init__(self, message):
self._message = message
def __str__(self):
return str(self._message)
def non_empty(param_name):
"""Validator that checks that parameter is not empty"""
def validator(param, context):
if not param:
raise ParameterInvalid("ERROR: parameter [%s] must be specified and non-empty"%param_name)
return param
return validator
def non_empty_str(param_name):
"""Validator that checks that parameter is a string and non-empty"""
def validator(param, context):
if not param:
raise ParameterInvalid("ERROR: parameter [%s] must be specified and non-empty"%param_name)
elif not isstring(param):
raise ParameterInvalid("ERROR: parameter [%s] must be a string"%param_name)
return param
return validator
def not_none(param_name):
"""Validator that checks that parameter is not None"""
def validator(param, context):
if param is None:
raise ParameterInvalid("ERROR: parameter [%s] must be specified"%param_name)
return param
return validator
# Validators ######################################
def is_api(paramName):
"""
Validator that checks that parameter is a valid API handle
(i.e. URI). Both http and rosrpc are allowed schemes.
"""
def validator(param_value, callerId):
if not param_value or not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] is not an XMLRPC URI"%paramName)
if not param_value.startswith("http://") and not param_value.startswith(ROSRPC):
raise ParameterInvalid("ERROR: parameter [%s] is not an RPC URI"%paramName)
#could do more fancy parsing, but the above catches the major cases well enough
return param_value
return validator
def is_topic(param_name):
"""
Validator that checks that parameter is a valid ROS topic name
"""
def validator(param_value, caller_id):
v = valid_name_validator_resolved(param_name, param_value, caller_id)
if param_value == '/':
raise ParameterInvalid("ERROR: parameter [%s] cannot be the global namespace"%param_name)
return v
return validator
def is_service(param_name):
"""Validator that checks that parameter is a valid ROS service name"""
def validator(param_value, caller_id):
v = valid_name_validator_resolved(param_name, param_value, caller_id)
if param_value == '/':
raise ParameterInvalid("ERROR: parameter [%s] cannot be the global namespace"%param_name)
return v
return validator
def empty_or_valid_name(param_name):
"""
empty or valid graph resource name.
Validator that resolves names unless they an empty string is supplied, in which case
an empty string is returned.
"""
def validator(param_value, caller_id):
if not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a string"%param_name)
if not param_value:
return ''
#return resolve_name(param_value, namespace(caller_id))
return resolve_name(param_value, caller_id)
return validator
def valid_name_validator_resolved(param_name, param_value, caller_id):
if not param_value or not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name)
#TODO: actual validation of chars
# I added the colon check as the common error will be to send an URI instead of name
if ':' in param_value or ' ' in param_value:
raise ParameterInvalid("ERROR: parameter [%s] contains illegal chars"%param_name)
#return resolve_name(param_value, namespace(caller_id))
return resolve_name(param_value, caller_id)
def valid_name_validator_unresolved(param_name, param_value, caller_id):
if not param_value or not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name)
#TODO: actual validation of chars
# I added the colon check as the common error will be to send an URI instead of name
if ':' in param_value or ' ' in param_value:
raise ParameterInvalid("ERROR: parameter [%s] contains illegal chars"%param_name)
return param_value
def valid_name(param_name, resolve=True):
"""
Validator that resolves names and also ensures that they are not empty
@param param_name: name
@type param_name: str
@param resolve: if True/omitted, the name will be resolved to
a global form. Otherwise, no resolution occurs.
@type resolve: bool
@return: resolved parameter value
@rtype: str
"""
def validator(param_value, caller_id):
if resolve:
return valid_name_validator_resolved(param_name, param_value, caller_id)
return valid_name_validator_unresolved(param_name, param_value, caller_id)
return validator
def global_name(param_name):
"""
Validator that checks for valid, global graph resource name.
@return: parameter value
@rtype: str
"""
def validator(param_value, caller_id):
if not param_value or not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name)
#TODO: actual validation of chars
if not is_global(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a globally referenced name"%param_name)
return param_value
return validator
def valid_type_name(param_name):
"""validator that checks the type name is specified correctly"""
def validator(param_value, caller_id):
if param_value == ANYTYPE:
return param_value
if not param_value or not isstring(param_value):
raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name)
if not len(param_value.split(TYPE_SEPARATOR)) == 2:
raise ParameterInvalid("ERROR: parameter [%s] is not a valid package resource name"%param_name)
#TODO: actual validation of chars
return param_value
return validator
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/master_api.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
ROS Master API.
L{ROSMasterHandler} provides the API implementation of the
Master. Python allows an API to be introspected from a Python class,
so the handler has a 1-to-1 mapping with the actual XMLRPC API.
API return convention: (statusCode, statusMessage, returnValue)
- statusCode: an integer indicating the completion condition of the method.
- statusMessage: a human-readable string message for debugging
- returnValue: the return value of the method; method-specific.
Current status codes:
- -1: ERROR: Error on the part of the caller, e.g. an invalid parameter
- 0: FAILURE: Method was attempted but failed to complete correctly.
- 1: SUCCESS: Method completed successfully.
Individual methods may assign additional meaning/semantics to statusCode.
"""
from __future__ import print_function
import os
import sys
import logging
import threading
import time
import traceback
from rosgraph.xmlrpc import XmlRpcHandler
import rosgraph.names
from rosgraph.names import resolve_name
import rosmaster.paramserver
import rosmaster.threadpool
from rosmaster.util import xmlrpcapi
from rosmaster.registrations import RegistrationManager
from rosmaster.validators import non_empty, non_empty_str, not_none, is_api, is_topic, is_service, valid_type_name, valid_name, empty_or_valid_name, ParameterInvalid
NUM_WORKERS = 3 #number of threads we use to send publisher_update notifications
# Return code slots
STATUS = 0
MSG = 1
VAL = 2
_logger = logging.getLogger("rosmaster.master")
LOG_API = False
def mloginfo(msg, *args):
"""
Info-level master log statements. These statements may be printed
to screen so they should be user-readable.
@param msg: Message string
@type msg: str
@param args: arguments for msg if msg is a format string
"""
#mloginfo is in core so that it is accessible to master and masterdata
_logger.info(msg, *args)
def mlogwarn(msg, *args):
"""
Warn-level master log statements. These statements may be printed
to screen so they should be user-readable.
@param msg: Message string
@type msg: str
@param args: arguments for msg if msg is a format string
"""
#mloginfo is in core so that it is accessible to master and masterdata
_logger.warn(msg, *args)
if args:
print("WARN: " + msg % args)
else:
print("WARN: " + str(msg))
def apivalidate(error_return_value, validators=()):
"""
ROS master/slave arg-checking decorator. Applies the specified
validator to the corresponding argument and also remaps each
argument to be the value returned by the validator. Thus,
arguments can be simultaneously validated and canonicalized prior
to actual function call.
@param error_return_value: API value to return if call unexpectedly fails
@param validators: sequence of validators to apply to each
arg. None means no validation for the parameter is required. As all
api methods take caller_id as the first parameter, the validators
start with the second param.
@type validators: sequence
"""
def check_validates(f):
try:
func_code = f.__code__
func_name = f.__name__
except AttributeError:
func_code = f.func_code
func_name = f.func_name
assert len(validators) == func_code.co_argcount - 2, "%s failed arg check"%f #ignore self and caller_id
def validated_f(*args, **kwds):
if LOG_API:
_logger.debug("%s%s", func_name, str(args[1:]))
#print "%s%s"%(func_name, str(args[1:]))
if len(args) == 1:
_logger.error("%s invoked without caller_id paramter" % func_name)
return -1, "missing required caller_id parameter", error_return_value
elif len(args) != func_code.co_argcount:
return -1, "Error: bad call arity", error_return_value
instance = args[0]
caller_id = args[1]
def isstring(s):
"""Small helper version to check an object is a string in
a way that works for both Python 2 and 3
"""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
if not isstring(caller_id):
_logger.error("%s: invalid caller_id param type", func_name)
return -1, "caller_id must be a string", error_return_value
newArgs = [instance, caller_id] #canonicalized args
try:
for (v, a) in zip(validators, args[2:]):
if v:
try:
newArgs.append(v(a, caller_id))
except ParameterInvalid as e:
_logger.error("%s: invalid parameter: %s", func_name, str(e) or 'error')
return -1, str(e) or 'error', error_return_value
else:
newArgs.append(a)
if LOG_API:
retval = f(*newArgs, **kwds)
_logger.debug("%s%s returns %s", func_name, args[1:], retval)
return retval
else:
code, msg, val = f(*newArgs, **kwds)
if val is None:
return -1, "Internal error (None value returned)", error_return_value
return code, msg, val
except TypeError as te: #most likely wrong arg number
_logger.error(traceback.format_exc())
return -1, "Error: invalid arguments: %s"%te, error_return_value
except Exception as e: #internal failure
_logger.error(traceback.format_exc())
return 0, "Internal failure: %s"%e, error_return_value
try:
validated_f.__name__ = func_name
except AttributeError:
validated_f.func_name = func_name
validated_f.__doc__ = f.__doc__ #preserve doc
return validated_f
return check_validates
def publisher_update_task(api, topic, pub_uris):
"""
Contact api.publisherUpdate with specified parameters
@param api: XML-RPC URI of node to contact
@type api: str
@param topic: Topic name to send to node
@type topic: str
@param pub_uris: list of publisher APIs to send to node
@type pub_uris: [str]
"""
mloginfo("publisherUpdate[%s] -> %s", topic, api)
#TODO: check return value for errors so we can unsubscribe if stale
xmlrpcapi(api).publisherUpdate('/master', topic, pub_uris)
def service_update_task(api, service, uri):
"""
Contact api.serviceUpdate with specified parameters
@param api: XML-RPC URI of node to contact
@type api: str
@param service: Service name to send to node
@type service: str
@param uri: URI to send to node
@type uri: str
"""
mloginfo("serviceUpdate[%s, %s] -> %s",service, uri, api)
xmlrpcapi(api).serviceUpdate('/master', service, uri)
###################################################
# Master Implementation
class ROSMasterHandler(object):
"""
XML-RPC handler for ROS master APIs.
API routines for the ROS Master Node. The Master Node is a
superset of the Slave Node and contains additional API methods for
creating and monitoring a graph of slave nodes.
By convention, ROS nodes take in caller_id as the first parameter
of any API call. The setting of this parameter is rarely done by
client code as ros::msproxy::MasterProxy automatically inserts
this parameter (see ros::client::getMaster()).
"""
def __init__(self, num_workers=NUM_WORKERS):
"""ctor."""
self.uri = None
self.done = False
self.thread_pool = rosmaster.threadpool.MarkedThreadPool(num_workers)
# pub/sub/providers: dict { topicName : [publishers/subscribers names] }
self.ps_lock = threading.Condition(threading.Lock())
self.reg_manager = RegistrationManager(self.thread_pool)
# maintain refs to reg_manager fields
self.publishers = self.reg_manager.publishers
self.subscribers = self.reg_manager.subscribers
self.services = self.reg_manager.services
self.param_subscribers = self.reg_manager.param_subscribers
self.topics_types = {} #dict { topicName : type }
# parameter server dictionary
self.param_server = rosmaster.paramserver.ParamDictionary(self.reg_manager)
def _shutdown(self, reason=''):
if self.thread_pool is not None:
self.thread_pool.join_all(wait_for_tasks=False, wait_for_threads=False)
self.thread_pool = None
self.done = True
def _ready(self, uri):
"""
Initialize the handler with the XMLRPC URI. This is a standard callback from the XmlRpcNode API.
@param uri: XML-RPC URI
@type uri: str
"""
self.uri = uri
def _ok(self):
return not self.done
###############################################################################
# EXTERNAL API
@apivalidate(0, (None, ))
def shutdown(self, caller_id, msg=''):
"""
Stop this server
@param caller_id: ROS caller id
@type caller_id: str
@param msg: a message describing why the node is being shutdown.
@type msg: str
@return: [code, msg, 0]
@rtype: [int, str, int]
"""
if msg:
print("shutdown request: %s" % msg, file=sys.stdout)
else:
print("shutdown requst", file=sys.stdout)
self._shutdown('external shutdown request from [%s]: %s'%(caller_id, msg))
return 1, "shutdown", 0
@apivalidate('')
def getUri(self, caller_id):
"""
Get the XML-RPC URI of this server.
@param caller_id str: ROS caller id
@return [int, str, str]: [1, "", xmlRpcUri]
"""
return 1, "", self.uri
@apivalidate(-1)
def getPid(self, caller_id):
"""
Get the PID of this server
@param caller_id: ROS caller id
@type caller_id: str
@return: [1, "", serverProcessPID]
@rtype: [int, str, int]
"""
return 1, "", os.getpid()
################################################################
# PARAMETER SERVER ROUTINES
@apivalidate(0, (non_empty_str('key'),))
def deleteParam(self, caller_id, key):
"""
Parameter Server: delete parameter
@param caller_id: ROS caller id
@type caller_id: str
@param key: parameter name
@type key: str
@return: [code, msg, 0]
@rtype: [int, str, int]
"""
try:
key = resolve_name(key, caller_id)
self.param_server.delete_param(key, self._notify_param_subscribers)
mloginfo("-PARAM [%s] by %s",key, caller_id)
return 1, "parameter %s deleted"%key, 0
except KeyError as e:
return -1, "parameter [%s] is not set"%key, 0
@apivalidate(0, (non_empty_str('key'), not_none('value')))
def setParam(self, caller_id, key, value):
"""
Parameter Server: set parameter. NOTE: if value is a
dictionary it will be treated as a parameter tree, where key
is the parameter namespace. For example:::
{'x':1,'y':2,'sub':{'z':3}}
will set key/x=1, key/y=2, and key/sub/z=3. Furthermore, it
will replace all existing parameters in the key parameter
namespace with the parameters in value. You must set
parameters individually if you wish to perform a union update.
@param caller_id: ROS caller id
@type caller_id: str
@param key: parameter name
@type key: str
@param value: parameter value.
@type value: XMLRPCLegalValue
@return: [code, msg, 0]
@rtype: [int, str, int]
"""
key = resolve_name(key, caller_id)
self.param_server.set_param(key, value, self._notify_param_subscribers)
mloginfo("+PARAM [%s] by %s",key, caller_id)
return 1, "parameter %s set"%key, 0
@apivalidate(0, (non_empty_str('key'),))
def getParam(self, caller_id, key):
"""
Retrieve parameter value from server.
@param caller_id: ROS caller id
@type caller_id: str
@param key: parameter to lookup. If key is a namespace,
getParam() will return a parameter tree.
@type key: str
getParam() will return a parameter tree.
@return: [code, statusMessage, parameterValue]. If code is not
1, parameterValue should be ignored. If key is a namespace,
the return value will be a dictionary, where each key is a
parameter in that namespace. Sub-namespaces are also
represented as dictionaries.
@rtype: [int, str, XMLRPCLegalValue]
"""
try:
key = resolve_name(key, caller_id)
return 1, "Parameter [%s]"%key, self.param_server.get_param(key)
except KeyError as e:
return -1, "Parameter [%s] is not set"%key, 0
@apivalidate(0, (non_empty_str('key'),))
def searchParam(self, caller_id, key):
"""
Search for parameter key on parameter server. Search starts in caller's namespace and proceeds
upwards through parent namespaces until Parameter Server finds a matching key.
searchParam's behavior is to search for the first partial match.
For example, imagine that there are two 'robot_description' parameters::
/robot_description
/robot_description/arm
/robot_description/base
/pr2/robot_description
/pr2/robot_description/base
If I start in the namespace /pr2/foo and search for
'robot_description', searchParam will match
/pr2/robot_description. If I search for 'robot_description/arm'
it will return /pr2/robot_description/arm, even though that
parameter does not exist (yet).
@param caller_id str: ROS caller id
@type caller_id: str
@param key: parameter key to search for.
@type key: str
@return: [code, statusMessage, foundKey]. If code is not 1, foundKey should be
ignored.
@rtype: [int, str, str]
"""
search_key = self.param_server.search_param(caller_id, key)
if search_key:
return 1, "Found [%s]"%search_key, search_key
else:
return -1, "Cannot find parameter [%s] in an upwards search"%key, ''
@apivalidate(0, (is_api('caller_api'), non_empty_str('key'),))
def subscribeParam(self, caller_id, caller_api, key):
"""
Retrieve parameter value from server and subscribe to updates to that param. See
paramUpdate() in the Node API.
@param caller_id str: ROS caller id
@type caller_id: str
@param key: parameter to lookup.
@type key: str
@param caller_api: API URI for paramUpdate callbacks.
@type caller_api: str
@return: [code, statusMessage, parameterValue]. If code is not
1, parameterValue should be ignored. parameterValue is an empty dictionary if the parameter
has not been set yet.
@rtype: [int, str, XMLRPCLegalValue]
"""
key = resolve_name(key, caller_id)
try:
# ps_lock has precedence and is required due to
# potential self.reg_manager modification
self.ps_lock.acquire()
val = self.param_server.subscribe_param(key, (caller_id, caller_api))
finally:
self.ps_lock.release()
return 1, "Subscribed to parameter [%s]"%key, val
@apivalidate(0, (is_api('caller_api'), non_empty_str('key'),))
def unsubscribeParam(self, caller_id, caller_api, key):
"""
Retrieve parameter value from server and subscribe to updates to that param. See
paramUpdate() in the Node API.
@param caller_id str: ROS caller id
@type caller_id: str
@param key: parameter to lookup.
@type key: str
@param caller_api: API URI for paramUpdate callbacks.
@type caller_api: str
@return: [code, statusMessage, numUnsubscribed].
If numUnsubscribed is zero it means that the caller was not subscribed to the parameter.
@rtype: [int, str, int]
"""
key = resolve_name(key, caller_id)
try:
# ps_lock is required due to potential self.reg_manager modification
self.ps_lock.acquire()
retval = self.param_server.unsubscribe_param(key, (caller_id, caller_api))
finally:
self.ps_lock.release()
return 1, "Unsubscribe to parameter [%s]"%key, 1
@apivalidate(False, (non_empty_str('key'),))
def hasParam(self, caller_id, key):
"""
Check if parameter is stored on server.
@param caller_id str: ROS caller id
@type caller_id: str
@param key: parameter to check
@type key: str
@return: [code, statusMessage, hasParam]
@rtype: [int, str, bool]
"""
key = resolve_name(key, caller_id)
if self.param_server.has_param(key):
return 1, key, True
else:
return 1, key, False
@apivalidate([])
def getParamNames(self, caller_id):
"""
Get list of all parameter names stored on this server.
This does not adjust parameter names for caller's scope.
@param caller_id: ROS caller id
@type caller_id: str
@return: [code, statusMessage, parameterNameList]
@rtype: [int, str, [str]]
"""
return 1, "Parameter names", self.param_server.get_param_names()
##################################################################################
# NOTIFICATION ROUTINES
def _notify(self, registrations, task, key, value, node_apis):
"""
Generic implementation of callback notification
@param registrations: Registrations
@type registrations: L{Registrations}
@param task: task to queue
@type task: fn
@param key: registration key
@type key: str
@param value: value to pass to task
@type value: Any
"""
# cache thread_pool for thread safety
thread_pool = self.thread_pool
if not thread_pool:
return
try:
for node_api in node_apis:
# use the api as a marker so that we limit one thread per subscriber
thread_pool.queue_task(node_api, task, (node_api, key, value))
except KeyError:
_logger.warn('subscriber data stale (key [%s], listener [%s]): node API unknown'%(key, s))
def _notify_param_subscribers(self, updates):
"""
Notify parameter subscribers of new parameter value
@param updates [([str], str, any)*]: [(subscribers, param_key, param_value)*]
@param param_value str: parameter value
"""
# cache thread_pool for thread safety
thread_pool = self.thread_pool
if not thread_pool:
return
for subscribers, key, value in updates:
# use the api as a marker so that we limit one thread per subscriber
for caller_id, caller_api in subscribers:
self.thread_pool.queue_task(caller_api, self.param_update_task, (caller_id, caller_api, key, value))
def param_update_task(self, caller_id, caller_api, param_key, param_value):
"""
Contact api.paramUpdate with specified parameters
@param caller_id: caller ID
@type caller_id: str
@param caller_api: XML-RPC URI of node to contact
@type caller_api: str
@param param_key: parameter key to pass to node
@type param_key: str
@param param_value: parameter value to pass to node
@type param_value: str
"""
mloginfo("paramUpdate[%s]", param_key)
code, _, _ = xmlrpcapi(caller_api).paramUpdate('/master', param_key, param_value)
if code == -1:
try:
# ps_lock is required due to potential self.reg_manager modification
self.ps_lock.acquire()
# reverse lookup to figure out who we just called
matches = self.reg_manager.reverse_lookup(caller_api)
for m in matches:
retval = self.param_server.unsubscribe_param(param_key, (m.id, caller_api))
finally:
self.ps_lock.release()
def _notify_topic_subscribers(self, topic, pub_uris, sub_uris):
"""
Notify subscribers with new publisher list
@param topic: name of topic
@type topic: str
@param pub_uris: list of URIs of publishers.
@type pub_uris: [str]
"""
self._notify(self.subscribers, publisher_update_task, topic, pub_uris, sub_uris)
##################################################################################
# SERVICE PROVIDER
@apivalidate(0, ( is_service('service'), is_api('service_api'), is_api('caller_api')))
def registerService(self, caller_id, service, service_api, caller_api):
"""
Register the caller as a provider of the specified service.
@param caller_id str: ROS caller id
@type caller_id: str
@param service: Fully-qualified name of service
@type service: str
@param service_api: Service URI
@type service_api: str
@param caller_api: XML-RPC URI of caller node
@type caller_api: str
@return: (code, message, ignore)
@rtype: (int, str, int)
"""
try:
self.ps_lock.acquire()
self.reg_manager.register_service(service, caller_id, caller_api, service_api)
mloginfo("+SERVICE [%s] %s %s", service, caller_id, caller_api)
finally:
self.ps_lock.release()
return 1, "Registered [%s] as provider of [%s]"%(caller_id, service), 1
@apivalidate(0, (is_service('service'),))
def lookupService(self, caller_id, service):
"""
Lookup all provider of a particular service.
@param caller_id str: ROS caller id
@type caller_id: str
@param service: fully-qualified name of service to lookup.
@type: service: str
@return: (code, message, serviceUrl). service URL is provider's
ROSRPC URI with address and port. Fails if there is no provider.
@rtype: (int, str, str)
"""
try:
self.ps_lock.acquire()
service_url = self.services.get_service_api(service)
finally:
self.ps_lock.release()
if service_url:
return 1, "rosrpc URI: [%s]"%service_url, service_url
else:
return -1, "no provider", ''
@apivalidate(0, ( is_service('service'), is_api('service_api')))
def unregisterService(self, caller_id, service, service_api):
"""
Unregister the caller as a provider of the specified service.
@param caller_id str: ROS caller id
@type caller_id: str
@param service: Fully-qualified name of service
@type service: str
@param service_api: API URI of service to unregister. Unregistration will only occur if current
registration matches.
@type service_api: str
@return: (code, message, numUnregistered). Number of unregistrations (either 0 or 1).
If this is zero it means that the caller was not registered as a service provider.
The call still succeeds as the intended final state is reached.
@rtype: (int, str, int)
"""
try:
self.ps_lock.acquire()
retval = self.reg_manager.unregister_service(service, caller_id, service_api)
mloginfo("-SERVICE [%s] %s %s", service, caller_id, service_api)
return retval
finally:
self.ps_lock.release()
##################################################################################
# PUBLISH/SUBSCRIBE
@apivalidate(0, ( is_topic('topic'), valid_type_name('topic_type'), is_api('caller_api')))
def registerSubscriber(self, caller_id, topic, topic_type, caller_api):
"""
Subscribe the caller to the specified topic. In addition to receiving
a list of current publishers, the subscriber will also receive notifications
of new publishers via the publisherUpdate API.
@param caller_id: ROS caller id
@type caller_id: str
@param topic str: Fully-qualified name of topic to subscribe to.
@param topic_type: Datatype for topic. Must be a package-resource name, i.e. the .msg name.
@type topic_type: str
@param caller_api: XML-RPC URI of caller node for new publisher notifications
@type caller_api: str
@return: (code, message, publishers). Publishers is a list of XMLRPC API URIs
for nodes currently publishing the specified topic.
@rtype: (int, str, [str])
"""
#NOTE: subscribers do not get to set topic type
try:
self.ps_lock.acquire()
self.reg_manager.register_subscriber(topic, caller_id, caller_api)
# ROS 1.1: subscriber can now set type if it is not already set
# - don't let '*' type squash valid typing
if not topic in self.topics_types and topic_type != rosgraph.names.ANYTYPE:
self.topics_types[topic] = topic_type
mloginfo("+SUB [%s] %s %s",topic, caller_id, caller_api)
pub_uris = self.publishers.get_apis(topic)
finally:
self.ps_lock.release()
return 1, "Subscribed to [%s]"%topic, pub_uris
@apivalidate(0, (is_topic('topic'), is_api('caller_api')))
def unregisterSubscriber(self, caller_id, topic, caller_api):
"""
Unregister the caller as a publisher of the topic.
@param caller_id: ROS caller id
@type caller_id: str
@param topic: Fully-qualified name of topic to unregister.
@type topic: str
@param caller_api: API URI of service to unregister. Unregistration will only occur if current
registration matches.
@type caller_api: str
@return: (code, statusMessage, numUnsubscribed).
If numUnsubscribed is zero it means that the caller was not registered as a subscriber.
The call still succeeds as the intended final state is reached.
@rtype: (int, str, int)
"""
try:
self.ps_lock.acquire()
retval = self.reg_manager.unregister_subscriber(topic, caller_id, caller_api)
mloginfo("-SUB [%s] %s %s",topic, caller_id, caller_api)
return retval
finally:
self.ps_lock.release()
@apivalidate(0, ( is_topic('topic'), valid_type_name('topic_type'), is_api('caller_api')))
def registerPublisher(self, caller_id, topic, topic_type, caller_api):
"""
Register the caller as a publisher the topic.
@param caller_id: ROS caller id
@type caller_id: str
@param topic: Fully-qualified name of topic to register.
@type topic: str
@param topic_type: Datatype for topic. Must be a
package-resource name, i.e. the .msg name.
@type topic_type: str
@param caller_api str: ROS caller XML-RPC API URI
@type caller_api: str
@return: (code, statusMessage, subscriberApis).
List of current subscribers of topic in the form of XMLRPC URIs.
@rtype: (int, str, [str])
"""
#NOTE: we need topic_type for getPublishedTopics.
try:
self.ps_lock.acquire()
self.reg_manager.register_publisher(topic, caller_id, caller_api)
# don't let '*' type squash valid typing
if topic_type != rosgraph.names.ANYTYPE or not topic in self.topics_types:
self.topics_types[topic] = topic_type
pub_uris = self.publishers.get_apis(topic)
sub_uris = self.subscribers.get_apis(topic)
self._notify_topic_subscribers(topic, pub_uris, sub_uris)
mloginfo("+PUB [%s] %s %s",topic, caller_id, caller_api)
sub_uris = self.subscribers.get_apis(topic)
finally:
self.ps_lock.release()
return 1, "Registered [%s] as publisher of [%s]"%(caller_id, topic), sub_uris
@apivalidate(0, (is_topic('topic'), is_api('caller_api')))
def unregisterPublisher(self, caller_id, topic, caller_api):
"""
Unregister the caller as a publisher of the topic.
@param caller_id: ROS caller id
@type caller_id: str
@param topic: Fully-qualified name of topic to unregister.
@type topic: str
@param caller_api str: API URI of service to
unregister. Unregistration will only occur if current
registration matches.
@type caller_api: str
@return: (code, statusMessage, numUnregistered).
If numUnregistered is zero it means that the caller was not registered as a publisher.
The call still succeeds as the intended final state is reached.
@rtype: (int, str, int)
"""
try:
self.ps_lock.acquire()
retval = self.reg_manager.unregister_publisher(topic, caller_id, caller_api)
if retval[VAL]:
self._notify_topic_subscribers(topic, self.publishers.get_apis(topic), self.subscribers.get_apis(topic))
mloginfo("-PUB [%s] %s %s",topic, caller_id, caller_api)
finally:
self.ps_lock.release()
return retval
##################################################################################
# GRAPH STATE APIS
@apivalidate('', (valid_name('node'),))
def lookupNode(self, caller_id, node_name):
"""
Get the XML-RPC URI of the node with the associated
name/caller_id. This API is for looking information about
publishers and subscribers. Use lookupService instead to lookup
ROS-RPC URIs.
@param caller_id: ROS caller id
@type caller_id: str
@param node: name of node to lookup
@type node: str
@return: (code, msg, URI)
@rtype: (int, str, str)
"""
try:
self.ps_lock.acquire()
node = self.reg_manager.get_node(node_name)
if node is not None:
retval = 1, "node api", node.api
else:
retval = -1, "unknown node [%s]"%node_name, ''
finally:
self.ps_lock.release()
return retval
@apivalidate(0, (empty_or_valid_name('subgraph'),))
def getPublishedTopics(self, caller_id, subgraph):
"""
Get list of topics that can be subscribed to. This does not return topics that have no publishers.
See L{getSystemState()} to get more comprehensive list.
@param caller_id: ROS caller id
@type caller_id: str
@param subgraph: Restrict topic names to match within the specified subgraph. Subgraph namespace
is resolved relative to the caller's namespace. Use '' to specify all names.
@type subgraph: str
@return: (code, msg, [[topic1, type1]...[topicN, typeN]])
@rtype: (int, str, [[str, str],])
"""
try:
self.ps_lock.acquire()
# force subgraph to be a namespace with trailing slash
if subgraph and subgraph[-1] != rosgraph.names.SEP:
subgraph = subgraph + rosgraph.names.SEP
#we don't bother with subscribers as subscribers don't report topic types. also, the intended
#use case is for subscribe-by-topic-type
retval = [[t, self.topics_types[t]] for t in self.publishers.iterkeys() if t.startswith(subgraph)]
finally:
self.ps_lock.release()
return 1, "current topics", retval
@apivalidate([])
def getTopicTypes(self, caller_id):
"""
Retrieve list topic names and their types.
@param caller_id: ROS caller id
@type caller_id: str
@rtype: (int, str, [[str,str]] )
@return: (code, statusMessage, topicTypes). topicTypes is a list of [topicName, topicType] pairs.
"""
try:
self.ps_lock.acquire()
retval = list(self.topics_types.items())
finally:
self.ps_lock.release()
return 1, "current system state", retval
@apivalidate([[],[], []])
def getSystemState(self, caller_id):
"""
Retrieve list representation of system state (i.e. publishers, subscribers, and services).
@param caller_id: ROS caller id
@type caller_id: str
@rtype: (int, str, [[str,[str]], [str,[str]], [str,[str]]])
@return: (code, statusMessage, systemState).
System state is in list representation::
[publishers, subscribers, services].
publishers is of the form::
[ [topic1, [topic1Publisher1...topic1PublisherN]] ... ]
subscribers is of the form::
[ [topic1, [topic1Subscriber1...topic1SubscriberN]] ... ]
services is of the form::
[ [service1, [service1Provider1...service1ProviderN]] ... ]
"""
edges = []
try:
self.ps_lock.acquire()
retval = [r.get_state() for r in (self.publishers, self.subscribers, self.services)]
finally:
self.ps_lock.release()
return 1, "current system state", retval
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/__init__.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
from .main import rosmaster_main
from .master import DEFAULT_MASTER_PORT
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/paramserver.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from threading import RLock
from rosgraph.names import ns_join, GLOBALNS, SEP, is_global, is_private, canonicalize_name
import os
import json
def _get_param_names(names, key, d):
"""
helper recursive routine for getParamNames()
@param names: list of param names to append to
@type names: [str]
@param d: parameter tree node
@type d: dict
@param key: parameter key for tree node d
@type key: str
"""
#TODOXXX
for k,v in d.items():
if type(v) == dict:
_get_param_names(names, ns_join(key, k), v)
else:
names.append(ns_join(key, k))
class ParamDictionary(object):
def __init__(self, reg_manager):
"""
ctor.
@param subscribers: parameter subscribers
@type subscribers: Registrations
"""
self.lock = RLock()
self.parameters = {}
self.reg_manager = reg_manager
self.snapshot = False
if "ROS_MASTER_SNAPSHOT" in os.environ:
try:
self.snapshot = True
self.snapshot_file = os.path.join(os.environ["ROS_ROOT"], ".master_snapshot")
with open(self.snapshot_file, "r") as f:
self.parameters = json.loads(f.read())
del self.parameters["run_id"]
except IOError:
pass
except KeyError:
pass
def get_param_names(self):
"""
Get list of all parameter names stored on this server.
@return: [code, statusMessage, parameterNameList]
@rtype: [int, str, [str]]
"""
try:
self.lock.acquire()
param_names = []
_get_param_names(param_names, '/', self.parameters)
finally:
self.lock.release()
return param_names
def search_param(self, ns, key):
"""
Search for matching parameter key for search param
key. Search for key starts at ns and proceeds upwards to
the root. As such, search_param should only be called with a
relative parameter name.
search_param's behavior is to search for the first partial match.
For example, imagine that there are two 'robot_description' parameters:
- /robot_description
- /robot_description/arm
- /robot_description/base
- /pr2/robot_description
- /pr2/robot_description/base
If I start in the namespace /pr2/foo and search for
'robot_description', search_param will match
/pr2/robot_description. If I search for 'robot_description/arm'
it will return /pr2/robot_description/arm, even though that
parameter does not exist (yet).
@param ns: namespace to begin search from.
@type ns: str
@param key: Parameter key.
@type key: str
@return: key of matching parameter or None if no matching
parameter.
@rtype: str
"""
if not key or is_private(key):
raise ValueError("invalid key")
if not is_global(ns):
raise ValueError("namespace must be global")
if is_global(key):
if self.has_param(key):
return key
else:
return None
# there are more efficient implementations, but our hiearchy
# is not very deep and this is fairly clean code to read.
# - we only search for the first namespace in the key to check for a match
key_namespaces = [x for x in key.split(SEP) if x]
key_ns = key_namespaces[0]
# - corner case: have to test initial namespace first as
# negative indices won't work with 0
search_key = ns_join(ns, key_ns)
if self.has_param(search_key):
# resolve to full key
return ns_join(ns, key)
namespaces = [x for x in ns.split(SEP) if x]
for i in range(1, len(namespaces)+1):
search_key = SEP + SEP.join(namespaces[0:-i] + [key_ns])
if self.has_param(search_key):
# we have a match on the namespace of the key, so
# compose the full key and return it
full_key = SEP + SEP.join(namespaces[0:-i] + [key])
return full_key
return None
def get_param(self, key):
"""
Get the parameter in the parameter dictionary.
@param key: parameter key
@type key: str
@return: parameter value
"""
try:
self.lock.acquire()
val = self.parameters
if key != GLOBALNS:
# split by the namespace separator, ignoring empty splits
namespaces = [x for x in key.split(SEP)[1:] if x]
for ns in namespaces:
if not type(val) == dict:
raise KeyError(val)
val = val[ns]
return val
finally:
self.lock.release()
def set_param(self, key, value, notify_task=None):
"""
Set the parameter in the parameter dictionary.
@param key: parameter key
@type key: str
@param value: parameter value
@param notify_task: function to call with
subscriber updates. updates is of the form
[(subscribers, param_key, param_value)*]. The empty dictionary
represents an unset parameter.
@type notify_task: fn(updates)
"""
try:
self.lock.acquire()
if key == GLOBALNS:
if type(value) != dict:
raise TypeError("cannot set root of parameter tree to non-dictionary")
self.parameters = value
else:
namespaces = [x for x in key.split(SEP) if x]
# - last namespace is the actual key we're storing in
value_key = namespaces[-1]
namespaces = namespaces[:-1]
d = self.parameters
# - descend tree to the node we're setting
for ns in namespaces:
if not ns in d:
new_d = {}
d[ns] = new_d
d = new_d
else:
val = d[ns]
# implicit type conversion of value to namespace
if type(val) != dict:
d[ns] = val = {}
d = val
d[value_key] = value
# ParamDictionary needs to queue updates so that the updates are thread-safe
if notify_task:
updates = compute_param_updates(self.reg_manager.param_subscribers, key, value)
if updates:
notify_task(updates)
finally:
self.lock.release()
if self.snapshot:
with open(self.snapshot_file, 'w') as f:
f.write(json.dumps(self.parameters))
def subscribe_param(self, key, registration_args):
"""
@param key: parameter key
@type key: str
@param registration_args: additional args to pass to
subscribers.register. First parameter is always the parameter
key.
@type registration_args: tuple
"""
if key != SEP:
key = canonicalize_name(key) + SEP
try:
self.lock.acquire()
# fetch parameter value
try:
val = self.get_param(key)
except KeyError:
# parameter not set yet
val = {}
self.reg_manager.register_param_subscriber(key, *registration_args)
return val
finally:
self.lock.release()
def unsubscribe_param(self, key, unregistration_args):
"""
@param key str: parameter key
@type key: str
@param unregistration_args: additional args to pass to
subscribers.unregister. i.e. unregister will be called with
(key, *unregistration_args)
@type unregistration_args: tuple
@return: return value of subscribers.unregister()
"""
if key != SEP:
key = canonicalize_name(key) + SEP
return self.reg_manager.unregister_param_subscriber(key, *unregistration_args)
def delete_param(self, key, notify_task=None):
"""
Delete the parameter in the parameter dictionary.
@param key str: parameter key
@param notify_task fn(updates): function to call with
subscriber updates. updates is of the form
[(subscribers, param_key, param_value)*]. The empty dictionary
represents an unset parameter.
"""
try:
self.lock.acquire()
if key == GLOBALNS:
raise KeyError("cannot delete root of parameter tree")
else:
# key is global, so first split is empty
namespaces = [x for x in key.split(SEP) if x]
# - last namespace is the actual key we're deleting
value_key = namespaces[-1]
namespaces = namespaces[:-1]
d = self.parameters
# - descend tree to the node we're setting
for ns in namespaces:
if type(d) != dict or not ns in d:
raise KeyError(key)
else:
d = d[ns]
if not value_key in d:
raise KeyError(key)
else:
del d[value_key]
# ParamDictionary needs to queue updates so that the updates are thread-safe
if notify_task:
updates = compute_param_updates(self.reg_manager.param_subscribers, key, {})
if updates:
notify_task(updates)
finally:
self.lock.release()
def has_param(self, key):
"""
Test for parameter existence
@param key: parameter key
@type key: str
@return: True if parameter set, False otherwise
@rtype: bool
"""
try:
# more efficient implementations are certainly possible,
# but this guarantees correctness for now
self.get_param(key)
return True
except KeyError:
return False
def _compute_all_keys(param_key, param_value, all_keys=None):
"""
Compute which subscribers should be notified based on the parameter update
@param param_key: key of updated parameter
@type param_key: str
@param param_value: value of updated parameter
@param all_keys: (internal use only) list of parameter keys
to append to for recursive calls.
@type all_keys: [str]
@return: list of parameter keys. All keys will be canonicalized with trailing slash.
@rtype: [str]
"""
if all_keys is None:
all_keys = []
for k, v in param_value.items():
new_k = ns_join(param_key, k) + SEP
all_keys.append(new_k)
if type(v) == dict:
_compute_all_keys(new_k, v, all_keys)
return all_keys
def compute_param_updates(subscribers, param_key, param_value):
"""
Compute subscribers that should be notified based on the parameter update
@param subscribers: parameter subscribers
@type subscribers: Registrations
@param param_key: parameter key
@type param_key: str
@param param_value: parameter value
@type param_value: str
"""
# logic correct for both updates and deletions
if not subscribers:
return []
# end with a trailing slash to optimize startswith check from
# needing an extra equals check
if param_key != SEP:
param_key = canonicalize_name(param_key) + SEP
# compute all the updated keys
if type(param_value) == dict:
all_keys = _compute_all_keys(param_key, param_value)
else:
all_keys = None
updates = []
# subscriber gets update if anything in the subscribed namespace is updated or if its deleted
for sub_key in subscribers.iterkeys():
ns_key = sub_key
if ns_key[-1] != SEP:
ns_key = sub_key + SEP
if param_key.startswith(ns_key):
node_apis = subscribers[sub_key]
updates.append((node_apis, param_key, param_value))
elif all_keys is not None and ns_key.startswith(param_key) \
and not sub_key in all_keys:
# parameter was deleted
node_apis = subscribers[sub_key]
updates.append((node_apis, sub_key, {}))
# add updates for exact matches within tree
if all_keys is not None:
# #586: iterate over parameter tree for notification
for key in all_keys:
if key in subscribers:
# compute actual update value
sub_key = key[len(param_key):]
namespaces = [x for x in sub_key.split(SEP) if x]
val = param_value
for ns in namespaces:
val = val[ns]
updates.append((subscribers[key], key, val))
return updates
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/master.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
ROS Master.
This module integrates the lower-level implementation modules into a
single interface for running and stopping the ROS Master.
"""
import logging
import time
import rosgraph.xmlrpc
import rosmaster.master_api
from rosmaster.broadcast_handler import BroadcastHandler
DEFAULT_MASTER_PORT=11311 #default port for master's to bind to
class Master(object):
def __init__(self, port=DEFAULT_MASTER_PORT, num_workers=rosmaster.master_api.NUM_WORKERS):
self.port = port
self.num_workers = num_workers
def start(self):
"""
Start the ROS Master.
"""
self.handler = None
self.master_node = None
self.uri = None
handler = rosmaster.master_api.ROSMasterHandler(self.num_workers)
master_node = rosgraph.xmlrpc.XmlRpcNode(self.port, handler)
master_node.start()
# poll for initialization
while not master_node.uri:
time.sleep(0.0001)
# save fields
self.handler = handler
self.master_node = master_node
self.uri = master_node.uri
self.bm = BroadcastHandler(handler)
logging.getLogger('rosmaster.master').info("Master initialized: port[%s], uri[%s]", self.port, self.uri)
def ok(self):
if self.master_node is not None:
return self.master_node.handler._ok()
else:
return False
def stop(self):
if self.master_node is not None:
self.master_node.shutdown('Master.stop')
self.master_node = None
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/broadcast_handler.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2017, The Apollo Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
import os
import json
import time
import socket
import struct
import decimal
import logging
import traceback
import threading
import functools
import rospy.core
from rospy.core import signal_shutdown
from rospy.impl.registration import Registration
from rospy.impl.registration import get_topic_manager
from rospy.impl.registration import get_service_manager
from rospy.impl.registration import get_node_handler
from rosgraph.network import parse_http_host_and_port,get_host_name
import sys
env = os.environ.get('LD_LIBRARY_PATH')
for sub_path in env.split(':'):
sys.path.append(sub_path)
from rospy.impl import participant
TIMESTAMP = 'timestamp'
NODE_NAME = 'node_name'
XMLRPC_URI = 'xmlrpc_uri'
REQUEST_TYPE = 'request_type'
NODE_TIME = "node_time"
TOPIC_NAME = "topic_name"
TOPIC_TYPE = "topic_type"
TOPIC_URI = "topic_uri"
SERVICE_NAME = "service_name"
SERVICE_TYPE = "service_type"
SERVICE_URI = "service_uri"
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def byteify(input):
"""
Convert unicode to str.
"""
if isinstance(input, dict):
return {byteify(key): byteify(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
class BroadcastHandler(object):
"""
BroadcastHandler.
"""
__metaclass__ = Singleton
def __init__(self, handler):
"""
brief info for: __init__
"""
super(BroadcastHandler, self).__init__()
self._logger = logging.getLogger(__name__)
self._logger.setLevel(logging.INFO)
self.callback = ["registerPublisher",
"unregisterPublisher",
"registerSubscriber",
"unregisterSubscriber",
"registerService",
"unregisterService",
"lookupService",
"getTopicTypes",
"lookupNode",
]
self._handler = handler
self._name = "rosmaster"
self._participant = participant.Participant(self._name)
self._participant.init_py()
self._broardcast_manager_thread = threading.Thread(
target=self.run, args=())
self._broardcast_manager_thread.setDaemon(True)
self._broardcast_manager_thread.start()
def run(self):
"""
brief info for: thread run method
"""
self._logger.debug("starting broadcast_manager!")
while True:
try:
msg = self._participant.read_msg()
if msg is None:
continue
if(len(msg) > 0):
data = self._unpack_msg(msg.strip())
self._logger.debug("recv data: %s " % data)
try:
cb = '_' + data[REQUEST_TYPE] + "Callback"
func = getattr(self, cb)
func(data)
except AttributeError:
pass
else:
time.sleep(0.005)
except Exception as e:
self._logger.error("broadcast_manager thread error is %s" % e)
finally:
pass
def getUri(self, caller_id):
"""
getUri
"""
return 1, "", self._uri
def getPid(self, caller_id):
"""
Get the PID of this server
"""
return 1, "", os.getpid()
def _registerPublisherCallback(self, data):
name = data[NODE_NAME]
topic = data[TOPIC_NAME]
datatype = data[TOPIC_TYPE]
uri = data[XMLRPC_URI]
self._handler.registerPublisher(name, topic, datatype, uri)
def _unregisterPublisherCallback(self, data):
name = data[NODE_NAME]
topic = data[TOPIC_NAME]
uri = data[TOPIC_URI]
self._handler.unregisterPublisher(name, topic, uri)
def _registerSubscriberCallback(self, data):
name = data[NODE_NAME]
topic = data[TOPIC_NAME]
datatype = data[TOPIC_TYPE]
uri = data[XMLRPC_URI]
self._handler.registerSubscriber(name, topic, datatype, uri)
def _unregisterSubscriberCallback(self, data):
name = data[NODE_NAME]
topic = data[TOPIC_NAME]
uri = data[TOPIC_URI]
self._handler.unregisterSubscriber(name, topic, uri)
def _registerServiceCallback(self, data):
name = data[NODE_NAME]
service_name = data[SERVICE_NAME]
service_uri = data[SERVICE_URI]
uri = data[XMLRPC_URI]
self._handler.registerService(name, service_name, service_uri, uri)
def _unregisterServiceCallback(self, data):
name = data[NODE_NAME]
service_name = data[SERVICE_NAME]
service_uri = data[SERVICE_URI]
self._handler.unregisterService(name, service_name, service_uri)
def _send(self, data):
"""
brief info for: Get _master_handler internal dict stuct according to dict_type
"""
self._participant.send(data)
def _recv(self, size=1024):
"""
brief info for: Get _master_handler internal dict stuct according to dict_type
"""
msg = addr = None
try:
msg, addr = self._sock.recvfrom(size)
except Exception as e:
self._logger.error("socket recv error is %s" % e)
self._logger.error(traceback.format_exc())
finally:
pass
return msg, addr
def _unpack_msg(self, msg):
try:
data = json.loads(msg, object_hook=byteify)
except Exception as e:
self._logger.error("parse json failed! %s" % e)
return data
def _pack_msg(self, data):
return json.dumps(data)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/exceptions.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Exceptions for rosmaster package.
"""
class InternalException(Exception): pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/registrations.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
from rosmaster.util import remove_server_proxy
from rosmaster.util import xmlrpcapi
import rosmaster.exceptions
"""Data structures for representing registration data in the Master"""
class NodeRef(object):
"""
Container for node registration information. Used in master's
self.nodes data structure. This is effectively a reference
counter for the node registration information: when the
subscriptions and publications are empty the node registration can
be deleted.
"""
def __init__(self, id, api):
"""
ctor
@param api str: node XML-RPC API
"""
self.id = id
self.api = api
self.param_subscriptions = []
self.topic_subscriptions = []
self.topic_publications = []
self.services = []
def clear(self):
"""
Delete all state from this NodeRef except for the api location
"""
self.param_subscriptions = []
self.topic_subscriptions = []
self.topic_publications = []
self.services = []
def is_empty(self):
"""
@return: True if node has no active registrations
"""
return sum((len(x) for x in
[self.param_subscriptions,
self.topic_subscriptions,
self.topic_publications,
self.services,])) == 0
def add(self, type_, key):
if type_ == Registrations.TOPIC_SUBSCRIPTIONS:
if not key in self.topic_subscriptions:
self.topic_subscriptions.append(key)
elif type_ == Registrations.TOPIC_PUBLICATIONS:
if not key in self.topic_publications:
self.topic_publications.append(key)
elif type_ == Registrations.SERVICE:
if not key in self.services:
self.services.append(key)
elif type_ == Registrations.PARAM_SUBSCRIPTIONS:
if not key in self.param_subscriptions:
self.param_subscriptions.append(key)
else:
raise rosmaster.exceptions.InternalException("internal bug")
def remove(self, type_, key):
if type_ == Registrations.TOPIC_SUBSCRIPTIONS:
if key in self.topic_subscriptions:
self.topic_subscriptions.remove(key)
elif type_ == Registrations.TOPIC_PUBLICATIONS:
if key in self.topic_publications:
self.topic_publications.remove(key)
elif type_ == Registrations.SERVICE:
if key in self.services:
self.services.remove(key)
elif type_ == Registrations.PARAM_SUBSCRIPTIONS:
if key in self.param_subscriptions:
self.param_subscriptions.remove(key)
else:
raise rosmaster.exceptions.InternalException("internal bug")
# NOTE: I'm not terribly happy that this task has leaked into the data model. need
# to refactor to get this back into masterslave.
def shutdown_node_task(api, caller_id, reason):
"""
Method to shutdown another ROS node. Generally invoked within a
separate thread as this is used to cleanup hung nodes.
@param api: XML-RPC API of node to shutdown
@type api: str
@param caller_id: name of node being shutdown
@type caller_id: str
@param reason: human-readable reason why node is being shutdown
@type reason: str
"""
try:
xmlrpcapi(api).shutdown('/master', reason)
except:
pass #expected in many common cases
remove_server_proxy(api)
class Registrations(object):
"""
All calls may result in access/modifications to node registrations
dictionary, so be careful to guarantee appropriate thread-safeness.
Data structure for storing a set of registrations (e.g. publications, services).
The underlying data storage is the same except for services, which have the
constraint that only one registration may be active for a given key.
"""
TOPIC_SUBSCRIPTIONS = 1
TOPIC_PUBLICATIONS = 2
SERVICE = 3
PARAM_SUBSCRIPTIONS = 4
def __init__(self, type_):
"""
ctor.
@param type_: one of [ TOPIC_SUBSCRIPTIONS,
TOPIC_PUBLICATIONS, SERVICE, PARAM_SUBSCRIPTIONS ]
@type type_: int
"""
if not type_ in [
Registrations.TOPIC_SUBSCRIPTIONS,
Registrations.TOPIC_PUBLICATIONS,
Registrations.SERVICE,
Registrations.PARAM_SUBSCRIPTIONS ]:
raise rosmaster.exceptions.InternalException("invalid registration type: %s"%type_)
self.type = type_
## { key: [(caller_id, caller_api)] }
self.map = {}
self.service_api_map = None
def __bool__(self):
"""
@return: True if there are registrations
"""
return len(self.map) != 0
def __nonzero__(self):
"""
@return: True if there are registrations
"""
return len(self.map) != 0
def iterkeys(self):
"""
Iterate over registration keys
@return: iterator for registration keys
"""
return self.map.keys()
def get_service_api(self, service):
"""
Lookup service API URI. NOTE: this should only be valid if type==SERVICE as
service Registrations instances are the only ones that track service API URIs.
@param service: service name
@type service: str
@return str: service_api for registered key or None if
registration is no longer valid.
@type: str
"""
if self.service_api_map and service in self.service_api_map:
caller_id, service_api = self.service_api_map[service]
return service_api
return None
def get_apis(self, key):
"""
Only valid if self.type != SERVICE.
@param key: registration key (e.g. topic/service/param name)
@type key: str
@return: caller_apis for registered key, empty list if registration is not valid
@rtype: [str]
"""
return [api for _, api in self.map.get(key, [])]
def __contains__(self, key):
"""
Emulate mapping type for has_key()
"""
return key in self.map
def __getitem__(self, key):
"""
@param key: registration key (e.g. topic/service/param name)
@type key: str
@return: (caller_id, caller_api) for registered
key, empty list if registration is not valid
@rtype: [(str, str),]
"""
# unlike get_apis, returns the caller_id to prevent any race
# conditions that can occur if caller_id/caller_apis change
# due to a new node.
return self.map.get(key, [])
def has_key(self, key):
"""
@param key: registration key (e.g. topic/service/param name)
@type key: str
@return: True if key is registered
@rtype: bool
"""
return key in self.map
def get_state(self):
"""
@return: state in getSystemState()-friendly format [ [key, [callerId1...callerIdN]] ... ]
@rtype: [str, [str]...]
"""
retval = []
for k in self.map.keys():
retval.append([k, [id for id, _ in self.map[k]]])
return retval
def register(self, key, caller_id, caller_api, service_api=None):
"""
Add caller_id into the map as a provider of the specified
service (key). caller_id must not have been previously
registered with a different caller_api.
Subroutine for managing provider map data structure (essentially a multimap).
@param key: registration key (e.g. topic/service/param name)
@type key: str
@param caller_id: caller_id of provider
@type caller_id: str
@param caller_api: API URI of provider
@type caller_api: str
@param service_api: (keyword) ROS service API URI if registering a service
@type service_api: str
"""
map = self.map
if key in map and not service_api:
providers = map[key]
if not (caller_id, caller_api) in providers:
providers.append((caller_id, caller_api))
else:
map[key] = providers = [(caller_id, caller_api)]
if service_api:
if self.service_api_map is None:
self.service_api_map = {}
self.service_api_map[key] = (caller_id, service_api)
elif self.type == Registrations.SERVICE:
raise rosmaster.exceptions.InternalException("service_api must be specified for Registrations.SERVICE")
def unregister_all(self, caller_id):
"""
Remove all registrations associated with caller_id
@param caller_id: caller_id of provider
@type caller_id: str
"""
map = self.map
# fairly expensive
dead_keys = []
for key in map:
providers = map[key]
# find all matching entries
to_remove = [(id, api) for id, api in providers if id == caller_id]
# purge them
for r in to_remove:
providers.remove(r)
if not providers:
dead_keys.append(key)
for k in dead_keys:
del self.map[k]
if self.type == Registrations.SERVICE and self.service_api_map:
del dead_keys[:]
for key, val in self.service_api_map.items():
if val[0] == caller_id:
dead_keys.append(key)
for k in dead_keys:
del self.service_api_map[k]
def unregister(self, key, caller_id, caller_api, service_api=None):
"""
Remove caller_id from the map as a provider of the specified service (key).
Subroutine for managing provider map data structure, essentially a multimap
@param key: registration key (e.g. topic/service/param name)
@type key: str
@param caller_id: caller_id of provider
@type caller_id: str
@param caller_api: API URI of provider
@type caller_api: str
@param service_api: (keyword) ROS service API URI if registering a service
@type service_api: str
@return: for ease of master integration, directly returns unregister value for
higher-level XMLRPC API. val is the number of APIs unregistered (0 or 1)
@rtype: code, msg, val
"""
# if we are unregistering a topic, validate against the caller_api
if service_api:
# validate against the service_api
if self.service_api_map is None:
return 1, "[%s] is not a provider of [%s]"%(caller_id, key), 0
if self.service_api_map.get(key, None) != (caller_id, service_api):
return 1, "[%s] is no longer the current service api handle for [%s]"%(service_api, key), 0
else:
del self.service_api_map[key]
del self.map[key]
# caller_api is None for unregister service, so we can't validate as well
return 1, "Unregistered [%s] as provider of [%s]"%(caller_id, key), 1
elif self.type == Registrations.SERVICE:
raise rosmaster.exceptions.InternalException("service_api must be specified for Registrations.SERVICE")
else:
providers = self.map.get(key, [])
if (caller_id, caller_api) in providers:
providers.remove((caller_id, caller_api))
if not providers:
del self.map[key]
return 1, "Unregistered [%s] as provider of [%s]"%(caller_id, key), 1
else:
return 1, "[%s] is not a known provider of [%s]"%(caller_id, key), 0
class RegistrationManager(object):
"""
Stores registrations for Master.
RegistrationManager is not threadsafe, so access must be externally locked as appropriate
"""
def __init__(self, thread_pool):
"""
ctor.
@param thread_pool: thread pool for queueing tasks
@type thread_pool: ThreadPool
"""
self.nodes = {}
self.thread_pool = thread_pool
self.publishers = Registrations(Registrations.TOPIC_PUBLICATIONS)
self.subscribers = Registrations(Registrations.TOPIC_SUBSCRIPTIONS)
self.services = Registrations(Registrations.SERVICE)
self.param_subscribers = Registrations(Registrations.PARAM_SUBSCRIPTIONS)
def reverse_lookup(self, caller_api):
"""
Get a NodeRef by caller_api
@param caller_api: caller XML RPC URI
@type caller_api: str
@return: nodes that declare caller_api as their
API. 99.9% of the time this should only be one node, but we
allow for multiple matches as the master API does not restrict
this.
@rtype: [NodeRef]
"""
matches = [n for n in self.nodes.items() if n.api == caller_api]
if matches:
return matches
def get_node(self, caller_id):
return self.nodes.get(caller_id, None)
def _register(self, r, key, caller_id, caller_api, service_api=None):
# update node information
node_ref, changed = self._register_node_api(caller_id, caller_api)
node_ref.add(r.type, key)
# update pub/sub/service indicies
if changed:
self.publishers.unregister_all(caller_id)
self.subscribers.unregister_all(caller_id)
self.services.unregister_all(caller_id)
self.param_subscribers.unregister_all(caller_id)
r.register(key, caller_id, caller_api, service_api)
def _unregister(self, r, key, caller_id, caller_api, service_api=None):
node_ref = self.nodes.get(caller_id, None)
if node_ref != None:
retval = r.unregister(key, caller_id, caller_api, service_api)
# check num removed field, if 1, unregister is valid
if retval[2] == 1:
node_ref.remove(r.type, key)
if node_ref.is_empty():
del self.nodes[caller_id]
else:
retval = 1, "[%s] is not a registered node"%caller_id, 0
return retval
def register_service(self, service, caller_id, caller_api, service_api):
"""
Register service provider
@return: None
"""
self._register(self.services, service, caller_id, caller_api, service_api)
def register_publisher(self, topic, caller_id, caller_api):
"""
Register topic publisher
@return: None
"""
self._register(self.publishers, topic, caller_id, caller_api)
def register_subscriber(self, topic, caller_id, caller_api):
"""
Register topic subscriber
@return: None
"""
self._register(self.subscribers, topic, caller_id, caller_api)
def register_param_subscriber(self, param, caller_id, caller_api):
"""
Register param subscriber
@return: None
"""
self._register(self.param_subscribers, param, caller_id, caller_api)
def unregister_service(self, service, caller_id, service_api):
caller_api = None
return self._unregister(self.services, service, caller_id, caller_api, service_api)
def unregister_subscriber(self, topic, caller_id, caller_api):
return self._unregister(self.subscribers, topic, caller_id, caller_api)
def unregister_publisher(self, topic, caller_id, caller_api):
return self._unregister(self.publishers, topic, caller_id, caller_api)
def unregister_param_subscriber(self, param, caller_id, caller_api):
return self._unregister(self.param_subscribers, param, caller_id, caller_api)
def _register_node_api(self, caller_id, caller_api):
"""
@param caller_id: caller_id of provider
@type caller_id: str
@param caller_api: caller_api of provider
@type caller_api: str
@return: (registration_information, changed_registration). changed_registration is true if
caller_api is differet than the one registered with caller_id
@rtype: (NodeRef, bool)
"""
node_ref = self.nodes.get(caller_id, None)
bumped_api = None
if node_ref is not None:
if node_ref.api == caller_api:
return node_ref, False
else:
bumped_api = node_ref.api
self.thread_pool.queue_task(bumped_api, shutdown_node_task,
(bumped_api, caller_id, "new node registered with same name"))
node_ref = NodeRef(caller_id, caller_api)
self.nodes[caller_id] = node_ref
return (node_ref, bumped_api != None)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmaster/src/rosmaster/main.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""Command-line handler for ROS zenmaster (Python Master)"""
import logging
import os
import sys
import time
import optparse
import rosmaster.master
from rosmaster.master_api import NUM_WORKERS
def configure_logging():
"""
Setup filesystem logging for the master
"""
filename = 'master.log'
# #988 __log command-line remapping argument
import rosgraph.names
import rosgraph.roslogging
mappings = rosgraph.names.load_mappings(sys.argv)
if '__log' in mappings:
logfilename_remap = mappings['__log']
filename = os.path.abspath(logfilename_remap)
_log_filename = rosgraph.roslogging.configure_logging('rosmaster', logging.DEBUG, filename=filename)
def rosmaster_main(argv=sys.argv, stdout=sys.stdout, env=os.environ):
parser = optparse.OptionParser(usage="usage: zenmaster [options]")
parser.add_option("--core",
dest="core", action="store_true", default=False,
help="run as core")
parser.add_option("-p", "--port",
dest="port", default=0,
help="override port", metavar="PORT")
parser.add_option("-w", "--numworkers",
dest="num_workers", default=NUM_WORKERS, type=int,
help="override number of worker threads", metavar="NUM_WORKERS")
parser.add_option("-t", "--timeout",
dest="timeout",
help="override the socket connection timeout (in seconds).", metavar="TIMEOUT")
options, args = parser.parse_args(argv[1:])
# only arg that zenmaster supports is __log remapping of logfilename
for arg in args:
if not arg.startswith('__log:='):
parser.error("unrecognized arg: %s"%arg)
configure_logging()
port = rosmaster.master.DEFAULT_MASTER_PORT
if options.port:
port = int(options.port)
if not options.core:
print("""
ACHTUNG WARNING ACHTUNG WARNING ACHTUNG
WARNING ACHTUNG WARNING ACHTUNG WARNING
Standalone zenmaster has been deprecated, please use 'roscore' instead
ACHTUNG WARNING ACHTUNG WARNING ACHTUNG
WARNING ACHTUNG WARNING ACHTUNG WARNING
""")
logger = logging.getLogger("rosmaster.main")
logger.info("initialization complete, waiting for shutdown")
if options.timeout is not None and float(options.timeout) >= 0.0:
logger.info("Setting socket timeout to %s" % options.timeout)
import socket
socket.setdefaulttimeout(float(options.timeout))
try:
logger.info("Starting ROS Master Node")
master = rosmaster.master.Master(port, options.num_workers)
master.start()
import time
while master.ok():
time.sleep(.1)
except KeyboardInterrupt:
logger.info("keyboard interrupt, will exit")
finally:
logger.info("stopping master...")
master.stop()
if __name__ == "__main__":
main()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(roscpp)
if(NOT WIN32)
set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra")
endif()
find_package(catkin REQUIRED COMPONENTS
cpp_common message_generation rosconsole roscpp_serialization roscpp_traits rosgraph_msgs rostime std_msgs xmlrpcpp
)
set(CMAKE_CXX_FLAGS "-g -std=c++11 ${CMAKE_CXX_FLAGS}")
catkin_package_xml()
# split version in parts and pass to extra file
string(REPLACE "." ";" roscpp_VERSION_LIST "${roscpp_VERSION}")
list(LENGTH roscpp_VERSION_LIST _count)
if(NOT _count EQUAL 3)
message(FATAL_ERROR "roscpp version '${roscpp_VERSION}' does not match 'MAJOR.MINOR.PATCH' pattern")
endif()
list(GET roscpp_VERSION_LIST 0 roscpp_VERSION_MAJOR)
list(GET roscpp_VERSION_LIST 1 roscpp_VERSION_MINOR)
list(GET roscpp_VERSION_LIST 2 roscpp_VERSION_PATCH)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/include/ros/common.h.in ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_INCLUDE_DESTINATION}/ros/common.h)
find_package(Boost REQUIRED COMPONENTS signals filesystem system)
include_directories(include ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_INCLUDE_DESTINATION}/ros ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
add_message_files(
DIRECTORY msg
FILES Logger.msg SharedMemoryHeader.msg
)
add_service_files(
DIRECTORY srv
FILES Empty.srv GetLoggers.srv SetLoggerLevel.srv SharedMemoryRegisterSegment.srv
)
generate_messages()
set(PTHREAD_LIB "")
find_package(Threads)
if(CMAKE_THREAD_LIBS_INIT)
string(LENGTH ${CMAKE_THREAD_LIBS_INIT} _length)
if(_length GREATER 2)
string(SUBSTRING ${CMAKE_THREAD_LIBS_INIT} 0 2 _prefix)
if(${_prefix} STREQUAL "-l")
math(EXPR _rest_len "${_length} - 2")
string(SUBSTRING ${CMAKE_THREAD_LIBS_INIT} 2 ${_rest_len} PTHREAD_LIB)
endif()
endif()
endif()
catkin_package(
INCLUDE_DIRS include ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_INCLUDE_DESTINATION}/ros
LIBRARIES roscpp ${PTHREAD_LIB}
CATKIN_DEPENDS cpp_common message_runtime rosconsole roscpp_serialization roscpp_traits rosgraph_msgs rostime std_msgs xmlrpcpp
DEPENDS Boost
)
include(CheckIncludeFiles)
include(CheckFunctionExists)
# Not everybody has <ifaddrs.h> (e.g., embedded arm-linux)
CHECK_INCLUDE_FILES(ifaddrs.h HAVE_IFADDRS_H)
# Not everybody has trunc (e.g., Windows, embedded arm-linux)
CHECK_FUNCTION_EXISTS(trunc HAVE_TRUNC)
# Output test results to config.h
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/libros/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(FASTRTPS_INCLUDE_DIR "${FASTRTPS_PATH}/include")
set(FASTRTPS_LIBRARY_DIR "${FASTRTPS_PATH}/lib")
set(FASTRTPS_GEN "${FASTRTPS_PATH}/bin/fastrtpsgen")
include_directories(include ${FASTRTPS_INCLUDE_DIR})
link_directories(
${FASTRTPS_LIBRARY_DIR}
)
SET(DISCOVERY_IDL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/src/libros/discovery/MetaMessagePubSubTypes.cxx ${CMAKE_CURRENT_SOURCE_DIR}/src/libros/discovery/MetaMessage.cxx)
#ADD_CUSTOM_COMMAND(
# OUTPUT ${DISCOVERY_IDL_SRCS}
# COMMAND ${FASTRTPS_GEN} ${CMAKE_CURRENT_SOURCE_DIR}/src/libros/discovery/MetaMessage.idl -d ${CMAKE_CURRENT_SOURCE_DIR}/src/libros/discovery/}
# DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/libros/discovery/MetaMessage.idl
#)
# Add discovery for python tools
add_library(discovery SHARED
src/libros/discovery/participant.cpp
${DISCOVERY_IDL_SRCS}
)
target_link_libraries(discovery fastcdr fastrtps -fPIC)
add_library(roscpp
src/libros/master.cpp
src/libros/network.cpp
src/libros/subscriber.cpp
src/libros/common.cpp
src/libros/publisher_link.cpp
src/libros/service_publication.cpp
src/libros/connection.cpp
src/libros/single_subscriber_publisher.cpp
src/libros/param.cpp
src/libros/service_server.cpp
src/libros/wall_timer.cpp
src/libros/xmlrpc_manager.cpp
src/libros/publisher.cpp
src/libros/timer.cpp
src/libros/io.cpp
src/libros/names.cpp
src/libros/topic.cpp
src/libros/topic_manager.cpp
src/libros/poll_manager.cpp
src/libros/publication.cpp
src/libros/statistics.cpp
src/libros/intraprocess_subscriber_link.cpp
src/libros/intraprocess_publisher_link.cpp
src/libros/callback_queue.cpp
src/libros/service_server_link.cpp
src/libros/service_client.cpp
src/libros/node_handle.cpp
src/libros/connection_manager.cpp
src/libros/file_log.cpp
src/libros/transport/transport.cpp
src/libros/transport/transport_udp.cpp
src/libros/transport/transport_tcp.cpp
src/libros/subscriber_link.cpp
src/libros/service_client_link.cpp
src/libros/transport_publisher_link.cpp
src/libros/transport_subscriber_link.cpp
src/libros/service_manager.cpp
src/libros/rosout_appender.cpp
src/libros/init.cpp
src/libros/subscription.cpp
src/libros/subscription_queue.cpp
src/libros/spinner.cpp
src/libros/internal_timer_manager.cpp
src/libros/message_deserializer.cpp
src/libros/poll_set.cpp
src/libros/service.cpp
src/libros/this_node.cpp
src/libros/shm_manager.cpp
src/libros/sharedmem_transport/sharedmem_block.cpp
src/libros/sharedmem_transport/sharedmem_publisher_impl.cpp
src/libros/sharedmem_transport/sharedmem_segment.cpp
src/libros/sharedmem_transport/sharedmem_util.cpp
src/libros/broadcast_manager.cpp
src/libros/discovery/participant.cpp
${DISCOVERY_IDL_SRCS}
)
add_dependencies(roscpp ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
add_dependencies(roscpp roscpp_gencpp rosgraph_msgs_gencpp metric_msgs_gencpp std_msgs_gencpp)
#add_definitions(-std=c++0x -g)
target_link_libraries(roscpp
${catkin_LIBRARIES}
${Boost_LIBRARIES}
fastrtps
fastcdr
yaml-cpp
-lrt
)
add_library(shm_manager SHARED
src/libros/sharedmem_transport/sharedmem_util.cpp
src/libros/sharedmem_transport/sharedmem_block.cpp
src/libros/sharedmem_transport/sharedmem_segment.cpp
)
add_dependencies(shm_manager roscpp)
target_link_libraries(shm_manager ${catkin_LIBRARIES} ${Boost_LIBRARIES} roscpp -fPIC)
#explicitly install library and includes
install(TARGETS roscpp
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
install(TARGETS shm_manager
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
install(DIRECTORY include/
DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h")
install(FILES ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_INCLUDE_DESTINATION}/ros/common.h
DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}/ros)
# install legacy infrastructure needed by rosbuild
install(FILES rosbuild/roscpp.cmake
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild)
catkin_install_python(PROGRAMS
rosbuild/scripts/genmsg_cpp.py
rosbuild/scripts/gensrv_cpp.py
rosbuild/scripts/msg_gen.py
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild/scripts)
install(FILES lib/_participant.so
DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
install(TARGETS discovery
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
message("${CATKIN_GLOBAL_ETC_DESTINATION}")
install(FILES transport_mode.yaml
DESTINATION ${CATKIN_GLOBAL_ETC_DESTINATION}/ros)
#node test
add_executable(talker test_node/talker.cpp)
add_executable(listener test_node/listener.cpp)
target_link_libraries(talker ${catkin_LIBRARIES} ${PROJECT_NAME})
target_link_libraries(listener ${catkin_LIBRARIES} ${PROJECT_NAME})
install(TARGETS talker
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
install(TARGETS listener
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
#unit test
catkin_add_gtest(test_shm
test/test_shm.cpp
src/libros/sharedmem_transport/sharedmem_block.cpp
src/libros/sharedmem_transport/sharedmem_publisher_impl.cpp
src/libros/sharedmem_transport/sharedmem_segment.cpp
src/libros/sharedmem_transport/sharedmem_util.cpp)
target_link_libraries(test_shm
${catkin_LIBRARIES}
${Boost_LIBRARIES}
roscpp
gtest)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/package.xml | <package>
<name>roscpp</name>
<version>1.11.21</version>
<description>
roscpp is a C++ implementation of ROS. It provides
a <a href="http://www.ros.org/wiki/Client%20Libraries">client
library</a> that enables C++ programmers to quickly interface with
ROS <a href="http://ros.org/wiki/Topics">Topics</a>,
<a href="http://ros.org/wiki/Services">Services</a>,
and <a href="http://ros.org/wiki/Parameter Server">Parameters</a>.
roscpp is the most widely used ROS client library and is designed to
be the high-performance library for ROS.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/roscpp</url>
<author>Morgan Quigley</author>
<author>Josh Faust</author>
<author>Brian Gerkey</author>
<author>Troy Straszheim</author>
<buildtool_depend version_gte="0.5.78">catkin</buildtool_depend>
<build_depend version_gte="0.3.17">cpp_common</build_depend>
<build_depend>message_generation</build_depend>
<build_depend>pkg-config</build_depend>
<build_depend>rosconsole</build_depend>
<build_depend>roscpp_serialization</build_depend>
<build_depend version_gte="0.3.17">roscpp_traits</build_depend>
<build_depend version_gte="1.10.3">rosgraph_msgs</build_depend>
<build_depend>roslang</build_depend>
<build_depend>rostime</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>xmlrpcpp</build_depend>
<run_depend version_gte="0.3.17">cpp_common</run_depend>
<run_depend>message_runtime</run_depend>
<run_depend>rosconsole</run_depend>
<run_depend>roscpp_serialization</run_depend>
<run_depend version_gte="0.3.17">roscpp_traits</run_depend>
<run_depend version_gte="1.10.3">rosgraph_msgs</run_depend>
<run_depend>rostime</run_depend>
<run_depend>std_msgs</run_depend>
<run_depend>xmlrpcpp</run_depend>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/transport_mode.yaml | ############################################################
#
# ### transport_mode ###
# Choose transport mode, in which nodes communicate with each other.
#
# 0: shared memory, default
# 1: socket
#
# ### topic_white_list ###
# Exclude some topics, which will be transported in socket mode.
# This key takes effect only when transport_mode is 0.
#
############################################################
transport_mode: 0
topic_white_list: ["/shm_sample1", "/shm_sample2"] | 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/roscpp/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-roscpp-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package roscpp
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
* fix UDP block number when EAGAIN or EWOULDBLOCK (`#957 <https://github.com/ros/ros_comm/issues/957>`_)
* improve stacktrace for exceptions thrown in callbacks (`#811 <https://github.com/ros/ros_comm/pull/811>`_)
1.11.20 (2016-06-27)
--------------------
* fix segfault if connection fails (`#807 <https://github.com/ros/ros_comm/pull/807>`_)
1.11.19 (2016-04-18)
--------------------
* use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_)
1.11.18 (2016-03-17)
--------------------
* fix CMake warning about non-existing targets
1.11.17 (2016-03-11)
--------------------
* fix order of argument in SubscriberLink interface to match actual implemenation (`#701 <https://github.com/ros/ros_comm/issues/701>`_)
* add method for getting all the parameters from the parameter server as implemented in the rospy client (`#739 <https://github.com/ros/ros_comm/issues/739>`_)
* use boost::make_shared instead of new for constructing boost::shared_ptr (`#740 <https://github.com/ros/ros_comm/issues/740>`_)
* fix max elements param for statistics window (`#750 <https://github.com/ros/ros_comm/issues/750>`_)
* improve NodeHandle constructor documentation (`#692 <https://github.com/ros/ros_comm/issues/692>`_)
1.11.16 (2015-11-09)
--------------------
* add getROSArg function (`#694 <https://github.com/ros/ros_comm/pull/694>`_)
1.11.15 (2015-10-13)
--------------------
* fix crash in onRetryTimer() callback (`#577 <https://github.com/ros/ros_comm/issues/577>`_)
1.11.14 (2015-09-19)
--------------------
* add optional reset argument to Timer::setPeriod() (`#590 <https://github.com/ros/ros_comm/issues/590>`_)
* add getParam() and getParamCached() for float (`#621 <https://github.com/ros/ros_comm/issues/621>`_, `#623 <https://github.com/ros/ros_comm/issues/623>`_)
* use explicit bool cast to compile with C++11 (`#632 <https://github.com/ros/ros_comm/pull/632>`_)
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
* fix memory leak in transport constructor (`#570 <https://github.com/ros/ros_comm/pull/570>`_)
* fix computation of stddev in statistics (`#556 <https://github.com/ros/ros_comm/pull/556>`_)
* fix empty connection header topic (`#543 <https://github.com/ros/ros_comm/issues/543>`_)
* alternative API to get parameter values (`#592 <https://github.com/ros/ros_comm/pull/592>`_)
* add getCached() for float parameters (`#584 <https://github.com/ros/ros_comm/pull/584>`_)
1.11.10 (2014-12-22)
--------------------
* fix various defects reported by coverity
* fix comment (`#529 <https://github.com/ros/ros_comm/issues/529>`_)
* improve Android support (`#518 <https://github.com/ros/ros_comm/pull/518>`_)
1.11.9 (2014-08-18)
-------------------
* add accessor to expose whether service is persistent (`#489 <https://github.com/ros/ros_comm/issues/489>`_)
* populate delivered_msgs field of TopicStatistics message (`#486 <https://github.com/ros/ros_comm/issues/486>`_)
1.11.8 (2014-08-04)
-------------------
* fix C++11 compatibility issue (`#483 <https://github.com/ros/ros_comm/issues/483>`_)
1.11.7 (2014-07-18)
-------------------
* fix segfault due to accessing a NULL pointer for some network interfaces (`#465 <https://github.com/ros/ros_comm/issues/465>`_) (regression from 1.11.6)
1.11.6 (2014-07-10)
-------------------
* check ROS_HOSTNAME for localhost / ROS_IP for 127./::1 and prevent connections from other hosts in that case (`#452 <https://github.com/ros/ros_comm/issues/452>`_)
1.11.5 (2014-06-24)
-------------------
* improve handling dropped connections (`#434 <https://github.com/ros/ros_comm/issues/434>`_)
* add header needed for Android (`#441 <https://github.com/ros/ros_comm/issues/441>`_)
* fix typo for parameter used for statistics (`#448 <https://github.com/ros/ros_comm/issues/448>`_)
1.11.4 (2014-06-16)
-------------------
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* update API to use boost::signals2 (`#267 <https://github.com/ros/ros_comm/issues/267>`_)
* only update param cache when being subscribed (`#351 <https://github.com/ros/ros_comm/issues/351>`_)
* ensure to remove delete parameters completely
* invalidate cached parent parameters when namespace parameter is set / changes (`#352 <https://github.com/ros/ros_comm/issues/352>`_)
* add optional topic/connection statistics (`#398 <https://github.com/ros/ros_comm/issues/398>`_)
* add transport information in SlaveAPI::getBusInfo() for roscpp & rospy (`#328 <https://github.com/ros/ros_comm/issues/328>`_)
* add AsyncSpinner::canStart() to check if a spinner can be started
1.11.0 (2014-03-04)
-------------------
* allow getting parameters with name '/' (`#313 <https://github.com/ros/ros_comm/issues/313>`_)
* support for /clock remapping (`#359 <https://github.com/ros/ros_comm/issues/359>`_)
* suppress boost::signals deprecation warning (`#362 <https://github.com/ros/ros_comm/issues/362>`_)
* use catkin_install_python() to install Python scripts (`#361 <https://github.com/ros/ros_comm/issues/361>`_)
1.10.0 (2014-02-11)
-------------------
* remove use of __connection header
1.9.54 (2014-01-27)
-------------------
* fix return value of pubUpdate() (`#334 <https://github.com/ros/ros_comm/issues/334>`_)
* fix handling optional third xml rpc response argument (`#335 <https://github.com/ros/ros_comm/issues/335>`_)
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
* move several client library independent parts from ros_comm into roscpp_core, split rosbag storage specific stuff from client library usage (`#299 <https://github.com/ros/ros_comm/issues/299>`_)
* add missing version dependency on roscpp_core stuff (`#299 <https://github.com/ros/ros_comm/issues/299>`_)
* remove log4cxx dependency from roscpp, using new agnostic interface from rosconsole
* fix compile problem with gcc 4.4 (`#302 <https://github.com/ros/ros_comm/issues/302>`_)
* fix clang warnings
* fix usage of boost include directories
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
* add rosparam getter/setter for std::vector and std::map (`#279 <https://github.com/ros/ros_comm/issues/279>`_)
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
1.9.46 (2013-06-18)
-------------------
1.9.45 (2013-06-06)
-------------------
* improve handling of UDP transport, when fragmented packets are lost or arive out-of-order the connection is not dropped anymore, onle a single message is lost (`#226 <https://github.com/ros/ros_comm/issues/226>`_)
* fix missing generation of constant definitions for services (`ros/gencpp#2 <https://github.com/ros/gencpp/issues/2>`_)
* fix restoring thread context when callback throws an exception (`#219 <https://github.com/ros/ros_comm/issues/219>`_)
* fix calling PollManager::shutdown() repeatedly (`#217 <https://github.com/ros/ros_comm/issues/217>`_)
1.9.44 (2013-03-21)
-------------------
* fix install destination for dll's under Windows
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
* improve speed of message generation in dry packages (`#183 <https://github.com/ros/ros_comm/issues/183>`_)
* fix roscpp service call deadlock (`#149 <https://github.com/ros/ros_comm/issues/149>`_)
* fix freezing service calls when returning false (`#168 <https://github.com/ros/ros_comm/issues/168>`_)
* fix error message publishing wrong message type (`#178 <https://github.com/ros/ros_comm/issues/178>`_)
* fix missing explicit dependency on pthread (`#135 <https://github.com/ros/ros_comm/issues/135>`_)
* fix compiler warning about wrong comparison of message md5 hashes (`#165 <https://github.com/ros/ros_comm/issues/165>`_)
1.9.41 (2013-01-24)
-------------------
* allow sending data exceeding 2GB in chunks (`#4049 <https://code.ros.org/trac/ros/ticket/4049>`_)
* update getParam() doc (`#1460 <https://code.ros.org/trac/ros/ticket/1460>`_)
* add param::get(float) (`#3754 <https://code.ros.org/trac/ros/ticket/3754>`_)
* update inactive assert when publishing message with md5sum "*", update related tests (`#3714 <https://code.ros.org/trac/ros/ticket/3714>`_)
* fix ros master retry timeout (`#4024 <https://code.ros.org/trac/ros/ticket/4024>`_)
* fix inactive assert when publishing message with wrong type (`#3714 <https://code.ros.org/trac/ros/ticket/3714>`_)
1.9.40 (2013-01-13)
-------------------
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild/roscpp.cmake | rosbuild_find_ros_package(genmsg_cpp)
rosbuild_find_ros_package(roscpp)
# Message-generation support.
macro(genmsg_cpp)
rosbuild_get_msgs(_msglist)
set(_autogen "")
foreach(_msg ${_msglist})
# Construct the path to the .msg file
set(_input ${PROJECT_SOURCE_DIR}/msg/${_msg})
rosbuild_gendeps(${PROJECT_NAME} ${_msg})
set(genmsg_cpp_exe ${roscpp_PACKAGE_PATH}/rosbuild/scripts/genmsg_cpp.py)
set(_output_cpp ${PROJECT_SOURCE_DIR}/msg_gen/cpp/include/${PROJECT_NAME}/${_msg})
string(REPLACE ".msg" ".h" _output_cpp ${_output_cpp})
# Add the rule to build the .h the .msg
add_custom_command(OUTPUT ${_output_cpp}
COMMAND ${genmsg_cpp_exe} ${_input}
DEPENDS ${_input} ${genmsg_cpp_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_msg}_GENDEPS} ${ROS_MANIFEST_LIST})
list(APPEND _autogen ${_output_cpp})
endforeach(_msg)
# Create a target that depends on the union of all the autogenerated
# files
add_custom_target(ROSBUILD_genmsg_cpp DEPENDS ${_autogen})
# Make our target depend on rosbuild_premsgsrvgen, to allow any
# pre-msg/srv generation steps to be done first.
add_dependencies(ROSBUILD_genmsg_cpp rosbuild_premsgsrvgen)
# Add our target to the top-level rospack_genmsg target, which will be
# fired if the user calls genmsg()
add_dependencies(rospack_genmsg ROSBUILD_genmsg_cpp)
if(_autogen)
# Also set up to clean the msg_gen directory
get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES)
list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/msg_gen)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}")
endif(_autogen)
endmacro(genmsg_cpp)
# Call the macro we just defined.
genmsg_cpp()
# Service-generation support.
macro(gensrv_cpp)
rosbuild_get_srvs(_srvlist)
set(_autogen "")
foreach(_srv ${_srvlist})
# Construct the path to the .srv file
set(_input ${PROJECT_SOURCE_DIR}/srv/${_srv})
rosbuild_gendeps(${PROJECT_NAME} ${_srv})
set(gensrv_cpp_exe ${roscpp_PACKAGE_PATH}/rosbuild/scripts/gensrv_cpp.py)
set(genmsg_cpp_exe ${roscpp_PACKAGE_PATH}/rosbuild/scripts/genmsg_cpp.py)
set(_output_cpp ${PROJECT_SOURCE_DIR}/srv_gen/cpp/include/${PROJECT_NAME}/${_srv})
string(REPLACE ".srv" ".h" _output_cpp ${_output_cpp})
# Add the rule to build the .h from the .srv
add_custom_command(OUTPUT ${_output_cpp}
COMMAND ${gensrv_cpp_exe} ${_input}
DEPENDS ${_input} ${gensrv_cpp_exe} ${genmsg_cpp_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_srv}_GENDEPS} ${ROS_MANIFEST_LIST})
list(APPEND _autogen ${_output_cpp})
endforeach(_srv)
# Create a target that depends on the union of all the autogenerated
# files
add_custom_target(ROSBUILD_gensrv_cpp DEPENDS ${_autogen})
# Make our target depend on rosbuild_premsgsrvgen, to allow any
# pre-msg/srv generation steps to be done first.
add_dependencies(ROSBUILD_gensrv_cpp rosbuild_premsgsrvgen)
# Add our target to the top-level gensrv target, which will be fired if
# the user calls gensrv()
add_dependencies(rospack_gensrv ROSBUILD_gensrv_cpp)
if(_autogen)
# Also set up to clean the srv_gen directory
get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES)
list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/srv_gen)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}")
endif(_autogen)
endmacro(gensrv_cpp)
# Call the macro we just defined.
gensrv_cpp()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild/scripts/genmsg_cpp.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
## ROS message source code generation for C++
##
## Converts ROS .msg files in a package into C++ source code implementations.
import msg_gen
import sys
if __name__ == "__main__":
msg_gen.generate_messages(sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild/scripts/gensrv_cpp.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
## ROS message source code generation for C++
##
## Converts ROS .msg files in a package into C++ source code implementations.
import msg_gen as genmsg_cpp
import sys
import os
import traceback
# roslib.msgs contains the utilities for parsing .msg specifications. It is meant to have no rospy-specific knowledge
import roslib.srvs
import roslib.packages
import roslib.gentools
from rospkg import RosPack
try:
from cStringIO import StringIO #Python 2.x
except ImportError:
from io import StringIO #Python 3.x
def write_begin(s, spec, file):
"""
Writes the beginning of the header file: a comment saying it's auto-generated and the include guards
@param s: The stream to write to
@type s: stream
@param spec: The spec
@type spec: roslib.srvs.SrvSpec
@param file: The file this service is being generated for
@type file: str
"""
s.write("/* Auto-generated by genmsg_cpp for file %s */\n"%(file))
s.write('#ifndef %s_SERVICE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
s.write('#define %s_SERVICE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
def write_end(s, spec):
"""
Writes the end of the header file: the ending of the include guards
@param s: The stream to write to
@type s: stream
@param spec: The spec
@type spec: roslib.srvs.SrvSpec
"""
s.write('#endif // %s_SERVICE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
def write_generic_includes(s):
"""
Writes the includes that all service need
@param s: The stream to write to
@type s: stream
"""
s.write('#include "ros/service_traits.h"\n\n')
def write_trait_char_class(s, class_name, cpp_msg, value):
"""
Writes a class trait for traits which have static value() members that return const char*
e.g. write_trait_char_class(s, "MD5Sum", "std_srvs::Empty", "hello") yields:
template<>
struct MD5Sum<std_srvs::Empty>
{
static const char* value() { return "hello"; }
static const char* value(const std_srvs::Empty&) { return value(); }
};
@param s: The stream to write to
@type s: stream
@param class_name: The name of the trait class
@type class_name: str
@param cpp_msg: The C++ message declaration, e.g. "std_srvs::Empty"
@type cpp_msg: str
@param value: The string value to return from the value() function
@type value: str
"""
s.write('template<>\nstruct %s<%s> {\n'%(class_name, cpp_msg))
s.write(' static const char* value() \n {\n return "%s";\n }\n\n'%(value))
s.write(' static const char* value(const %s&) { return value(); } \n'%(cpp_msg))
s.write('};\n\n')
def write_traits(s, spec, cpp_name_prefix, rospack=None):
"""
Write all the service traits for a message
@param s: The stream to write to
@type s: stream
@param spec: The service spec
@type spec: roslib.srvs.SrvSpec
@param cpp_name_prefix: The C++ prefix to prepend when referencing the service, e.g. "std_srvs::"
@type cpp_name_prefix: str
"""
gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, rospack=rospack)
md5sum = roslib.gentools.compute_md5(gendeps_dict, rospack=rospack)
s.write('namespace ros\n{\n')
s.write('namespace service_traits\n{\n')
request_with_allocator = '%s%s_<ContainerAllocator> '%(cpp_name_prefix, spec.request.short_name)
response_with_allocator = '%s%s_<ContainerAllocator> '%(cpp_name_prefix, spec.response.short_name)
write_trait_char_class(s, 'MD5Sum', '%s%s'%(cpp_name_prefix, spec.short_name), md5sum);
write_trait_char_class(s, 'DataType', '%s%s'%(cpp_name_prefix, spec.short_name), spec.full_name);
genmsg_cpp.write_trait_char_class(s, 'MD5Sum', request_with_allocator, md5sum)
genmsg_cpp.write_trait_char_class(s, 'DataType', request_with_allocator, spec.full_name)
genmsg_cpp.write_trait_char_class(s, 'MD5Sum', response_with_allocator, md5sum)
genmsg_cpp.write_trait_char_class(s, 'DataType', response_with_allocator, spec.full_name)
s.write('} // namespace service_traits\n')
s.write('} // namespace ros\n\n')
def generate(srv_path):
"""
Generate a service
@param srv_path: the path to the .srv file
@type srv_path: str
"""
(package_dir, package) = roslib.packages.get_dir_pkg(srv_path)
(_, spec) = roslib.srvs.load_from_file(srv_path, package)
s = StringIO()
cpp_prefix = '%s::'%(package)
write_begin(s, spec, srv_path)
genmsg_cpp.write_generic_includes(s)
write_generic_includes(s)
genmsg_cpp.write_includes(s, spec.request)
s.write('\n')
genmsg_cpp.write_includes(s, spec.response)
rospack = RosPack()
gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, rospack=rospack)
md5sum = roslib.gentools.compute_md5(gendeps_dict, rospack=rospack)
s.write('namespace %s\n{\n'%(package))
genmsg_cpp.write_struct(s, spec.request, cpp_prefix, {'ServerMD5Sum': md5sum})
genmsg_cpp.write_constant_definitions(s, spec.request)
s.write('\n')
genmsg_cpp.write_struct(s, spec.response, cpp_prefix, {'ServerMD5Sum': md5sum})
genmsg_cpp.write_constant_definitions(s, spec.response)
s.write('struct %s\n{\n'%(spec.short_name))
s.write('\n')
s.write('typedef %s Request;\n'%(spec.request.short_name))
s.write('typedef %s Response;\n'%(spec.response.short_name))
s.write('Request request;\n')
s.write('Response response;\n\n')
s.write('typedef Request RequestType;\n')
s.write('typedef Response ResponseType;\n')
s.write('}; // struct %s\n'%(spec.short_name))
s.write('} // namespace %s\n\n'%(package))
request_cpp_name = "Request"
response_cpp_name = "Response"
genmsg_cpp.write_traits(s, spec.request, cpp_prefix, rospack=rospack)
s.write('\n')
genmsg_cpp.write_traits(s, spec.response, cpp_prefix, rospack=rospack)
genmsg_cpp.write_serialization(s, spec.request, cpp_prefix)
s.write('\n')
genmsg_cpp.write_serialization(s, spec.response, cpp_prefix)
write_traits(s, spec, cpp_prefix, rospack=rospack)
write_end(s, spec)
output_dir = '%s/srv_gen/cpp/include/%s'%(package_dir, package)
if (not os.path.exists(output_dir)):
# if we're being run concurrently, the above test can report false but os.makedirs can still fail if
# another copy just created the directory
try:
os.makedirs(output_dir)
except OSError as e:
pass
f = open('%s/%s.h'%(output_dir, spec.short_name), 'w')
f.write(s.getvalue() + "\n")
s.close()
def generate_services(argv):
for arg in argv[1:]:
generate(arg)
if __name__ == "__main__":
roslib.msgs.set_verbose(False)
generate_services(sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/rosbuild/scripts/msg_gen.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
## ROS message source code generation for C++
##
## Converts ROS .msg files in a package into C++ source code implementations.
import sys
import os
import traceback
import roslib.msgs
import roslib.packages
import roslib.gentools
from rospkg import RosPack
try:
from cStringIO import StringIO #Python 2.x
except ImportError:
from io import StringIO #Python 3.x
MSG_TYPE_TO_CPP = {'byte': 'int8_t', 'char': 'uint8_t',
'bool': 'uint8_t',
'uint8': 'uint8_t', 'int8': 'int8_t',
'uint16': 'uint16_t', 'int16': 'int16_t',
'uint32': 'uint32_t', 'int32': 'int32_t',
'uint64': 'uint64_t', 'int64': 'int64_t',
'float32': 'float',
'float64': 'double',
'string': 'std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > ',
'time': 'ros::Time',
'duration': 'ros::Duration'}
def msg_type_to_cpp(type):
"""
Converts a message type (e.g. uint32, std_msgs/String, etc.) into the C++ declaration
for that type (e.g. uint32_t, std_msgs::String_<ContainerAllocator>)
@param type: The message type
@type type: str
@return: The C++ declaration
@rtype: str
"""
(base_type, is_array, array_len) = roslib.msgs.parse_type(type)
cpp_type = None
if (roslib.msgs.is_builtin(base_type)):
cpp_type = MSG_TYPE_TO_CPP[base_type]
elif (len(base_type.split('/')) == 1):
if (roslib.msgs.is_header_type(base_type)):
cpp_type = ' ::std_msgs::Header_<ContainerAllocator> '
else:
cpp_type = '%s_<ContainerAllocator> '%(base_type)
else:
pkg = base_type.split('/')[0]
msg = base_type.split('/')[1]
cpp_type = ' ::%s::%s_<ContainerAllocator> '%(pkg, msg)
if (is_array):
if (array_len is None):
return 'std::vector<%s, typename ContainerAllocator::template rebind<%s>::other > '%(cpp_type, cpp_type)
else:
return 'boost::array<%s, %s> '%(cpp_type, array_len)
else:
return cpp_type
def cpp_message_declarations(name_prefix, msg):
"""
Returns the different possible C++ declarations for a message given the message itself.
@param name_prefix: The C++ prefix to be prepended to the name, e.g. "std_msgs::"
@type name_prefix: str
@param msg: The message type
@type msg: str
@return: A tuple of 3 different names. cpp_message_decelarations("std_msgs::", "String") returns the tuple
("std_msgs::String_", "std_msgs::String_<ContainerAllocator>", "std_msgs::String")
@rtype: str
"""
pkg, basetype = roslib.names.package_resource_name(msg)
cpp_name = ' ::%s%s'%(name_prefix, msg)
if (pkg):
cpp_name = ' ::%s::%s'%(pkg, basetype)
return ('%s_'%(cpp_name), '%s_<ContainerAllocator> '%(cpp_name), '%s'%(cpp_name))
def write_begin(s, spec, file):
"""
Writes the beginning of the header file: a comment saying it's auto-generated and the include guards
@param s: The stream to write to
@type s: stream
@param spec: The spec
@type spec: roslib.msgs.MsgSpec
@param file: The file this message is being generated for
@type file: str
"""
s.write("/* Auto-generated by genmsg_cpp for file %s */\n"%(file))
s.write('#ifndef %s_MESSAGE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
s.write('#define %s_MESSAGE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
def write_end(s, spec):
"""
Writes the end of the header file: the ending of the include guards
@param s: The stream to write to
@type s: stream
@param spec: The spec
@type spec: roslib.msgs.MsgSpec
"""
s.write('#endif // %s_MESSAGE_%s_H\n'%(spec.package.upper(), spec.short_name.upper()))
def write_generic_includes(s):
"""
Writes the includes that all messages need
@param s: The stream to write to
@type s: stream
"""
s.write('#include <string>\n')
s.write('#include <vector>\n')
s.write('#include <map>\n')
s.write('#include <ostream>\n')
s.write('#include "ros/serialization.h"\n')
s.write('#include "ros/builtin_message_traits.h"\n')
s.write('#include "ros/message_operations.h"\n')
s.write('#include "ros/time.h"\n\n')
s.write('#include "ros/macros.h"\n\n')
s.write('#include "ros/assert.h"\n\n')
def write_includes(s, spec):
"""
Writes the message-specific includes
@param s: The stream to write to
@type s: stream
@param spec: The message spec to iterate over
@type spec: roslib.msgs.MsgSpec
"""
for field in spec.parsed_fields():
if (not field.is_builtin):
if (field.is_header):
s.write('#include "std_msgs/Header.h"\n')
else:
(pkg, name) = roslib.names.package_resource_name(field.base_type)
pkg = pkg or spec.package # convert '' to package
s.write('#include "%s/%s.h"\n'%(pkg, name))
s.write('\n')
def write_struct(s, spec, cpp_name_prefix, extra_deprecated_traits = {}):
"""
Writes the entire message struct: declaration, constructors, members, constants and (deprecated) member functions
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. "std_msgs::"
@type cpp_name_prefix: str
"""
msg = spec.short_name
s.write('template <class ContainerAllocator>\n')
s.write('struct %s_ {\n'%(msg))
s.write(' typedef %s_<ContainerAllocator> Type;\n\n'%(msg))
write_constructors(s, spec, cpp_name_prefix)
write_members(s, spec)
write_constant_declarations(s, spec)
#rospack = RosPack()
#gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, compute_files=False, rospack=rospack)
#md5sum = roslib.gentools.compute_md5(gendeps_dict, rospack=rospack)
#full_text = compute_full_text_escaped(gendeps_dict)
# write_deprecated_member_functions(s, spec, dict(list({'MD5Sum': md5sum, 'DataType': '%s/%s'%(spec.package, spec.short_name), 'MessageDefinition': full_text}.items()) + list(extra_deprecated_traits.items())))
(cpp_msg_unqualified, cpp_msg_with_alloc, cpp_msg_base) = cpp_message_declarations(cpp_name_prefix, msg)
s.write(' typedef boost::shared_ptr<%s> Ptr;\n'%(cpp_msg_with_alloc))
s.write(' typedef boost::shared_ptr<%s const> ConstPtr;\n'%(cpp_msg_with_alloc))
s.write('}; // struct %s\n'%(msg))
s.write('typedef %s_<std::allocator<void> > %s;\n\n'%(cpp_msg_base, msg))
s.write('typedef boost::shared_ptr<%s> %sPtr;\n'%(cpp_msg_base, msg))
s.write('typedef boost::shared_ptr<%s const> %sConstPtr;\n\n'%(cpp_msg_base, msg))
def default_value(type):
"""
Returns the value to initialize a message member with. 0 for integer types, 0.0 for floating point, false for bool,
empty string for everything else
@param type: The type
@type type: str
"""
if type in ['byte', 'int8', 'int16', 'int32', 'int64',
'char', 'uint8', 'uint16', 'uint32', 'uint64']:
return '0'
elif type in ['float32', 'float64']:
return '0.0'
elif type == 'bool':
return 'false'
return ""
def takes_allocator(type):
"""
Returns whether or not a type can take an allocator in its constructor. False for all builtin types except string.
True for all others.
@param type: The type
@type: str
"""
return not type in ['byte', 'int8', 'int16', 'int32', 'int64',
'char', 'uint8', 'uint16', 'uint32', 'uint64',
'float32', 'float64', 'bool', 'time', 'duration']
def write_initializer_list(s, spec, container_gets_allocator):
"""
Writes the initializer list for a constructor
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param container_gets_allocator: Whether or not a container type (whether it's another message, a vector, array or string)
should have the allocator passed to its constructor. Assumes the allocator is named _alloc.
@type container_gets_allocator: bool
"""
i = 0
for field in spec.parsed_fields():
if (i == 0):
s.write(' : ')
else:
s.write(' , ')
val = default_value(field.base_type)
use_alloc = takes_allocator(field.base_type)
if (field.is_array):
if (field.array_len is None and container_gets_allocator):
s.write('%s(_alloc)\n'%(field.name))
else:
s.write('%s()\n'%(field.name))
else:
if (container_gets_allocator and use_alloc):
s.write('%s(_alloc)\n'%(field.name))
else:
s.write('%s(%s)\n'%(field.name, val))
i = i + 1
def write_fixed_length_assigns(s, spec, container_gets_allocator, cpp_name_prefix):
"""
Initialize any fixed-length arrays
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param container_gets_allocator: Whether or not a container type (whether it's another message, a vector, array or string)
should have the allocator passed to its constructor. Assumes the allocator is named _alloc.
@type container_gets_allocator: bool
@param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. "std_msgs::"
@type cpp_name_prefix: str
"""
# Assign all fixed-length arrays their default values
for field in spec.parsed_fields():
if (not field.is_array or field.array_len is None):
continue
val = default_value(field.base_type)
if (container_gets_allocator and takes_allocator(field.base_type)):
# String is a special case, as it is the only builtin type that takes an allocator
if (field.base_type == "string"):
string_cpp = msg_type_to_cpp("string")
s.write(' %s.assign(%s(_alloc));\n'%(field.name, string_cpp))
else:
(cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, field.base_type)
s.write(' %s.assign(%s(_alloc));\n'%(field.name, cpp_msg_with_alloc))
elif (len(val) > 0):
s.write(' %s.assign(%s);\n'%(field.name, val))
def write_constructors(s, spec, cpp_name_prefix):
"""
Writes any necessary constructors for the message
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. "std_msgs::"
@type cpp_name_prefix: str
"""
msg = spec.short_name
# Default constructor
s.write(' %s_()\n'%(msg))
write_initializer_list(s, spec, False)
s.write(' {\n')
write_fixed_length_assigns(s, spec, False, cpp_name_prefix)
s.write(' }\n\n')
# Constructor that takes an allocator constructor
s.write(' %s_(const ContainerAllocator& _alloc)\n'%(msg))
write_initializer_list(s, spec, True)
s.write(' {\n')
write_fixed_length_assigns(s, spec, True, cpp_name_prefix)
s.write(' }\n\n')
def write_member(s, field):
"""
Writes a single member's declaration and type typedef
@param s: The stream to write to
@type s: stream
@param type: The member type
@type type: str
@param name: The name of the member
@type name: str
"""
cpp_type = msg_type_to_cpp(field.type)
s.write(' typedef %s _%s_type;\n'%(cpp_type, field.name))
s.write(' %s %s;\n\n'%(cpp_type, field.name))
def write_members(s, spec):
"""
Write all the member declarations
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
"""
[write_member(s, field) for field in spec.parsed_fields()]
def escape_string(str):
str = str.replace('\\', '\\\\')
str = str.replace('"', '\\"')
return str
def write_constant_declaration(s, constant):
"""
Write a constant value as a static member
@param s: The stream to write to
@type s: stream
@param constant: The constant
@type constant: roslib.msgs.Constant
"""
# integral types get their declarations as enums to allow use at compile time
if (constant.type in ['byte', 'int8', 'int16', 'int32', 'int64', 'char', 'uint8', 'uint16', 'uint32', 'uint64']):
s.write(' enum { %s = %s };\n'%(constant.name, constant.val))
else:
s.write(' static const %s %s;\n'%(msg_type_to_cpp(constant.type), constant.name))
def write_constant_declarations(s, spec):
"""
Write all the constants from a spec as static members
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
"""
[write_constant_declaration(s, constant) for constant in spec.constants]
s.write('\n')
def write_constant_definition(s, spec, constant):
"""
Write a constant value as a static member
@param s: The stream to write to
@type s: stream
@param constant: The constant
@type constant: roslib.msgs.Constant
"""
# integral types do not need a definition, since they've been defined where they are declared
if (constant.type not in ['byte', 'int8', 'int16', 'int32', 'int64', 'char', 'uint8', 'uint16', 'uint32', 'uint64', 'string']):
s.write('template<typename ContainerAllocator> const %s %s_<ContainerAllocator>::%s = %s;\n'%(msg_type_to_cpp(constant.type), spec.short_name, constant.name, constant.val))
elif (constant.type == 'string'):
s.write('template<typename ContainerAllocator> const %s %s_<ContainerAllocator>::%s = "%s";\n'%(msg_type_to_cpp(constant.type), spec.short_name, constant.name, escape_string(constant.val)))
def write_constant_definitions(s, spec):
"""
Write all the constants from a spec as static members
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
"""
[write_constant_definition(s, spec, constant) for constant in spec.constants]
s.write('\n')
def is_fixed_length(spec):
"""
Returns whether or not the message is fixed-length
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param package: The package of the
@type package: str
"""
types = []
for field in spec.parsed_fields():
if (field.is_array and field.array_len is None):
return False
if (field.base_type == 'string'):
return False
if (not field.is_builtin):
types.append(field.base_type)
types = set(types)
for type in types:
type = roslib.msgs.resolve_type(type, spec.package)
(_, new_spec) = roslib.msgs.load_by_type(type, spec.package)
if (not is_fixed_length(new_spec)):
return False
return True
def write_deprecated_member_functions(s, spec, traits):
"""
Writes the deprecated member functions for backwards compatibility
"""
for field in spec.parsed_fields():
if (field.is_array):
s.write(' ROS_DEPRECATED uint32_t get_%s_size() const { return (uint32_t)%s.size(); }\n'%(field.name, field.name))
if (field.array_len is None):
s.write(' ROS_DEPRECATED void set_%s_size(uint32_t size) { %s.resize((size_t)size); }\n'%(field.name, field.name))
s.write(' ROS_DEPRECATED void get_%s_vec(%s& vec) const { vec = this->%s; }\n'%(field.name, msg_type_to_cpp(field.type), field.name))
s.write(' ROS_DEPRECATED void set_%s_vec(const %s& vec) { this->%s = vec; }\n'%(field.name, msg_type_to_cpp(field.type), field.name))
for k, v in traits.items():
s.write('private:\n')
s.write(' static const char* __s_get%s_() { return "%s"; }\n'%(k, v))
s.write('public:\n')
s.write(' ROS_DEPRECATED static const std::string __s_get%s() { return __s_get%s_(); }\n\n'%(k, k))
s.write(' ROS_DEPRECATED const std::string __get%s() const { return __s_get%s_(); }\n\n'%(k, k))
s.write(' ROS_DEPRECATED virtual uint8_t *serialize(uint8_t *write_ptr, uint32_t seq) const\n {\n')
s.write(' ros::serialization::OStream stream(write_ptr, 1000000000);\n')
for field in spec.parsed_fields():
s.write(' ros::serialization::serialize(stream, %s);\n'%(field.name))
s.write(' return stream.getData();\n }\n\n')
s.write(' ROS_DEPRECATED virtual uint8_t *deserialize(uint8_t *read_ptr)\n {\n')
s.write(' ros::serialization::IStream stream(read_ptr, 1000000000);\n');
for field in spec.parsed_fields():
s.write(' ros::serialization::deserialize(stream, %s);\n'%(field.name))
s.write(' return stream.getData();\n }\n\n')
s.write(' ROS_DEPRECATED virtual uint32_t serializationLength() const\n {\n')
s.write(' uint32_t size = 0;\n');
for field in spec.parsed_fields():
s.write(' size += ros::serialization::serializationLength(%s);\n'%(field.name))
s.write(' return size;\n }\n\n')
def compute_full_text_escaped(gen_deps_dict):
"""
Same as roslib.gentools.compute_full_text, except that the
resulting text is escaped to be safe for C++ double quotes
@param get_deps_dict: dictionary returned by get_dependencies call
@type get_deps_dict: dict
@return: concatenated text for msg/srv file and embedded msg/srv types. Text will be escaped for double quotes
@rtype: str
"""
definition = roslib.gentools.compute_full_text(gen_deps_dict)
lines = definition.split('\n')
s = StringIO()
for line in lines:
line = escape_string(line)
s.write('%s\\n\\\n'%(line))
val = s.getvalue()
s.close()
return val
def is_hex_string(str):
for c in str:
if c not in '0123456789abcdefABCDEF':
return False
return True
def write_trait_char_class(s, class_name, cpp_msg_with_alloc, value, write_static_hex_value = False):
"""
Writes a class trait for traits which have static value() members that return const char*
e.g. write_trait_char_class(s, "MD5Sum", "std_msgs::String_<ContainerAllocator>", "hello") yields:
template<class ContainerAllocator>
struct MD5Sum<std_msgs::String_<ContainerAllocator> >
{
static const char* value() { return "hello"; }
static const char* value(const std_msgs::String_<ContainerAllocator>&) { return value(); }
};
@param s: The stream to write to
@type s: stream
@param class_name: The name of the trait class to write
@type class_name: str
@param cpp_msg_with_alloc: The C++ declaration of the message, including the allocator template
@type cpp_msg_with_alloc: str
@param value: The value to return in the string
@type value: str
@param write_static_hex_value: Whether or not to write a set of compile-time-checkable static values. Useful for,
for example, MD5Sum. Writes static const uint64_t static_value1... static_valueN
@type write_static_hex_value: bool
@raise ValueError if write_static_hex_value is True but value contains characters invalid in a hex value
"""
s.write('template<class ContainerAllocator>\nstruct %s<%s> {\n'%(class_name, cpp_msg_with_alloc))
s.write(' static const char* value() \n {\n return "%s";\n }\n\n'%(value))
s.write(' static const char* value(const %s&) { return value(); } \n'%(cpp_msg_with_alloc))
if (write_static_hex_value):
if (not is_hex_string(value)):
raise ValueError('%s is not a hex value'%(value))
iter_count = len(value) / 16
for i in range(0, int(iter_count)):
start = i*16
s.write(' static const uint64_t static_value%s = 0x%sULL;\n'%((i+1), value[start:start+16]))
s.write('};\n\n')
def write_trait_true_class(s, class_name, cpp_msg_with_alloc):
"""
Writes a true/false trait class
@param s: stream to write to
@type s: stream
@param class_name: Name of the trait class
@type class_name: str
@param cpp_msg_with_alloc: The C++ declaration of the message, including the allocator template
@type cpp_msg_with_alloc: str
"""
s.write('template<class ContainerAllocator> struct %s<%s> : public TrueType {};\n'%(class_name, cpp_msg_with_alloc))
def write_traits(s, spec, cpp_name_prefix, datatype = None, rospack=None):
"""
Writes all the traits classes for a message
@param s: The stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param cpp_name_prefix: The C++ prefix to prepend to a message to refer to it (e.g. "std_msgs::")
@type cpp_name_prefix: str
@param datatype: The string to write as the datatype of the message. If None (default), pkg/msg is used.
@type datatype: str
"""
# generate dependencies dictionary
gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, compute_files=False, rospack=rospack)
md5sum = roslib.gentools.compute_md5(gendeps_dict, rospack=rospack)
full_text = compute_full_text_escaped(gendeps_dict)
if (datatype is None):
datatype = '%s'%(spec.full_name)
(cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, spec.short_name)
s.write('namespace ros\n{\n')
s.write('namespace message_traits\n{\n')
write_trait_true_class(s, 'IsMessage', cpp_msg_with_alloc)
write_trait_true_class(s, 'IsMessage', cpp_msg_with_alloc + " const")
write_trait_char_class(s, 'MD5Sum', cpp_msg_with_alloc, md5sum, True)
write_trait_char_class(s, 'DataType', cpp_msg_with_alloc, datatype)
write_trait_char_class(s, 'Definition', cpp_msg_with_alloc, full_text)
if (spec.has_header()):
write_trait_true_class(s, 'HasHeader', cpp_msg_with_alloc)
write_trait_true_class(s, 'HasHeader', ' const' + cpp_msg_with_alloc)
if (is_fixed_length(spec)):
write_trait_true_class(s, 'IsFixedSize', cpp_msg_with_alloc)
s.write('} // namespace message_traits\n')
s.write('} // namespace ros\n\n')
def write_operations(s, spec, cpp_name_prefix):
(cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, spec.short_name)
s.write('namespace ros\n{\n')
s.write('namespace message_operations\n{\n')
# Write the Printer operation
s.write('\ntemplate<class ContainerAllocator>\nstruct Printer<%s>\n{\n'%(cpp_msg_with_alloc))
s.write(' template<typename Stream> static void stream(Stream& s, const std::string& indent, const %s& v) \n {\n'%cpp_msg_with_alloc)
for field in spec.parsed_fields():
cpp_type = msg_type_to_cpp(field.base_type)
if (field.is_array):
s.write(' s << indent << "%s[]" << std::endl;\n'%(field.name))
s.write(' for (size_t i = 0; i < v.%s.size(); ++i)\n {\n'%(field.name))
s.write(' s << indent << " %s[" << i << "]: ";\n'%field.name)
indent_increment = ' '
if (not field.is_builtin):
s.write(' s << std::endl;\n')
s.write(' s << indent;\n')
indent_increment = ' ';
s.write(' Printer<%s>::stream(s, indent + "%s", v.%s[i]);\n'%(cpp_type, indent_increment, field.name))
s.write(' }\n')
else:
s.write(' s << indent << "%s: ";\n'%field.name)
indent_increment = ' '
if (not field.is_builtin or field.is_array):
s.write('s << std::endl;\n')
s.write(' Printer<%s>::stream(s, indent + "%s", v.%s);\n'%(cpp_type, indent_increment, field.name))
s.write(' }\n')
s.write('};\n\n')
s.write('\n')
s.write('} // namespace message_operations\n')
s.write('} // namespace ros\n\n')
def write_serialization(s, spec, cpp_name_prefix):
"""
Writes the Serializer class for a message
@param s: Stream to write to
@type s: stream
@param spec: The message spec
@type spec: roslib.msgs.MsgSpec
@param cpp_name_prefix: The C++ prefix to prepend to a message to refer to it (e.g. "std_msgs::")
@type cpp_name_prefix: str
"""
(cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, spec.short_name)
s.write('namespace ros\n{\n')
s.write('namespace serialization\n{\n\n')
s.write('template<class ContainerAllocator> struct Serializer<%s>\n{\n'%(cpp_msg_with_alloc))
s.write(' template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)\n {\n')
for field in spec.parsed_fields():
s.write(' stream.next(m.%s);\n'%(field.name))
s.write(' }\n\n')
s.write(' ROS_DECLARE_ALLINONE_SERIALIZER;\n')
s.write('}; // struct %s_\n'%(spec.short_name))
s.write('} // namespace serialization\n')
s.write('} // namespace ros\n\n')
def write_ostream_operator(s, spec, cpp_name_prefix):
(cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, spec.short_name)
s.write('template<typename ContainerAllocator>\nstd::ostream& operator<<(std::ostream& s, const %s& v)\n{\n'%(cpp_msg_with_alloc))
s.write(' ros::message_operations::Printer<%s>::stream(s, "", v);\n return s;}\n\n'%(cpp_msg_with_alloc))
def generate(msg_path):
"""
Generate a message
@param msg_path: The path to the .msg file
@type msg_path: str
"""
(package_dir, package) = roslib.packages.get_dir_pkg(msg_path)
(_, spec) = roslib.msgs.load_from_file(msg_path, package)
s = StringIO()
write_begin(s, spec, msg_path)
write_generic_includes(s)
write_includes(s, spec)
cpp_prefix = '%s::'%(package)
s.write('namespace %s\n{\n'%(package))
write_struct(s, spec, cpp_prefix)
write_constant_definitions(s, spec)
write_ostream_operator(s, spec, cpp_prefix)
s.write('} // namespace %s\n\n'%(package))
rospack = RosPack()
write_traits(s, spec, cpp_prefix, rospack=rospack)
write_serialization(s, spec, cpp_prefix)
write_operations(s, spec, cpp_prefix)
# HACK HACK HACK. The moving of roslib/Header causes many problems. We end up having to make roslib/Header act exactly
# like std_msgs/Header (as in, constructor that takes it, as well as operator std_msgs::Header()), and it needs to be
# available wherever std_msgs/Header.h has been included
if (package == "std_msgs" and spec.short_name == "Header"):
s.write("#define STD_MSGS_INCLUDING_HEADER_DEPRECATED_DEF 1\n")
s.write("#include <std_msgs/header_deprecated_def.h>\n")
s.write("#undef STD_MSGS_INCLUDING_HEADER_DEPRECATED_DEF\n\n")
write_end(s, spec)
output_dir = '%s/msg_gen/cpp/include/%s'%(package_dir, package)
if (not os.path.exists(output_dir)):
# if we're being run concurrently, the above test can report false but os.makedirs can still fail if
# another copy just created the directory
try:
os.makedirs(output_dir)
except OSError as e:
pass
f = open('%s/%s.h'%(output_dir, spec.short_name), 'w')
f.write(s.getvalue() + "\n")
s.close()
def generate_messages(argv):
for arg in argv[1:]:
generate(arg)
if __name__ == "__main__":
roslib.msgs.set_verbose(False)
generate_messages(sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/test/test_shm.cpp | /**
* Unit test for SHM.
*
*/
#include <gtest/gtest.h>
#include <stdlib.h>
#include <iostream>
#include <map>
#include "sharedmem_transport/sharedmem_block.h"
#include "sharedmem_transport/sharedmem_publisher_impl.h"
#include "sharedmem_transport/sharedmem_segment.h"
#include "sharedmem_transport/sharedmem_util.h"
#include "ros/time.h"
#include "boost/shared_ptr.hpp"
namespace ros {
TEST(SHMTest, handle_segment) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
std::string topic = "/chatter";
util->remove_segment(topic.c_str());
boost::interprocess::managed_shared_memory* segment = util->get_segment(topic.c_str());
EXPECT_EQ(NULL, segment);
sharedmem_transport::SharedMemorySegment* segment_mgr = util->get_segment_mgr(segment);
EXPECT_EQ(NULL, segment_mgr);
bool ret = util->remove_segment(topic.c_str());
ASSERT_FALSE(ret);
boost::interprocess::managed_shared_memory* segment_sec =
util->create_segment(topic.c_str(), 1000000);
ASSERT_TRUE(segment_sec != NULL);
sharedmem_transport::SharedMemorySegment* segment_mgr_sec =
util->create_segment_mgr(segment_sec);
ASSERT_TRUE(segment_mgr_sec != NULL);
boost::interprocess::managed_shared_memory* segment_thd = util->get_segment(topic.c_str());
ASSERT_TRUE(segment_thd != NULL);
sharedmem_transport::SharedMemorySegment* segment_mgr_thd = util->get_segment_mgr(segment_thd);
ASSERT_TRUE(segment_mgr_thd != NULL);
bool ret_sec = util->remove_segment(topic.c_str());
ASSERT_TRUE(ret_sec);
}
TEST(SHMTest, init_all_block) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
sharedmem_transport::SharedMemoryBlock* descriptors_pub = NULL;
std::string topic = "/chatter";
int segment_size = 1000000;
uint32_t queue_size = 10;
uint64_t msg_size = 20;
int32_t index = 1;
util->remove_segment(topic.c_str());
boost::interprocess::managed_shared_memory* segment =
util->create_segment(topic.c_str(), segment_size);
ASSERT_TRUE(segment != NULL);
sharedmem_transport::SharedMemorySegment* segment_mgr = util->create_segment_mgr(segment);
ASSERT_TRUE(segment_mgr != NULL);
uint8_t** addr_pub = new uint8_t*[queue_size];
bool ret = segment_mgr->init_all_blocks(*segment, queue_size,
msg_size, descriptors_pub, addr_pub);
ASSERT_TRUE(ret);
bool ret_sec = util->remove_segment(topic.c_str());
ASSERT_TRUE(ret_sec);
sharedmem_transport::SharedMemoryPublisherImpl* shared_impl;
bool ret_thd = shared_impl->create_topic_segement(topic, index, queue_size, msg_size, "", "", "");
ASSERT_TRUE(ret_thd);
if (addr_pub) {
delete []addr_pub;
}
ASSERT_TRUE(util->remove_segment(topic.c_str()));
}
TEST(SHMTest, map_all_block) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
std::string topic = "/chatter";
util->remove_segment(topic.c_str());
boost::interprocess::managed_shared_memory* segment = NULL;
sharedmem_transport::SharedMemorySegment* segment_mgr = NULL;
sharedmem_transport::SharedMemoryBlock* descriptors_sub = NULL;
uint32_t queue_size = 10;
bool ret = util->init_sharedmem(topic.c_str(),
segment, segment_mgr, descriptors_sub, queue_size);
ASSERT_TRUE(ret);
uint8_t** addr_sub = new uint8_t*[queue_size];
bool ret_sec = segment_mgr->map_all_blocks(segment, queue_size, addr_sub);
ASSERT_TRUE(ret_sec);
if (addr_sub) {
delete []addr_sub;
}
bool ret_thd = util->remove_segment(topic.c_str());
ASSERT_TRUE(ret_thd);
}
TEST(SHMTest, lock_mutex) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
std::string topic = "/chatter";
util->remove_segment(topic.c_str());
boost::shared_ptr<sharedmem_transport::SharedMemoryBlock>
block(new sharedmem_transport::SharedMemoryBlock());
for (int i = 0; i < 10; ++i) {
block->try_reserve_for_radical_write();
usleep(1000);
block->release_reserve_for_radical_write();
}
for (int i = 0; i < 10; ++i) {
block->try_reserve_for_radical_read();
usleep(1000);
block->release_reserve_for_radical_read();
}
ASSERT_TRUE(true);
}
TEST(SHMTest, write_msg) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
sharedmem_transport::SharedMemoryBlock* descriptors_pub = NULL;
std::string topic = "/chatter";
int segment_size = 10;
uint32_t queue_size = 10;
int msg_size = 10;
ros::SerializedMessage msg;
util->remove_segment(topic.c_str());
boost::interprocess::managed_shared_memory* segment =
util->create_segment(topic.c_str(), segment_size);
ASSERT_TRUE(segment != NULL);
sharedmem_transport::SharedMemorySegment* segment_mgr = util->create_segment_mgr(segment);
ASSERT_TRUE(segment_mgr != NULL);
uint8_t** addr_pub = new uint8_t*[queue_size];
bool ret = segment_mgr->init_all_blocks(*segment, queue_size,
msg_size, descriptors_pub, addr_pub);
ASSERT_TRUE(ret);
for (int i = 0; i < 5; ++i) {
bool ret_sec = segment_mgr->write_data(msg, queue_size, descriptors_pub, addr_pub);
ASSERT_TRUE(ret_sec);
}
if (addr_pub) {
delete []addr_pub;
}
bool ret_thd = util->remove_segment(topic.c_str());
ASSERT_TRUE(ret_thd);
}
TEST(SHMTest, read_msg) {
boost::shared_ptr<sharedmem_transport::SharedMemoryUtil>
util(new sharedmem_transport::SharedMemoryUtil());
std::string topic = "/chatter";
util->remove_segment(topic.c_str());
boost::interprocess::managed_shared_memory* segment = NULL;
sharedmem_transport::SharedMemorySegment* segment_mgr = NULL;
sharedmem_transport::SharedMemoryBlock* descriptors_sub = NULL;
uint32_t queue_size = 10;
int32_t read_index = -1;
int32_t msg_index;
uint32_t msg_size;
bool ret = util->init_sharedmem(topic.c_str(), segment,
segment_mgr, descriptors_sub, queue_size);
ASSERT_TRUE(ret);
uint8_t** addr_sub = new uint8_t*[queue_size];
bool ret_sec = segment_mgr->map_all_blocks(segment, queue_size, addr_sub);
ASSERT_TRUE(ret_sec);
for (int i = 0; i < 100; ++i) {
bool ret_thd = segment_mgr->read_data(read_index,
descriptors_sub, topic, msg_index, msg_size);
EXPECT_EQ(false, ret_thd);
}
if (addr_sub) {
delete []addr_sub;
}
ASSERT_TRUE(util->remove_segment(topic.c_str()));
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
ros::Time::init();
return RUN_ALL_TESTS();
} | 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/msg/Logger.msg | string name
string level
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/msg/SharedMemoryHeader.msg | uint32 index
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/connection.h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_CONNECTION_H
#define ROSCPP_CONNECTION_H
#include "ros/header.h"
#include "common.h"
#include <boost/signals2.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#define READ_BUFFER_SIZE (1024*64)
namespace ros
{
class Transport;
typedef boost::shared_ptr<Transport> TransportPtr;
class Connection;
typedef boost::shared_ptr<Connection> ConnectionPtr;
typedef boost::function<void(const ConnectionPtr&, const boost::shared_array<uint8_t>&, uint32_t, bool)> ReadFinishedFunc;
typedef boost::function<void(const ConnectionPtr&)> WriteFinishedFunc;
typedef boost::function<bool(const ConnectionPtr&, const Header&)> HeaderReceivedFunc;
/**
* \brief Encapsulates a connection to a remote host, independent of the transport type
*
* Connection provides automatic header negotiation, as well as easy ways of reading and writing
* arbitrary amounts of data without having to set up your own state machines.
*/
class ROSCPP_DECL Connection : public boost::enable_shared_from_this<Connection>
{
public:
enum DropReason
{
TransportDisconnect,
HeaderError,
Destructing,
};
Connection();
~Connection();
/**
* \brief Initialize this connection.
*/
void initialize(const TransportPtr& transport, bool is_server, const HeaderReceivedFunc& header_func);
/**
* \brief Drop this connection. Anything added as a drop listener through addDropListener will get called back when this connection has
* been dropped.
*/
void drop(DropReason reason);
/**
* \brief Returns whether or not this connection has been dropped
*/
bool isDropped();
/**
* \brief Returns true if we're currently sending a header error (and will be automatically dropped when it's finished)
*/
bool isSendingHeaderError() { return sending_header_error_; }
/**
* \brief Send a header error message, of the form "error=<message>". Drops the connection once the data has written successfully (or fails to write)
* \param error_message The error message
*/
void sendHeaderError(const std::string& error_message);
/**
* \brief Send a list of string key/value pairs as a header message.
* \param key_vals The values to send. Neither keys nor values can have any newlines in them
* \param finished_callback The function to call when the header has finished writing
*/
void writeHeader(const M_string& key_vals, const WriteFinishedFunc& finished_callback);
/**
* \brief Read a number of bytes, calling a callback when finished
*
* read() will not queue up multiple reads. Once read() has been called, it is not valid to call it again until the
* finished callback has been called. It \b is valid to call read() from within the finished callback.
*
* The finished callback is of the form void(const ConnectionPtr&, const boost::shared_array<uint8_t>&, uint32_t)
*
* \note The finished callback may be called from within this call to read() if the data has already arrived
*
* \param size The size, in bytes, of data to read
* \param finished_callback The function to call when this read is finished
*/
void read(uint32_t size, const ReadFinishedFunc& finished_callback);
/**
* \brief Write a buffer of bytes, calling a callback when finished
*
* write() will not queue up multiple writes. Once write() has been called, it is not valid to call it again until
* the finished callback has been called. It \b is valid to call write() from within the finished callback.
*
* * The finished callback is of the form void(const ConnectionPtr&)
*
* \note The finished callback may be called from within this call to write() if the data can be written immediately
*
* \param buffer The buffer of data to write
* \param size The size of the buffer, in bytes
* \param finished_callback The function to call when the write has finished
* \param immediate Whether to immediately try to write as much data as possible to the socket or to pass
* the data off to the server thread
*/
void write(const boost::shared_array<uint8_t>& buffer, uint32_t size, const WriteFinishedFunc& finished_callback, bool immedate = true);
typedef boost::signals2::signal<void(const ConnectionPtr&, DropReason reason)> DropSignal;
typedef boost::function<void(const ConnectionPtr&, DropReason reason)> DropFunc;
/**
* \brief Add a callback to be called when this connection has dropped
*/
boost::signals2::connection addDropListener(const DropFunc& slot);
void removeDropListener(const boost::signals2::connection& c);
/**
* \brief Set the header receipt callback
*/
void setHeaderReceivedCallback(const HeaderReceivedFunc& func);
/**
* \brief Get the Transport associated with this connection
*/
const TransportPtr& getTransport() { return transport_; }
/**
* \brief Get the Header associated with this connection
*/
Header& getHeader() { return header_; }
/**
* \brief Set the Header associated with this connection (used with UDPROS,
* which receives the connection during XMLRPC negotiation).
*/
void setHeader(const Header& header) { header_ = header; }
std::string getCallerId();
std::string getRemoteString();
std::string getRemoteIp();
std::string getLocalIp();
private:
/**
* \brief Called by the Transport when there is data available to be read
*/
void onReadable(const TransportPtr& transport);
/**
* \brief Called by the Transport when it is possible to write data
*/
void onWriteable(const TransportPtr& transport);
/**
* \brief Called by the Transport when it has been disconnected, either through a call to close()
* or through an error in the connection (such as a remote disconnect)
*/
void onDisconnect(const TransportPtr& transport);
void onHeaderWritten(const ConnectionPtr& conn);
void onErrorHeaderWritten(const ConnectionPtr& conn);
void onHeaderLengthRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success);
void onHeaderRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success);
/**
* \brief Read data off our transport. Also manages calling the read callback. If there is any data to be read,
* read() will read it until the fixed read buffer is filled.
*/
void readTransport();
/**
* \brief Write data to our transport. Also manages calling the write callback.
*/
void writeTransport();
/// Are we a server? Servers wait for clients to send a header and then send a header in response.
bool is_server_;
/// Have we dropped?
bool dropped_;
/// Incoming header
Header header_;
/// Transport associated with us
TransportPtr transport_;
/// Function that handles the incoming header
HeaderReceivedFunc header_func_;
/// Read buffer that ends up being passed to the read callback
boost::shared_array<uint8_t> read_buffer_;
/// Amount of data currently in the read buffer, in bytes
uint32_t read_filled_;
/// Size of the read buffer, in bytes
uint32_t read_size_;
/// Function to call when the read is finished
ReadFinishedFunc read_callback_;
/// Mutex used for protecting reading. Recursive because a read can immediately cause another read through the callback.
boost::recursive_mutex read_mutex_;
/// Flag telling us if we're in the middle of a read (mostly to avoid recursive deadlocking)
bool reading_;
/// flag telling us if there is a read callback
/// 32-bit loads and stores are atomic on x86 and PPC... TODO: use a cross-platform atomic operations library
/// to ensure this is done atomically
volatile uint32_t has_read_callback_;
/// Buffer to write from
boost::shared_array<uint8_t> write_buffer_;
/// Amount of data we've written from the write buffer
uint32_t write_sent_;
/// Size of the write buffer
uint32_t write_size_;
/// Function to call when the current write is finished
WriteFinishedFunc write_callback_;
boost::mutex write_callback_mutex_;
/// Mutex used for protecting writing. Recursive because a write can immediately cause another write through the callback
boost::recursive_mutex write_mutex_;
/// Flag telling us if we're in the middle of a write (mostly used to avoid recursive deadlocking)
bool writing_;
/// flag telling us if there is a write callback
/// 32-bit loads and stores are atomic on x86 and PPC... TODO: use a cross-platform atomic operations library
/// to ensure this is done atomically
volatile uint32_t has_write_callback_;
/// Function to call when the outgoing header has finished writing
WriteFinishedFunc header_written_callback_;
/// Signal raised when this connection is dropped
DropSignal drop_signal_;
/// Synchronizes drop() calls
boost::recursive_mutex drop_mutex_;
/// If we're sending a header error we disable most other calls
bool sending_header_error_;
};
typedef boost::shared_ptr<Connection> ConnectionPtr;
} // namespace ros
#endif // ROSCPP_CONNECTION_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/node_handle.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_NODE_HANDLE_H
#define ROSCPP_NODE_HANDLE_H
#include "ros/forwards.h"
#include "ros/publisher.h"
#include "ros/subscriber.h"
#include "ros/service_server.h"
#include "ros/service_client.h"
#include "ros/timer.h"
#include "ros/rate.h"
#include "ros/wall_timer.h"
#include "ros/advertise_options.h"
#include "ros/advertise_service_options.h"
#include "ros/subscribe_options.h"
#include "ros/service_client_options.h"
#include "ros/timer_options.h"
#include "ros/wall_timer_options.h"
#include "ros/spinner.h"
#include "ros/init.h"
#include "common.h"
#include <boost/bind.hpp>
#include <XmlRpcValue.h>
namespace ros
{
class NodeHandleBackingCollection;
/**
* \brief roscpp's interface for creating subscribers, publishers, etc.
*
* This class is used for writing nodes. It provides a RAII interface
* to this process' node, in that when the first NodeHandle is
* created, it instantiates everything necessary for this node, and
* when the last NodeHandle goes out of scope it shuts down the node.
*
* NodeHandle uses reference counting internally, and copying a
* NodeHandle is very lightweight.
*
* You must call one of the ros::init functions prior to instantiating
* this class.
*
* The most widely used methods are:
* - Setup:
* - ros::init()
* - Publish / subscribe messaging:
* - advertise()
* - subscribe()
* - RPC services:
* - advertiseService()
* - serviceClient()
* - ros::service::call()
* - Parameters:
* - getParam()
* - setParam()
*/
class ROSCPP_DECL NodeHandle
{
public:
/**
* \brief Constructor
*
* When a NodeHandle is constructed, it checks to see if the global
* node state has already been started. If so, it increments a
* global reference count. If not, it starts the node with
* ros::start() and sets the reference count to 1.
*
* \param ns Namespace for this NodeHandle. This acts in addition to any namespace assigned to this ROS node.
* eg. If the node's namespace is "/a" and the namespace passed in here is "b", all
* topics/services/parameters will be prefixed with "/a/b/"
* \param remappings Remappings for this NodeHandle.
* \throws InvalidNameException if the namespace is not a valid graph resource name
*/
NodeHandle(const std::string& ns = std::string(), const M_string& remappings = M_string());
/**
* \brief Copy constructor
*
* When a NodeHandle is copied, it inherits the namespace of the
* NodeHandle being copied, and increments the reference count of
* the global node state by 1.
*/
NodeHandle(const NodeHandle& rhs);
/**
* \brief Parent constructor
*
* This version of the constructor takes a "parent" NodeHandle.
* If the passed "ns" is relative (does not start with a slash), it is equivalent to calling:
\verbatim
NodeHandle child(parent.getNamespace() + "/" + ns);
\endverbatim
*
* If the passed "ns" is absolute (does start with a slash), it is equivalent to calling:
\verbatim
NodeHandle child(ns);
\endverbatim
*
* When a NodeHandle is copied, it inherits the namespace of the
* NodeHandle being copied, and increments the reference count of
* the global node state by 1.
*
* \throws InvalidNameException if the namespace is not a valid
* graph resource name
*/
NodeHandle(const NodeHandle& parent, const std::string& ns);
/**
* \brief Parent constructor
*
* This version of the constructor takes a "parent" NodeHandle.
* If the passed "ns" is relative (does not start with a slash), it is equivalent to calling:
\verbatim
NodeHandle child(parent.getNamespace() + "/" + ns, remappings);
\endverbatim
*
* If the passed "ns" is absolute (does start with a slash), it is equivalent to calling:
\verbatim
NodeHandle child(ns, remappings);
\endverbatim
*
* This version also lets you pass in name remappings that are specific to this NodeHandle
*
* When a NodeHandle is copied, it inherits the namespace of the NodeHandle being copied,
* and increments the reference count of the global node state
* by 1.
* \throws InvalidNameException if the namespace is not a valid graph resource name
*/
NodeHandle(const NodeHandle& parent, const std::string& ns, const M_string& remappings);
/**
* \brief Destructor
*
* When a NodeHandle is destroyed, it decrements a global reference
* count by 1, and if the reference count is now 0, shuts down the
* node.
*/
~NodeHandle();
NodeHandle& operator=(const NodeHandle& rhs);
/**
* \brief Set the default callback queue to be used by this NodeHandle.
*
* Setting this will cause any callbacks from
* advertisements/subscriptions/services/etc. to happen through the
* use of the specified queue. NULL (the default) causes the global
* queue (serviced by ros::spin() and ros::spinOnce()) to be used.
*/
void setCallbackQueue(CallbackQueueInterface* queue);
/**
* \brief Returns the callback queue associated with this
* NodeHandle. If none has been explicitly set, returns the global
* queue.
*/
CallbackQueueInterface* getCallbackQueue() const
{
return callback_queue_ ? callback_queue_ : (CallbackQueueInterface*)getGlobalCallbackQueue();
}
/**
* \brief Returns the namespace associated with this NodeHandle
*/
const std::string& getNamespace() const { return namespace_; }
/**
* \brief Returns the namespace associated with this NodeHandle as
* it was passed in (before it was resolved)
*/
const std::string& getUnresolvedNamespace() const { return unresolved_namespace_; }
/** \brief Resolves a name into a fully-qualified name
*
* Resolves a name into a fully qualified name, eg. "blah" =>
* "/namespace/blah". By default also applies any matching
* name-remapping rules (which were usually supplied on the command
* line at startup) to the given name, returning the resulting
* remapped name.
*
* \param name Name to remap
*
* \param remap Whether to apply name-remapping rules
*
* \return Resolved name.
*
* \throws InvalidNameException If the name begins with a tilde, or is an otherwise invalid graph resource name
*/
std::string resolveName(const std::string& name, bool remap = true) const;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of advertise()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief Advertise a topic, simple version
*
* This call connects to the master to publicize that the node will be
* publishing messages on the given topic. This method returns a Publisher that allows you to
* publish a message on this topic.
*
* This version of advertise is a templated convenience function, and can be used like so
*
* ros::Publisher pub = handle.advertise<std_msgs::Empty>("my_topic", 1);
*
* \param topic Topic to advertise on
*
* \param queue_size Maximum number of outgoing messages to be
* queued for delivery to subscribers
*
* \param latch (optional) If true, the last message published on
* this topic will be saved and sent to new subscribers when they
* connect
*
* \return On success, a Publisher that, when it goes out of scope,
* will automatically release a reference on this advertisement. On
* failure, an empty Publisher.
*
* \throws InvalidNameException If the topic name begins with a
* tilde, or is an otherwise invalid graph resource name, or is an
* otherwise invalid graph resource name
*/
template <class M>
Publisher advertise(const std::string& topic, uint32_t queue_size, bool latch = false)
{
AdvertiseOptions ops;
ops.template init<M>(topic, queue_size);
ops.latch = latch;
return advertise(ops);
}
/**
* \brief Advertise a topic, with most of the available options, including subscriber status callbacks
*
* This call connects to the master to publicize that the node will be
* publishing messages on the given topic. This method returns a Publisher that allows you to
* publish a message on this topic.
*
* This version of advertise allows you to pass functions to be called when new subscribers connect and
* disconnect. With bare functions it can be used like so:
\verbatim
void connectCallback(const ros::SingleSubscriberPublisher& pub)
{
// Do something
}
handle.advertise<std_msgs::Empty>("my_topic", 1, (ros::SubscriberStatusCallback)connectCallback);
\endverbatim
*
* With class member functions it can be used with boost::bind:
\verbatim
void MyClass::connectCallback(const ros::SingleSubscriberPublisher& pub)
{
// Do something
}
MyClass my_class;
ros::Publisher pub = handle.advertise<std_msgs::Empty>("my_topic", 1,
boost::bind(&MyClass::connectCallback, my_class, _1));
\endverbatim
*
*
* \param topic Topic to advertise on
*
* \param queue_size Maximum number of outgoing messages to be queued for delivery to subscribers
*
* \param connect_cb Function to call when a subscriber connects
*
* \param disconnect_cb (optional) Function to call when a subscriber disconnects
*
* \param tracked_object (optional) A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
* Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
* \param latch (optional) If true, the last message published on this topic will be saved and sent to new subscribers when they connect
* \return On success, a Publisher that, when it goes out of scope, will automatically release a reference
* on this advertisement. On failure, an empty Publisher which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
ros::publisher pub = nodeHandle.advertise<std_msgs::Empty>("my_topic", 1, (ros::SubscriberStatusCallback)callback);
if (pub) // Enter if publisher is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
*/
template <class M>
Publisher advertise(const std::string& topic, uint32_t queue_size,
const SubscriberStatusCallback& connect_cb,
const SubscriberStatusCallback& disconnect_cb = SubscriberStatusCallback(),
const VoidConstPtr& tracked_object = VoidConstPtr(),
bool latch = false)
{
AdvertiseOptions ops;
ops.template init<M>(topic, queue_size, connect_cb, disconnect_cb);
ops.tracked_object = tracked_object;
ops.latch = latch;
return advertise(ops);
}
/**
* \brief Advertise a topic, with full range of AdvertiseOptions
*
* This call connects to the master to publicize that the node will be
* publishing messages on the given topic. This method returns a Publisher that allows you to
* publish a message on this topic.
*
* This is an advanced version advertise() that exposes all options (through the AdvertiseOptions structure)
*
* \param ops Advertise options to use
* \return On success, a Publisher that, when it goes out of scope, will automatically release a reference
* on this advertisement. On failure, an empty Publisher which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
ros::AdvertiseOptions ops;
...
ros::publisher pub = nodeHandle.advertise(ops);
if (pub) // Enter if publisher is valid
{
...
}
\endverbatim
*
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
*/
Publisher advertise(AdvertiseOptions& ops);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of subscribe()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief Subscribe to a topic, version for class member function with bare pointer
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using member functions, and can be used like so:
\verbatim
void Foo::callback(const std_msgs::Empty::ConstPtr& message)
{
}
Foo foo_object;
ros::Subscriber sub = handle.subscribe("my_topic", 1, &Foo::callback, &foo_object);
\endverbatim
*
* \param M [template] M here is the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&), \b not the message type, and should almost always be deduced
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Member function pointer to call when a message has arrived
* \param obj Object to call fp on
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
void Foo::callback(const std_msgs::Empty::ConstPtr& message) {}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, &Foo::callback, foo_object);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(T::*fp)(M), T* obj,
const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<M>(topic, queue_size, boost::bind(fp, obj, _1));
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/// and the const version
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(T::*fp)(M) const, T* obj,
const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<M>(topic, queue_size, boost::bind(fp, obj, _1));
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for class member function with bare pointer
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using member functions, and can be used like so:
\verbatim
void Foo::callback(const std_msgs::Empty::ConstPtr& message)
{
}
Foo foo_object;
ros::Subscriber sub = handle.subscribe("my_topic", 1, &Foo::callback, &foo_object);
\endverbatim
*
* \param M [template] M here is the message type
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Member function pointer to call when a message has arrived
* \param obj Object to call fp on
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
void Foo::callback(const std_msgs::Empty::ConstPtr& message) {}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, &Foo::callback, foo_object);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size,
void(T::*fp)(const boost::shared_ptr<M const>&), T* obj,
const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, boost::bind(fp, obj, _1));
ops.transport_hints = transport_hints;
return subscribe(ops);
}
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size,
void(T::*fp)(const boost::shared_ptr<M const>&) const, T* obj,
const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, boost::bind(fp, obj, _1));
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for class member function with shared_ptr
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using member functions on a shared_ptr:
\verbatim
void Foo::callback(const std_msgs::Empty::ConstPtr& message)
{
}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = handle.subscribe("my_topic", 1, &Foo::callback, foo_object);
\endverbatim
*
* \param M [template] M here is the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&), \b not the message type, and should almost always be deduced
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Member function pointer to call when a message has arrived
* \param obj Object to call fp on. Since this is a shared pointer, the object will automatically be tracked with a weak_ptr
* so that if it is deleted before the Subscriber goes out of scope the callback will no longer be called (and therefore will not crash).
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
void Foo::callback(const std_msgs::Empty::ConstPtr& message) {}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, &Foo::callback, foo_object);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(T::*fp)(M),
const boost::shared_ptr<T>& obj, const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<M>(topic, queue_size, boost::bind(fp, obj.get(), _1));
ops.tracked_object = obj;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(T::*fp)(M) const,
const boost::shared_ptr<T>& obj, const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<M>(topic, queue_size, boost::bind(fp, obj.get(), _1));
ops.tracked_object = obj;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for class member function with shared_ptr
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using member functions on a shared_ptr:
\verbatim
void Foo::callback(const std_msgs::Empty::ConstPtr& message)
{
}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = handle.subscribe("my_topic", 1, &Foo::callback, foo_object);
\endverbatim
*
* \param M [template] M here is the message type
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Member function pointer to call when a message has arrived
* \param obj Object to call fp on. Since this is a shared pointer, the object will automatically be tracked with a weak_ptr
* so that if it is deleted before the Subscriber goes out of scope the callback will no longer be called (and therefore will not crash).
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
ros::NodeHandle nodeHandle;
void Foo::callback(const std_msgs::Empty::ConstPtr& message) {}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, &Foo::callback, foo_object);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size,
void(T::*fp)(const boost::shared_ptr<M const>&),
const boost::shared_ptr<T>& obj, const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, boost::bind(fp, obj.get(), _1));
ops.tracked_object = obj;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
template<class M, class T>
Subscriber subscribe(const std::string& topic, uint32_t queue_size,
void(T::*fp)(const boost::shared_ptr<M const>&) const,
const boost::shared_ptr<T>& obj, const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, boost::bind(fp, obj.get(), _1));
ops.tracked_object = obj;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for bare function
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using bare functions, and can be used like so:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message)
{
}
ros::Subscriber sub = handle.subscribe("my_topic", 1, callback);
\endverbatim
*
* \param M [template] M here is the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&), \b not the message type, and should almost always be deduced
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Function pointer to call when a message has arrived
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message){...}
ros::NodeHandle nodeHandle;
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, callback);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(*fp)(M), const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<M>(topic, queue_size, fp);
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for bare function
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe is a convenience function for using bare functions, and can be used like so:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message)
{
}
ros::Subscriber sub = handle.subscribe("my_topic", 1, callback);
\endverbatim
*
* \param M [template] M here is the message type
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param fp Function pointer to call when a message has arrived
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message){...}
ros::NodeHandle nodeHandle;
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, callback);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(*fp)(const boost::shared_ptr<M const>&), const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, fp);
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for arbitrary boost::function object
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, callback is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe allows anything bindable to a boost::function object
*
* \param M [template] M here is the message type
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param callback Callback to call when a message has arrived
* \param tracked_object A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
* Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message){...}
ros::NodeHandle nodeHandle;
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, callback);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, const boost::function<void (const boost::shared_ptr<M const>&)>& callback,
const VoidConstPtr& tracked_object = VoidConstPtr(), const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template init<M>(topic, queue_size, callback);
ops.tracked_object = tracked_object;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version for arbitrary boost::function object
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, callback is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe allows anything bindable to a boost::function object
*
* \param M [template] the message type
* \param C [template] the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&)
* \param topic Topic to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param callback Callback to call when a message has arrived
* \param tracked_object A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
* Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
* \param transport_hints a TransportHints structure which defines various transport-related options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
void callback(const std_msgs::Empty::ConstPtr& message){...}
ros::NodeHandle nodeHandle;
ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, callback);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
template<class M, class C>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, const boost::function<void (C)>& callback,
const VoidConstPtr& tracked_object = VoidConstPtr(), const TransportHints& transport_hints = TransportHints())
{
SubscribeOptions ops;
ops.template initByFullCallbackType<C>(topic, queue_size, callback);
ops.tracked_object = tracked_object;
ops.transport_hints = transport_hints;
return subscribe(ops);
}
/**
* \brief Subscribe to a topic, version with full range of SubscribeOptions
*
* This method connects to the master to register interest in a given
* topic. The node will automatically be connected with publishers on
* this topic. On each message receipt, fp is invoked and passed a shared pointer
* to the message received. This message should \b not be changed in place, as it
* is shared with any other subscriptions to this topic.
*
* This version of subscribe allows the full range of options, exposed through the SubscribeOptions class
*
* \param ops Subscribe options
* \return On success, a Subscriber that, when all copies of it go out of scope, will unsubscribe from this topic.
* On failure, an empty Subscriber which can be checked with:
\verbatim
SubscribeOptions ops;
...
ros::NodeHandle nodeHandle;
ros::Subscriber sub = nodeHandle.subscribe(ops);
if (sub) // Enter if subscriber is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the topic name begins with a tilde, or is an otherwise invalid graph resource name
* \throws ConflictingSubscriptionException If this node is already subscribed to the same topic with a different datatype
*/
Subscriber subscribe(SubscribeOptions& ops);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of advertiseService()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief Advertise a service, version for class member function with bare pointer
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using member functions, and can be used like so:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
Foo foo_object;
ros::ServiceServer service = handle.advertiseService("my_service", &Foo::callback, &foo_object);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func Member function pointer to call when a message has arrived
* \param obj Object to call srv_func on
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", &Foo::callback, &foo_object);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name, or is an otherwise invalid graph resource name
*/
template<class T, class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(T::*srv_func)(MReq &, MRes &), T *obj)
{
AdvertiseServiceOptions ops;
ops.template init<MReq, MRes>(service, boost::bind(srv_func, obj, _1, _2));
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for class member function with bare pointer using ros::ServiceEvent as the callback parameter type
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using member functions, and can be used like so:
\verbatim
bool Foo::callback(ros::ServiceEvent<std_srvs::Empty::Request, std_srvs::Empty::Response>& event)
{
return true;
}
Foo foo_object;
ros::ServiceServer service = handle.advertiseService("my_service", &Foo::callback, &foo_object);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func Member function pointer to call when a message has arrived
* \param obj Object to call srv_func on
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", &Foo::callback, &foo_object);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name, or is an otherwise invalid graph resource name
*/
template<class T, class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(T::*srv_func)(ServiceEvent<MReq, MRes>&), T *obj)
{
AdvertiseServiceOptions ops;
ops.template initBySpecType<ServiceEvent<MReq, MRes> >(service, boost::bind(srv_func, obj, _1));
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for class member function with shared_ptr
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using member functions on shared pointers, and can be used like so:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::ServiceServer service = handle.advertiseService("my_service", &Foo::callback, foo_object);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func Member function pointer to call when a message has arrived
* \param obj Object to call srv_func on. Since this is a shared_ptr, it will automatically be tracked with a weak_ptr,
* and if the object is deleted the service callback will stop being called (and therefore will not crash).
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", &Foo::callback, &foo_object);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class T, class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(T::*srv_func)(MReq &, MRes &), const boost::shared_ptr<T>& obj)
{
AdvertiseServiceOptions ops;
ops.template init<MReq, MRes>(service, boost::bind(srv_func, obj.get(), _1, _2));
ops.tracked_object = obj;
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for class member function with shared_ptr using ros::ServiceEvent as the callback parameter type
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using member functions on shared pointers, and can be used like so:
\verbatim
bool Foo::callback(ros::ServiceEvent<std_srvs::Empty, std_srvs::Empty>& event)
{
return true;
}
boost::shared_ptr<Foo> foo_object(boost::make_shared<Foo>());
ros::ServiceServer service = handle.advertiseService("my_service", &Foo::callback, foo_object);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func Member function pointer to call when a message has arrived
* \param obj Object to call srv_func on. Since this is a shared_ptr, it will automatically be tracked with a weak_ptr,
* and if the object is deleted the service callback will stop being called (and therefore will not crash).
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", &Foo::callback, &foo_object);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class T, class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(T::*srv_func)(ServiceEvent<MReq, MRes>&), const boost::shared_ptr<T>& obj)
{
AdvertiseServiceOptions ops;
ops.template initBySpecType<ServiceEvent<MReq, MRes> >(service, boost::bind(srv_func, obj.get(), _1));
ops.tracked_object = obj;
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for bare function
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using bare functions, and can be used like so:
\verbatim
bool callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::ServiceServer service = handle.advertiseService("my_service", callback);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func function pointer to call when a message has arrived
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", callback);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(*srv_func)(MReq&, MRes&))
{
AdvertiseServiceOptions ops;
ops.template init<MReq, MRes>(service, srv_func);
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for bare function using ros::ServiceEvent as the callback parameter type
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This is a convenience function for using bare functions, and can be used like so:
\verbatim
bool callback(ros::ServiceEvent<std_srvs::Empty, std_srvs::Empty>& event)
{
return true;
}
ros::ServiceServer service = handle.advertiseService("my_service", callback);
\endverbatim
*
* \param service Service name to advertise on
* \param srv_func function pointer to call when a message has arrived
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", callback);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(*srv_func)(ServiceEvent<MReq, MRes>&))
{
AdvertiseServiceOptions ops;
ops.template initBySpecType<ServiceEvent<MReq, MRes> >(service, srv_func);
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for arbitrary boost::function object
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This version of advertiseService allows non-class functions, as well as functor objects and boost::bind (along with anything
* else boost::function supports).
*
* \param service Service name to advertise on
* \param callback Callback to call when the service is called
* \param tracked_object A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
* Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", callback);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, const boost::function<bool(MReq&, MRes&)>& callback,
const VoidConstPtr& tracked_object = VoidConstPtr())
{
AdvertiseServiceOptions ops;
ops.template init<MReq, MRes>(service, callback);
ops.tracked_object = tracked_object;
return advertiseService(ops);
}
/**
* \brief Advertise a service, version for arbitrary boost::function object using ros::ServiceEvent as the callback parameter type
*
* Note that the template parameter S is the full event type, e.g. ros::ServiceEvent<Req, Res>
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This version of advertiseService allows non-class functions, as well as functor objects and boost::bind (along with anything
* else boost::function supports).
*
* \param service Service name to advertise on
* \param callback Callback to call when the service is called
* \param tracked_object A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
* Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response)
{
return true;
}
ros::NodeHandle nodeHandle;
Foo foo_object;
ros::ServiceServer service = nodeHandle.advertiseService("my_service", callback);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class S>
ServiceServer advertiseService(const std::string& service, const boost::function<bool(S&)>& callback,
const VoidConstPtr& tracked_object = VoidConstPtr())
{
AdvertiseServiceOptions ops;
ops.template initBySpecType<S>(service, callback);
ops.tracked_object = tracked_object;
return advertiseService(ops);
}
/**
* \brief Advertise a service, with full range of AdvertiseServiceOptions
*
* This call connects to the master to publicize that the node will be
* offering an RPC service with the given name.
*
* This version of advertiseService allows the full set of options, exposed through the AdvertiseServiceOptions class
*
* \param ops Advertise options
* \return On success, a ServiceServer that, when all copies of it go out of scope, will unadvertise this service.
* On failure, an empty ServiceServer which can be checked with:
\verbatim
AdvertiseServiceOptions ops;
...
ros::NodeHandle nodeHandle;
ros::ServiceServer service = nodeHandle.advertiseService(ops);
if (service) // Enter if advertised service is valid
{
...
}
\endverbatim
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
ServiceServer advertiseService(AdvertiseServiceOptions& ops);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of serviceClient()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @brief Create a client for a service, version templated on two message types
*
* When the last handle reference of a persistent connection is cleared, the connection will automatically close.
*
* @param service_name The name of the service to connect to
* @param persistent Whether this connection should persist. Persistent services keep the connection to the remote host active
* so that subsequent calls will happen faster. In general persistent services are discouraged, as they are not as
* robust to node failure as non-persistent services.
* @param header_values Key/value pairs you'd like to send along in the connection handshake
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class MReq, class MRes>
ServiceClient serviceClient(const std::string& service_name, bool persistent = false,
const M_string& header_values = M_string())
{
ServiceClientOptions ops;
ops.template init<MReq, MRes>(service_name, persistent, header_values);
return serviceClient(ops);
}
/** @brief Create a client for a service, version templated on service type
*
* When the last handle reference of a persistent connection is cleared, the connection will automatically close.
*
* @param service_name The name of the service to connect to
* @param persistent Whether this connection should persist. Persistent services keep the connection to the remote host active
* so that subsequent calls will happen faster. In general persistent services are discouraged, as they are not as
* robust to node failure as non-persistent services.
* @param header_values Key/value pairs you'd like to send along in the connection handshake
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
template<class Service>
ServiceClient serviceClient(const std::string& service_name, bool persistent = false,
const M_string& header_values = M_string())
{
ServiceClientOptions ops;
ops.template init<Service>(service_name, persistent, header_values);
return serviceClient(ops);
}
/** @brief Create a client for a service, version with full range of ServiceClientOptions
*
* When the last handle reference of a persistent connection is cleared, the connection will automatically close.
*
* @param ops The options for this service client
* \throws InvalidNameException If the service name begins with a tilde, or is an otherwise invalid graph resource name
*/
ServiceClient serviceClient(ServiceClientOptions& ops);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of createTimer()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief Create a timer which will call a callback at the specified rate. This variant takes
* a class member function, and a bare pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param r The rate at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
template<class Handler, class Obj>
Timer createTimer(Rate r, Handler h, Obj o, bool oneshot = false, bool autostart = true) const
{
return createTimer(r.expectedCycleTime(), h, o, oneshot, autostart);
}
/**
* \brief Create a timer which will call a callback at the specified rate. This variant takes
* a class member function, and a bare pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
template<class T>
Timer createTimer(Duration period, void(T::*callback)(const TimerEvent&) const, T* obj,
bool oneshot = false, bool autostart = true) const
{
return createTimer(period, boost::bind(callback, obj, _1), oneshot, autostart);
}
/**
* \brief Create a timer which will call a callback at the specified rate. This variant takes
* a class member function, and a bare pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
template<class T>
Timer createTimer(Duration period, void(T::*callback)(const TimerEvent&), T* obj,
bool oneshot = false, bool autostart = true) const
{
return createTimer(period, boost::bind(callback, obj, _1), oneshot, autostart);
}
/**
* \brief Create a timer which will call a callback at the specified rate. This variant takes
* a class member function, and a shared pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on. Since this is a shared pointer, the object will
* automatically be tracked with a weak_ptr so that if it is deleted before the Timer goes out of
* scope the callback will no longer be called (and therefore will not crash).
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
template<class T>
Timer createTimer(Duration period, void(T::*callback)(const TimerEvent&), const boost::shared_ptr<T>& obj,
bool oneshot = false, bool autostart = true) const
{
TimerOptions ops(period, boost::bind(callback, obj.get(), _1), 0);
ops.tracked_object = obj;
ops.oneshot = oneshot;
ops.autostart = autostart;
return createTimer(ops);
}
/**
* \brief Create a timer which will call a callback at the specified rate. This variant takes
* anything that can be bound to a Boost.Function, including a bare function
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The function to call
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
Timer createTimer(Duration period, const TimerCallback& callback, bool oneshot = false,
bool autostart = true) const;
/**
* \brief Create a timer which will call a callback at the specified rate. This variant allows
* the full range of TimerOptions.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param ops The options to use when creating the timer
*/
Timer createTimer(TimerOptions& ops) const;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Versions of createWallTimer()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief Create a timer which will call a callback at the specified rate, using wall time to determine
* when to call the callback instead of ROS time.
* This variant takes a class member function, and a bare pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on
* \param oneshot If true, this timer will only fire once
* \param autostart If true (default), return timer that is already started
*/
template<class T>
WallTimer createWallTimer(WallDuration period, void(T::*callback)(const WallTimerEvent&), T* obj,
bool oneshot = false, bool autostart = true) const
{
return createWallTimer(period, boost::bind(callback, obj, _1), oneshot, autostart);
}
/**
* \brief Create a timer which will call a callback at the specified rate, using wall time to determine
* when to call the callback instead of ROS time. This variant takes
* a class member function, and a shared pointer to the object to call the method on.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The method to call
* \param obj The object to call the method on. Since this is a shared pointer, the object will
* automatically be tracked with a weak_ptr so that if it is deleted before the Timer goes out of
* scope the callback will no longer be called (and therefore will not crash).
* \param oneshot If true, this timer will only fire once
*/
template<class T>
WallTimer createWallTimer(WallDuration period, void(T::*callback)(const WallTimerEvent&),
const boost::shared_ptr<T>& obj,
bool oneshot = false, bool autostart = true) const
{
WallTimerOptions ops(period, boost::bind(callback, obj.get(), _1), 0);
ops.tracked_object = obj;
ops.oneshot = oneshot;
ops.autostart = autostart;
return createWallTimer(ops);
}
/**
* \brief Create a timer which will call a callback at the specified rate, using wall time to determine
* when to call the callback instead of ROS time. This variant takes
* anything that can be bound to a Boost.Function, including a bare function
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param period The period at which to call the callback
* \param callback The function to call
* \param oneshot If true, this timer will only fire once
*/
WallTimer createWallTimer(WallDuration period, const WallTimerCallback& callback,
bool oneshot = false, bool autostart = true) const;
/**
* \brief Create a timer which will call a callback at the specified rate, using wall time to determine
* when to call the callback instead of ROS time. This variant allows
* the full range of TimerOptions.
*
* When the Timer (and all copies of it) returned goes out of scope, the timer will automatically
* be stopped, and the callback will no longer be called.
*
* \param ops The options to use when creating the timer
*/
WallTimer createWallTimer(WallTimerOptions& ops) const;
/** \brief Set an arbitrary XML/RPC value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param v The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const XmlRpc::XmlRpcValue& v) const;
/** \brief Set a string value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param s The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::string& s) const;
/** \brief Set a string value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param s The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const char* s) const;
/** \brief Set a double value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param d The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, double d) const;
/** \brief Set an integer value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param i The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, int i) const;
/** \brief Set a boolean value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param b The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, bool b) const;
/** \brief Set a string vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param vec The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::vector<std::string>& vec) const;
/** \brief Set a double vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param vec The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::vector<double>& vec) const;
/** \brief Set a float vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param vec The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::vector<float>& vec) const;
/** \brief Set a int vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param vec The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::vector<int>& vec) const;
/** \brief Set a bool vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param vec The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::vector<bool>& vec) const;
/** \brief Set a string vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param map The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::map<std::string, std::string>& map) const;
/** \brief Set a double vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param map The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::map<std::string, double>& map) const;
/** \brief Set a float vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param map The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::map<std::string, float>& map) const;
/** \brief Set a int vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param map The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::map<std::string, int>& map) const;
/** \brief Set a bool vector value on the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param map The value to be inserted.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
void setParam(const std::string& key, const std::map<std::string, bool>& map) const;
/** \brief Get a string value from the parameter server.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] s Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::string& s) const;
/** \brief Get a double value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] d Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, double& d) const;
/** \brief Get a float value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] f Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, float& f) const;
/** \brief Get an integer value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] i Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, int& i) const;
/** \brief Get a boolean value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] b Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, bool& b) const;
/** \brief Get an arbitrary XML/RPC value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] v Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, XmlRpc::XmlRpcValue& v) const;
/** \brief Get a string vector value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::vector<std::string>& vec) const;
/** \brief Get a double vector value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::vector<double>& vec) const;
/** \brief Get a float vector value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::vector<float>& vec) const;
/** \brief Get an int vector value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::vector<int>& vec) const;
/** \brief Get a boolean vector value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::vector<bool>& vec) const;
/** \brief Get a string map value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::map<std::string, std::string>& map) const;
/** \brief Get a double map value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::map<std::string, double>& map) const;
/** \brief Get a float map value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::map<std::string, float>& map) const;
/** \brief Get an int map value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::map<std::string, int>& map) const;
/** \brief Get a boolean map value from the parameter server.
*
* If you want to provide a default value in case the key does not exist use param().
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParam(const std::string& key, std::map<std::string, bool>& map) const;
/** \brief Get a string value from the parameter server, with local caching
*
* If you want to provide a default value in case the key does not exist use param().
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] s Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::string& s) const;
/** \brief Get a double value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] d Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, double& d) const;
/** \brief Get a float value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] f Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, float& f) const;
/** \brief Get an integer value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] i Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, int& i) const;
/** \brief Get a boolean value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] b Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, bool& b) const;
/** \brief Get an arbitrary XML/RPC value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] v Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, XmlRpc::XmlRpcValue& v) const;
/** \brief Get a std::string vector value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::vector<std::string>& vec) const;
/** \brief Get a double vector value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::vector<double>& vec) const;
/** \brief Get a float vector value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::vector<float>& vec) const;
/** \brief Get a int vector value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::vector<int>& vec) const;
/** \brief Get a bool vector value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] vec Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::vector<bool>& vec) const;
/** \brief Get a string->std::string map value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::map<std::string, std::string>& map) const;
/** \brief Get a string->double map value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::map<std::string, double>& map) const;
/** \brief Get a string->float map value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::map<std::string, float>& map) const;
/** \brief Get a string->int map value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::map<std::string, int>& map) const;
/** \brief Get a string->bool map value from the parameter server, with local caching
*
* This method will cache parameters locally, and subscribe for updates from
* the parameter server. Once the parameter is retrieved for the first time
* no subsequent getCached() calls with the same key will query the master --
* they will instead look up in the local cache.
*
* \param key The key to be used in the parameter server's dictionary
* \param[out] map Storage for the retrieved value.
*
* \return true if the parameter value was retrieved, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool getParamCached(const std::string& key, std::map<std::string, bool>& map) const;
/** \brief Check whether a parameter exists on the parameter server.
*
* \param key The key to check.
*
* \return true if the parameter exists, false otherwise
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool hasParam(const std::string& key) const;
/** \brief Search up the tree for a parameter with a given key
*
* This function parameter server's searchParam feature to search up the tree for
* a parameter. For example, if the parameter server has a parameter [/a/b]
* and you're in the namespace [/a/c/d], searching for the parameter "b" will
* yield [/a/b]. If [/a/c/d/b] existed, that parameter would be returned instead.
*
* \param key the parameter to search for
* \param [out] result the found value (if any)
*
* \return true if the parameter was found, false otherwise.
*/
bool searchParam(const std::string& key, std::string& result) const;
/** \brief Delete a parameter from the parameter server.
*
* \param key The key to delete.
*
* \return true if the deletion succeeded, false otherwise.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
bool deleteParam(const std::string& key) const;
/** \brief Get the keys for all the parameters in the parameter server.
* \param keys The keys retrieved.
* \return true if the query succeeded, false otherwise.
*/
bool getParamNames(std::vector<std::string>& keys) const;
/** \brief Assign value from parameter server, with default.
*
* This method tries to retrieve the indicated parameter value from the
* parameter server, storing the result in param_val. If the value
* cannot be retrieved from the server, default_val is used instead.
*
* \param param_name The key to be searched on the parameter server.
* \param[out] param_val Storage for the retrieved value.
* \param default_val Value to use if the server doesn't contain this
* parameter.
* \throws InvalidNameException If the parameter key begins with a tilde, or is an otherwise invalid graph resource name
*/
template<typename T>
void param(const std::string& param_name, T& param_val, const T& default_val) const
{
if (hasParam(param_name))
{
if (getParam(param_name, param_val))
{
return;
}
}
param_val = default_val;
}
/**
* \brief Return value from parameter server, or default if unavailable.
*
* This method tries to retrieve the indicated parameter value from the
* parameter server. If the parameter cannot be retrieved, \c default_val
* is returned instead.
*
* \param param_name The key to be searched on the parameter server.
*
* \param default_val Value to return if the server doesn't contain this
* parameter.
*
* \return The parameter value retrieved from the parameter server, or
* \c default_val if unavailable.
*
* \throws InvalidNameException If the parameter key begins with a tilde,
* or is an otherwise invalid graph resource name.
*/
template<typename T>
T param(const std::string& param_name, const T& default_val)
{
T param_val;
param(param_name, param_val, default_val);
return param_val;
}
/**
* \brief Shutdown every handle created through this NodeHandle.
*
* This method will unadvertise every topic and service advertisement,
* and unsubscribe every subscription created through this NodeHandle.
*/
void shutdown();
/** \brief Check whether it's time to exit.
*
* This method checks to see if both ros::ok() is true and shutdown() has not been called on this NodeHandle, to see whether it's yet time
* to exit. ok() is false once either ros::shutdown() or NodeHandle::shutdown() have been called
*
* \return true if we're still OK, false if it's time to exit
*/
bool ok() const;
private:
struct no_validate { };
// this is pretty awful, but required to preserve public interface (and make minimum possible changes)
std::string resolveName(const std::string& name, bool remap, no_validate) const;
void construct(const std::string& ns, bool validate_name);
void destruct();
void initRemappings(const M_string& remappings);
std::string remapName(const std::string& name) const;
std::string namespace_;
std::string unresolved_namespace_;
M_string remappings_;
M_string unresolved_remappings_;
CallbackQueueInterface* callback_queue_;
NodeHandleBackingCollection* collection_;
bool ok_;
};
}
#endif // ROSCPP_NODE_HANDLE_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/file_log.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_FILE_LOG_H
#define ROSCPP_FILE_LOG_H
#include "forwards.h"
#include <ros/console.h>
#include "common.h"
#define ROSCPP_LOG_DEBUG(...) ROS_DEBUG_NAMED("roscpp_internal", __VA_ARGS__)
namespace ros
{
/**
* \brief internal
*/
namespace file_log
{
// 20110418 TDS: this appears to be used only by rosout.
ROSCPP_DECL const std::string& getLogDirectory();
}
}
#endif // ROSCPP_FILE_LOG_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscribe_options.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_SUBSCRIBE_OPTIONS_H
#define ROSCPP_SUBSCRIBE_OPTIONS_H
#include "ros/forwards.h"
#include "common.h"
#include "ros/transport_hints.h"
#include "ros/message_traits.h"
#include "subscription_callback_helper.h"
#include "ros/names.h"
#include "roscpp/SharedMemoryHeader.h"
#include "sharedmem_transport/sharedmem_util.h"
namespace ros
{
/**
* \brief Encapsulates all options available for creating a Subscriber
*/
struct ROSCPP_DECL SubscribeOptions
{
/**
*
*/
SubscribeOptions()
: queue_size(1)
, callback_queue(0)
, allow_concurrent_callbacks(false)
{
}
/**
* \brief Constructor
* \param _topic Topic to subscribe on
* \param _queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param _md5sum
* \param _datatype
*/
SubscribeOptions(const std::string& _topic, uint32_t _queue_size, const std::string& _md5sum, const std::string& _datatype)
: topic(_topic)
, queue_size(_queue_size)
, md5sum(_md5sum)
, datatype(_datatype)
, callback_queue(0)
, allow_concurrent_callbacks(false)
{}
/**
* \brief Templated initialization, templated on callback parameter type. Supports any callback parameters supported by the SubscriptionCallbackAdapter
* \param _topic Topic to subscribe on
* \param _queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param _callback Callback to call when a message arrives on this topic
*/
template<class P>
void initByFullCallbackType(const std::string& _topic, uint32_t _queue_size,
const boost::function<void (P)>& _callback,
const boost::function<boost::shared_ptr<typename ParameterAdapter<P>::Message>(void)>& factory_fn = DefaultMessageCreator<typename ParameterAdapter<P>::Message>())
{
typedef typename ParameterAdapter<P>::Message MessageType;
topic = _topic;
queue_size = _queue_size;
md5sum = message_traits::md5sum<MessageType>();
datatype = message_traits::datatype<MessageType>();
helper = boost::make_shared<SubscriptionCallbackHelperT<P> >(_callback, factory_fn);
}
/**
* \brief Templated initialization, templated on message type. Only supports "const boost::shared_ptr<M const>&" callback types
* \param _topic Topic to subscribe on
* \param _queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param _callback Callback to call when a message arrives on this topic
*/
template<class M>
void init(const std::string& _topic, uint32_t _queue_size,
const boost::function<void (const boost::shared_ptr<M const>&)>& _callback,
const boost::function<boost::shared_ptr<M>(void)>& factory_fn = DefaultMessageCreator<M>())
{
typedef typename ParameterAdapter<M>::Message MessageType;
topic = _topic;
queue_size = _queue_size;
md5sum = message_traits::md5sum<MessageType>();
datatype = message_traits::datatype<MessageType>();
helper = boost::make_shared<SubscriptionCallbackHelperT<const boost::shared_ptr<MessageType const>&> >(_callback, factory_fn);
}
std::string topic; ///< Topic to subscribe to
uint32_t queue_size; ///< Number of incoming messages to queue up for processing (messages in excess of this queue capacity will be discarded).
std::string md5sum; ///< MD5 of the message datatype
std::string datatype; ///< Datatype of the message we'd like to subscribe as
SubscriptionCallbackHelperPtr helper; ///< Helper object used to get create messages and call callbacks
CallbackQueueInterface* callback_queue; ///< Queue to add callbacks to. If NULL, the global callback queue will be used
/// By default subscription callbacks are guaranteed to arrive in-order, with only one callback happening for this subscription at any given
/// time. Setting this to true allows you to receive multiple messages on the same topic from multiple threads at the same time
bool allow_concurrent_callbacks;
/**
* \brief An object whose destruction will prevent the callback associated with this subscription
*
* A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
*
* \note Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
*/
VoidConstPtr tracked_object;
TransportHints transport_hints; ///< Hints for transport type and options
/**
* \brief Templated helper function for creating an AdvertiseServiceOptions with most of its options
* \param topic Topic name to subscribe to
* \param queue_size Number of incoming messages to queue up for
* processing (messages in excess of this queue capacity will be
* discarded).
* \param callback The callback to invoke when a message is received on this topic
* \param tracked_object The tracked object to use (see SubscribeOptions::tracked_object)
* \param queue The callback queue to use (see SubscribeOptions::callback_queue)
*/
template<class M>
static SubscribeOptions create(const std::string& topic, uint32_t queue_size,
const boost::function<void (const boost::shared_ptr<M const>&)>& callback,
const VoidConstPtr& tracked_object, CallbackQueueInterface* queue)
{
SubscribeOptions ops;
ops.init<M>(topic, queue_size, callback);
ops.tracked_object = tracked_object;
ops.callback_queue = queue;
return ops;
}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport_hints.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_TRANSPORT_HINTS_H
#define ROSCPP_TRANSPORT_HINTS_H
#include "common.h"
#include "ros/forwards.h"
#include <boost/lexical_cast.hpp>
namespace ros
{
/**
* \brief Provides a way of specifying network transport hints to ros::NodeHandle::subscribe() and
* someday ros::NodeHandle::advertise()
*
* Uses the named parameter idiom, allowing you to do things like:
\verbatim
ros::TransportHints()
.unreliable()
.maxDatagramSize(1000)
.tcpNoDelay();
\endverbatim
*
* Hints for the transport type are used in the order they are specified, i.e. TransportHints().unreliable().reliable()
* specifies that you would prefer an unreliable transport, followed by a reliable one.
*/
class ROSCPP_DECL TransportHints
{
public:
/**
* \brief Specifies a reliable transport. Currently this means TCP
*/
TransportHints& reliable()
{
tcp();
return *this;
}
/**
* \brief Explicitly specifies the TCP transport
*/
TransportHints& tcp()
{
transports_.push_back("TCP");
return *this;
}
/**
* \brief If a TCP transport is used, specifies whether or not to use TCP_NODELAY to provide
* a potentially lower-latency connection.
*
* \param nodelay [optional] Whether or not to use TCP_NODELAY. Defaults to true.
*/
TransportHints& tcpNoDelay(bool nodelay = true)
{
options_["tcp_nodelay"] = nodelay ? "true" : "false";
return *this;
}
/**
* \brief Returns whether or not this TransportHints has specified TCP_NODELAY
*/
bool getTCPNoDelay()
{
M_string::iterator it = options_.find("tcp_nodelay");
if (it == options_.end())
{
return false;
}
const std::string& val = it->second;
if (val == "true")
{
return true;
}
return false;
}
/**
* \brief If a UDP transport is used, specifies the maximum datagram size.
*
* \param size The size, in bytes
*/
TransportHints& maxDatagramSize(int size)
{
options_["max_datagram_size"] = boost::lexical_cast<std::string>(size);
return *this;
}
/**
* \brief Returns the maximum datagram size specified on this TransportHints, or 0 if
* no size was specified.
*/
int getMaxDatagramSize()
{
M_string::iterator it = options_.find("max_datagram_size");
if (it == options_.end())
{
return 0;
}
return boost::lexical_cast<int>(it->second);
}
/**
* \brief Specifies an unreliable transport. Currently this means UDP.
*/
TransportHints& unreliable()
{
udp();
return *this;
}
/**
* \brief Explicitly specifies a UDP transport.
*/
TransportHints& udp()
{
transports_.push_back("UDP");
return *this;
}
/**
* \brief Returns a vector of transports, ordered by preference
*/
const V_string& getTransports() { return transports_; }
/**
* \brief Returns the map of options created by other methods inside TransportHints
*/
const M_string& getOptions() { return options_; }
private:
V_string transports_;
M_string options_;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/topic_manager.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_TOPIC_MANAGER_H
#define ROSCPP_TOPIC_MANAGER_H
#include "forwards.h"
#include "common.h"
#include "ros/serialization.h"
#include "rosout_appender.h"
#include "XmlRpcValue.h"
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include "sharedmem_transport/sharedmem_util.h"
#include <string.h>
#include <stdio.h>
namespace ros
{
class Message;
struct SubscribeOptions;
struct AdvertiseOptions;
class TopicManager;
typedef boost::shared_ptr<TopicManager> TopicManagerPtr;
class PollManager;
typedef boost::shared_ptr<PollManager> PollManagerPtr;
class XMLRPCManager;
typedef boost::shared_ptr<XMLRPCManager> XMLRPCManagerPtr;
class ConnectionManager;
typedef boost::shared_ptr<ConnectionManager> ConnectionManagerPtr;
class SubscriptionCallbackHelper;
typedef boost::shared_ptr<SubscriptionCallbackHelper> SubscriptionCallbackHelperPtr;
const std::string MANAGER_SHELL_ROSTOPIC_LIST = "rostopic list -v";
class ROSCPP_DECL TopicManager
{
public:
static const TopicManagerPtr& instance();
TopicManager();
~TopicManager();
void start();
void shutdown();
bool subscribe(const SubscribeOptions& ops);
bool unsubscribe(const std::string &_topic, const SubscriptionCallbackHelperPtr& helper);
bool advertise(const AdvertiseOptions& ops, const SubscriberCallbacksPtr& callbacks);
bool unadvertise(const std::string &topic, const SubscriberCallbacksPtr& callbacks);
/** @brief Get the list of topics advertised by this node
*
* @param[out] topics The advertised topics
*/
void getAdvertisedTopics(V_string& topics);
/** @brief Get the list of topics subscribed to by this node
*
* @param[out] The subscribed topics
*/
void getSubscribedTopics(V_string& topics);
/** @brief Lookup an advertised topic.
*
* This method iterates over advertised_topics, looking for one with name
* matching the given topic name. The advertised_topics_mutex is locked
* during this search. This method is only used internally.
*
* @param topic The topic name to look for.
*
* @returns Pointer to the matching Publication, NULL if none is found.
*/
PublicationPtr lookupPublication(const std::string& topic);
SubscriptionPtr lookupSubscription(const std::string& topic);
/** @brief Return the number of subscribers a node has for a particular topic:
*
* @param _topic The topic name to check
*
* @return number of subscribers
*/
size_t getNumSubscribers(const std::string &_topic);
size_t getNumSubscriptions();
L_Subscription getAllSubscription();
/**
* \brief Return the number of publishers connected to this node on a particular topic
*
* \param _topic the topic name to check
* \return the number of subscribers
*/
size_t getNumPublishers(const std::string &_topic);
template<typename M>
void publish(const std::string& topic, const M& message)
{
using namespace serialization;
SerializedMessage m;
publish(topic, boost::bind(serializeMessage<M>, boost::ref(message)), m);
}
void publish(const std::string &_topic, const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& m);
void incrementSequence(const std::string &_topic);
bool isLatched(const std::string& topic);
/** @brief Update local publisher lists.
*
* Use this method to update address information for publishers on a
* given topic.
*
* @param topic The topic of interest
* @param pubs The list of publishers to update.
*
* @return true on success, false otherwise.
*/
bool pubUpdate(const std::string &topic, const std::vector<std::string> &pubs);
void registerPublisher(const std::string &topic, const std::string &datatype);
void registerPublisher(const std::string &topic);
void registerAllPublisher();
private:
/** if it finds a pre-existing subscription to the same topic and of the
* same message type, it appends the Functor to the callback vector for
* that subscription. otherwise, it returns false, indicating that a new
* subscription needs to be created.
*/
bool addSubCallback(const SubscribeOptions& ops);
/** @brief Request a topic
*
* Negotiate a subscriber connection on a topic.
*
* @param topic The topic of interest.
* @param protos List of transport protocols, in preference order
* @param ret Return value
*
* @return true on success, false otherwise
*
* @todo Consider making this private
*/
bool requestTopic(const std::string &topic, XmlRpc::XmlRpcValue &protos, XmlRpc::XmlRpcValue &ret);
// Must lock the advertised topics mutex before calling this function
bool isTopicAdvertised(const std::string& topic);
bool registerSubscriber(const SubscriptionPtr& s, const std::string& datatype);
bool unregisterSubscriber(const std::string& topic);
bool unregisterPublisher(const std::string& topic);
PublicationPtr lookupPublicationWithoutLock(const std::string &topic);
SubscriptionPtr lookupSubscriptionWithoutLock(const std::string &topic);
void processPublishQueues();
/** @brief Compute the statistics for the node's connectivity
*
* This is the implementation of the xml-rpc getBusStats function;
* it populates the XmlRpcValue object sent to it with various statistics
* about the node's connectivity, bandwidth utilization, etc.
*/
void getBusStats(XmlRpc::XmlRpcValue &stats);
/** @brief Compute the info for the node's connectivity
*
* This is the implementation of the xml-rpc getBusInfo function;
* it populates the XmlRpcValue object sent to it with various info
* about the node's connectivity.
*/
void getBusInfo(XmlRpc::XmlRpcValue &info);
/** @brief Return the list of subcriptions for the node
*
* This is the implementation of the xml-rpc getSubscriptions
* function; it populates the XmlRpcValue object sent to it with the
* list of subscribed topics and their datatypes.
*/
void getSubscriptions(XmlRpc::XmlRpcValue &subscriptions);
/** @brief Return the list of advertised topics for the node
*
* This is the implementation of the xml-rpc getPublications
* function; it populates the XmlRpcValue object sent to it with the
* list of advertised topics and their datatypes.
*/
void getPublications(XmlRpc::XmlRpcValue &publications);
void pubUpdateCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void requestTopicCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void getBusStatsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void getBusInfoCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void getSubscriptionsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void getPublicationsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result);
void checkAndRemoveSHMSegment(std::string topic);
bool isShuttingDown() { return shutting_down_; }
boost::mutex subs_mutex_;
L_Subscription subscriptions_;
boost::recursive_mutex advertised_topics_mutex_;
V_Publication advertised_topics_;
std::list<std::string> advertised_topic_names_;
boost::mutex advertised_topic_names_mutex_;
volatile bool shutting_down_;
boost::mutex shutting_down_mutex_;
boost::mutex remove_segment_mutex_;
PollManagerPtr poll_manager_;
ConnectionManagerPtr connection_manager_;
XMLRPCManagerPtr xmlrpc_manager_;
};
} // namespace ros
#endif // ROSCPP_TOPIC_MANAGER_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/advertise_options.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_ADVERTISE_OPTIONS_H
#define ROSCPP_ADVERTISE_OPTIONS_H
#include "ros/forwards.h"
#include "ros/message_traits.h"
#include "common.h"
namespace ros
{
/**
* \brief Encapsulates all options available for creating a Publisher
*/
struct ROSCPP_DECL AdvertiseOptions
{
AdvertiseOptions()
: callback_queue(0)
, latch(false)
{
}
/*
* \brief Constructor
* \param _topic Topic to publish on
* \param _queue_size Maximum number of outgoing messages to be queued for delivery to subscribers
* \param _md5sum The md5sum of the message datatype published on this topic
* \param _datatype Datatype of the message published on this topic (eg. "std_msgs/String")
* \param _connect_cb Function to call when a subscriber connects to this topic
* \param _disconnect_cb Function to call when a subscriber disconnects from this topic
*/
AdvertiseOptions(const std::string& _topic, uint32_t _queue_size, const std::string& _md5sum,
const std::string& _datatype, const std::string& _message_definition,
const SubscriberStatusCallback& _connect_cb = SubscriberStatusCallback(),
const SubscriberStatusCallback& _disconnect_cb = SubscriberStatusCallback())
: topic(_topic)
, queue_size(_queue_size)
, md5sum(_md5sum)
, datatype(_datatype)
, message_definition(_message_definition)
, connect_cb(_connect_cb)
, disconnect_cb(_disconnect_cb)
, callback_queue(0)
, latch(false)
, has_header(false)
{}
/**
* \brief templated helper function for automatically filling out md5sum, datatype and message definition
*
* \param M [template] Message type
* \param _topic Topic to publish on
* \param _queue_size Maximum number of outgoing messages to be queued for delivery to subscribers
* \param _connect_cb Function to call when a subscriber connects to this topic
* \param _disconnect_cb Function to call when a subscriber disconnects from this topic
*/
template <class M>
void init(const std::string& _topic, uint32_t _queue_size,
const SubscriberStatusCallback& _connect_cb = SubscriberStatusCallback(),
const SubscriberStatusCallback& _disconnect_cb = SubscriberStatusCallback())
{
topic = _topic;
queue_size = _queue_size;
connect_cb = _connect_cb;
disconnect_cb = _disconnect_cb;
md5sum = message_traits::md5sum<M>();
datatype = message_traits::datatype<M>();
message_definition = message_traits::definition<M>();
has_header = message_traits::hasHeader<M>();
}
std::string topic; ///< The topic to publish on
uint32_t queue_size; ///< The maximum number of outgoing messages to be queued for delivery to subscribers
std::string md5sum; ///< The md5sum of the message datatype published on this topic
std::string datatype; ///< The datatype of the message published on this topic (eg. "std_msgs/String")
std::string message_definition; ///< The full definition of the message published on this topic
SubscriberStatusCallback connect_cb; ///< The function to call when a subscriber connects to this topic
SubscriberStatusCallback disconnect_cb; ///< The function to call when a subscriber disconnects from this topic
CallbackQueueInterface* callback_queue; ///< Queue to add callbacks to. If NULL, the global callback queue will be used
/**
* \brief An object whose destruction will prevent the callbacks associated with this advertisement from being called
*
* A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object,
* and if the reference count goes to 0 the subscriber callbacks will not get called.
*
* \note Note that setting this will cause a new reference to be added to the object before the
* callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore
* thread) that the callback is invoked from.
*/
VoidConstPtr tracked_object;
/**
* \brief Whether or not this publication should "latch". A latching publication will automatically send out the last published message
* to any new subscribers.
*/
bool latch;
/** \brief Tells whether or not the message has a header. If it does, the sequence number will be written directly into the
* serialized bytes after the message has been serialized.
*/
bool has_header;
/**
* \brief Templated helper function for creating an AdvertiseOptions for a message type with most options.
*
* \param M [template] Message type
* \param topic Topic to publish on
* \param queue_size Maximum number of outgoing messages to be queued for delivery to subscribers
* \param connect_cb Function to call when a subscriber connects to this topic
* \param disconnect_cb Function to call when a subscriber disconnects from this topic
* \param tracked_object tracked object to use (see AdvertiseOptions::tracked_object)
* \param queue The callback queue to use (see AdvertiseOptions::callback_queue)
*
* \return an AdvertiseOptions which embodies the parameters
*/
template<class M>
static AdvertiseOptions create(const std::string& topic, uint32_t queue_size,
const SubscriberStatusCallback& connect_cb,
const SubscriberStatusCallback& disconnect_cb,
const VoidConstPtr& tracked_object,
CallbackQueueInterface* queue)
{
AdvertiseOptions ops;
ops.init<M>(topic, queue_size, connect_cb, disconnect_cb);
ops.tracked_object = tracked_object;
ops.callback_queue = queue;
return ops;
}
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/wall_timer.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_WALL_TIMER_H
#define ROSCPP_WALL_TIMER_H
#include "common.h"
#include "forwards.h"
#include "wall_timer_options.h"
namespace ros
{
/**
* \brief Manages a wall-clock timer callback
*
* A WallTimer should always be created through a call to NodeHandle::createWallTimer(), or copied from one
* that was. Once all copies of a specific
* WallTimer go out of scope, the callback associated with that handle will stop
* being called.
*/
class ROSCPP_DECL WallTimer
{
public:
WallTimer() {}
WallTimer(const WallTimer& rhs);
~WallTimer();
/**
* \brief Start the timer. Does nothing if the timer is already started.
*/
void start();
/**
* \brief Stop the timer. Once this call returns, no more callbacks will be called. Does
* nothing if the timer is already stopped.
*/
void stop();
/**
* \brief Returns whether or not the timer has any pending events to call.
*/
bool hasPending();
/**
* \brief Set the period of this timer
* \param reset Whether to reset the timer. If true, timer ignores elapsed time and next cb occurs at now()+period
*/
void setPeriod(const WallDuration& period, bool reset=true);
bool isValid() { return impl_ && impl_->isValid(); }
operator void*() { return isValid() ? (void*)1 : (void*)0; }
bool operator<(const WallTimer& rhs)
{
return impl_ < rhs.impl_;
}
bool operator==(const WallTimer& rhs)
{
return impl_ == rhs.impl_;
}
bool operator!=(const WallTimer& rhs)
{
return impl_ != rhs.impl_;
}
private:
WallTimer(const WallTimerOptions& ops);
class Impl
{
public:
Impl();
~Impl();
bool isValid();
bool hasPending();
void setPeriod(const WallDuration& period, bool reset=true);
void start();
void stop();
bool started_;
int32_t timer_handle_;
WallDuration period_;
WallTimerCallback callback_;
CallbackQueueInterface* callback_queue_;
VoidConstWPtr tracked_object_;
bool has_tracked_object_;
bool oneshot_;
};
typedef boost::shared_ptr<Impl> ImplPtr;
typedef boost::weak_ptr<Impl> ImplWPtr;
ImplPtr impl_;
friend class NodeHandle;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/shm_manager.h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROS_SHM_MANAGER_H
#define ROS_SHM_MANAGER_H
#include <memory>
#include <mutex>
#include <thread>
#include <map>
#include <boost/make_shared.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "ros/this_node.h"
#include "ros/ros.h"
#include "roscpp/SharedMemoryHeader.h"
#include "sharedmem_transport/sharedmem_util.h"
#include "ros/topic_manager.h"
#include "ros/subscription.h"
#include "ros/header.h"
#include "ros/this_node.h"
#include "ros/message_deserializer.h"
#include "ros/names.h"
#include <algorithm>
#include "ros/config_comm.h"
#include <thread>
namespace ros
{
class ShmManager;
typedef boost::shared_ptr<ShmManager> ShmManagerPtr;
class ShmManager
{
public:
static const ShmManagerPtr& instance();
ShmManager();
~ShmManager();
void start();
void shutdown();
inline bool isStarted()
{
return started_;
}
private:
struct ItemShm
{
boost::interprocess::managed_shared_memory* segment;
sharedmem_transport::SharedMemorySegment* segment_mgr;
sharedmem_transport::SharedMemoryBlock* descriptors_sub;
uint32_t queue_size;
uint8_t** addr_sub;
bool shm_poll_flag;
SubscriptionPtr shm_sub_ptr;
std::string topic_name;
std::string md5sum;
std::string callerid;
std::string datatype;
std::string message_definition;
};
std::map<std::string, ItemShm> shm_map_;
std::vector <std::thread> shm_threads_;
private:
void threadFunc();
std::thread server_thread_;
mutable std::mutex mutex_;
bool started_;
boost::interprocess::interprocess_mutex shm_sub_mutex_;
std::map<std::string, bool> shm_skip_first_msg_;
boost::mutex shm_map_mutex_;
boost::mutex shm_first_msg_map_mutex_;
};
}
#endif // ROS_SHM_MANAGER_H
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/xmlrpc_manager.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_XMLRPC_MANAGER_H
#define ROSCPP_XMLRPC_MANAGER_H
#include <string>
#include <set>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "common.h"
#include "XmlRpc.h"
#include <ros/time.h>
namespace ros
{
/**
* \brief internal
*/
namespace xmlrpc
{
XmlRpc::XmlRpcValue responseStr(int code, const std::string& msg, const std::string& response);
XmlRpc::XmlRpcValue responseInt(int code, const std::string& msg, int response);
XmlRpc::XmlRpcValue responseBool(int code, const std::string& msg, bool response);
}
class XMLRPCCallWrapper;
typedef boost::shared_ptr<XMLRPCCallWrapper> XMLRPCCallWrapperPtr;
class ROSCPP_DECL ASyncXMLRPCConnection : public boost::enable_shared_from_this<ASyncXMLRPCConnection>
{
public:
virtual ~ASyncXMLRPCConnection() {}
virtual void addToDispatch(XmlRpc::XmlRpcDispatch* disp) = 0;
virtual void removeFromDispatch(XmlRpc::XmlRpcDispatch* disp) = 0;
virtual bool check() = 0;
};
typedef boost::shared_ptr<ASyncXMLRPCConnection> ASyncXMLRPCConnectionPtr;
typedef std::set<ASyncXMLRPCConnectionPtr> S_ASyncXMLRPCConnection;
class ROSCPP_DECL CachedXmlRpcClient
{
public:
CachedXmlRpcClient(XmlRpc::XmlRpcClient *c)
: in_use_(false)
, client_(c)
{
}
bool in_use_;
ros::WallTime last_use_time_; // for reaping
XmlRpc::XmlRpcClient* client_;
static const ros::WallDuration s_zombie_time_; // how long before it is toasted
};
class XMLRPCManager;
typedef boost::shared_ptr<XMLRPCManager> XMLRPCManagerPtr;
typedef boost::function<void(XmlRpc::XmlRpcValue&, XmlRpc::XmlRpcValue&)> XMLRPCFunc;
class ROSCPP_DECL XMLRPCManager
{
public:
static const XMLRPCManagerPtr& instance();
XMLRPCManager();
~XMLRPCManager();
/** @brief Validate an XML/RPC response
*
* @param method The RPC method that was invoked.
* @param response The resonse that was received.
* @param payload The payload that was received.
*
* @return true if validation succeeds, false otherwise.
*
* @todo Consider making this private.
*/
bool validateXmlrpcResponse(const std::string& method,
XmlRpc::XmlRpcValue &response, XmlRpc::XmlRpcValue &payload);
/**
* @brief Get the xmlrpc server URI of this node
*/
inline const std::string& getServerURI() const { return uri_; }
inline uint32_t getServerPort() const { return port_; }
XmlRpc::XmlRpcClient* getXMLRPCClient(const std::string& host, const int port, const std::string& uri);
void releaseXMLRPCClient(XmlRpc::XmlRpcClient* c);
void addASyncConnection(const ASyncXMLRPCConnectionPtr& conn);
void removeASyncConnection(const ASyncXMLRPCConnectionPtr& conn);
bool bind(const std::string& function_name, const XMLRPCFunc& cb);
void unbind(const std::string& function_name);
void start(int port = 0);
void shutdown();
bool isShuttingDown() { return shutting_down_; }
private:
void serverThreadFunc();
std::string uri_;
int port_;
boost::thread server_thread_;
#if defined(__APPLE__)
// OSX has problems with lots of concurrent xmlrpc calls
boost::mutex xmlrpc_call_mutex_;
#endif
XmlRpc::XmlRpcServer server_;
typedef std::vector<CachedXmlRpcClient> V_CachedXmlRpcClient;
V_CachedXmlRpcClient clients_;
boost::mutex clients_mutex_;
bool shutting_down_;
ros::WallDuration master_retry_timeout_;
S_ASyncXMLRPCConnection added_connections_;
boost::mutex added_connections_mutex_;
S_ASyncXMLRPCConnection removed_connections_;
boost::mutex removed_connections_mutex_;
S_ASyncXMLRPCConnection connections_;
struct FunctionInfo
{
std::string name;
XMLRPCFunc function;
XMLRPCCallWrapperPtr wrapper;
};
typedef std::map<std::string, FunctionInfo> M_StringToFuncInfo;
boost::mutex functions_mutex_;
M_StringToFuncInfo functions_;
volatile bool unbind_requested_;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/this_node.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_THIS_NODE_H
#define ROSCPP_THIS_NODE_H
#include "common.h"
#include "forwards.h"
namespace ros
{
/**
* \brief Contains functions which provide information about this process' ROS node
*/
namespace this_node
{
/**
* \brief Returns the name of the current node.
*/
ROSCPP_DECL const std::string& getName();
/**
* \brief Returns the namespace of the current node.
*/
ROSCPP_DECL const std::string& getNamespace();
/** @brief Get the list of topics advertised by this node
*
* @param[out] topics The advertised topics
*/
ROSCPP_DECL void getAdvertisedTopics(V_string& topics);
/** @brief Get the list of topics subscribed to by this node
*
* @param[out] The subscribed topics
*/
ROSCPP_DECL void getSubscribedTopics(V_string& topics);
} // namespace this_node
} // namespace ros
#endif // ROSCPP_THIS_NODE_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/intraprocess_subscriber_link.h | /*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_INTRAPROCESS_SUBSCRIBER_LINK_H
#define ROSCPP_INTRAPROCESS_SUBSCRIBER_LINK_H
#include "subscriber_link.h"
#include "common.h"
#include <boost/thread/recursive_mutex.hpp>
namespace ros
{
class IntraProcessPublisherLink;
typedef boost::shared_ptr<IntraProcessPublisherLink> IntraProcessPublisherLinkPtr;
/**
* \brief SubscriberLink handles broadcasting messages to a single subscriber on a single topic
*/
class ROSCPP_DECL IntraProcessSubscriberLink : public SubscriberLink
{
public:
IntraProcessSubscriberLink(const PublicationPtr& parent);
virtual ~IntraProcessSubscriberLink();
void setSubscriber(const IntraProcessPublisherLinkPtr& subscriber);
bool isLatching();
virtual void enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy);
virtual void drop();
virtual std::string getTransportType();
virtual std::string getTransportInfo();
virtual const ConnectionPtr& getConnection() { return connection_; };
virtual bool isIntraprocess() { return true; }
virtual void getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti);
private:
IntraProcessPublisherLinkPtr subscriber_;
bool dropped_;
boost::recursive_mutex drop_mutex_;
ConnectionPtr connection_;
};
typedef boost::shared_ptr<IntraProcessSubscriberLink> IntraProcessSubscriberLinkPtr;
} // namespace ros
#endif // ROSCPP_INTRAPROCESS_SUBSCRIBER_LINK_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service.h | /*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_SERVICE_H
#define ROSCPP_SERVICE_H
#include <string>
#include "ros/common.h"
#include "ros/message.h"
#include "ros/forwards.h"
#include "ros/node_handle.h"
#include "ros/service_traits.h"
#include "ros/names.h"
#include <boost/shared_ptr.hpp>
namespace ros
{
class ServiceServerLink;
typedef boost::shared_ptr<ServiceServerLink> ServiceServerLinkPtr;
/**
* \brief Contains functions for querying information about and calling a service
*/
namespace service
{
/** @brief Invoke an RPC service.
*
* This method invokes an RPC service on a remote server, looking up the
* service location first via the master.
*
* @param service_name The name of the service.
* @param req The request message.
* @param[out] res Storage for the response message.
*
* @return true on success, false otherwise.
*/
template<class MReq, class MRes>
bool call(const std::string& service_name, MReq& req, MRes& res)
{
namespace st = service_traits;
NodeHandle nh;
ServiceClientOptions ops(ros::names::resolve(service_name), st::md5sum(req), false, M_string());
ServiceClient client = nh.serviceClient(ops);
return client.call(req, res);
}
/** @brief Invoke an RPC service.
*
* This method invokes an RPC service on a remote server, looking up the
* service location first via the master.
*
* @param service_name The name of the service.
* @param service The service class that contains the request and response messages
*
* @return true on success, false otherwise.
*/
template<class Service>
bool call(const std::string& service_name, Service& service)
{
namespace st = service_traits;
NodeHandle nh;
ServiceClientOptions ops(ros::names::resolve(service_name), st::md5sum(service), false, M_string());
ServiceClient client = nh.serviceClient(ops);
return client.call(service.request, service.response);
}
/**
* \brief Wait for a service to be advertised and available. Blocks until it is.
* \param service_name Name of the service to wait for.
* \param timeout The amount of time to wait for, in milliseconds. If timeout is -1,
* waits until the node is shutdown
* \return true on success, false otherwise
*/
ROSCPP_DECL bool waitForService(const std::string& service_name, int32_t timeout);
/**
* \brief Wait for a service to be advertised and available. Blocks until it is.
* \param service_name Name of the service to wait for.
* \param timeout The amount of time to wait for before timing out. If timeout is -1 (default),
* waits until the node is shutdown
* \return true on success, false otherwise
*/
ROSCPP_DECL bool waitForService(const std::string& service_name, ros::Duration timeout = ros::Duration(-1));
/**
* \brief Checks if a service is both advertised and available.
* \param service_name Name of the service to check for
* \param print_failure_reason Whether to print the reason for failure to the console (service not advertised vs.
* could not connect to the advertised host)
* \return true if the service is up and available, false otherwise
*/
ROSCPP_DECL bool exists(const std::string& service_name, bool print_failure_reason);
/** @brief Create a client for a service.
*
* When the last handle reference of a persistent connection is cleared, the connection will automatically close.
*
* @param service_name The name of the service to connect to
* @param persistent Whether this connection should persist. Persistent services keep the connection to the remote host active
* so that subsequent calls will happen faster. In general persistent services are discouraged, as they are not as
* robust to node failure as non-persistent services.
* @param header_values Key/value pairs you'd like to send along in the connection handshake
*/
template<class MReq, class MRes>
ServiceClient createClient(const std::string& service_name, bool persistent = false, const M_string& header_values = M_string())
{
NodeHandle nh;
ServiceClient client = nh.template serviceClient<MReq, MRes>(ros::names::resolve(service_name), persistent, header_values);
return client;
}
/** @brief Create a client for a service.
*
* When the last handle reference of a persistent connection is cleared, the connection will automatically close.
*
* @param service_name The name of the service to connect to
* @param persistent Whether this connection should persist. Persistent services keep the connection to the remote host active
* so that subsequent calls will happen faster. In general persistent services are discouraged, as they are not as
* robust to node failure as non-persistent services.
* @param header_values Key/value pairs you'd like to send along in the connection handshake
*/
template<class Service>
ServiceClient createClient(const std::string& service_name, bool persistent = false, const M_string& header_values = M_string())
{
NodeHandle nh;
ServiceClient client = nh.template serviceClient<Service>(ros::names::resolve(service_name), persistent, header_values);
return client;
}
}
}
#endif // ROSCPP_SERVICE_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/publisher_link.h | /*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_PUBLISHER_LINK_H
#define ROSCPP_PUBLISHER_LINK_H
#include "ros/common.h"
#include "ros/transport_hints.h"
#include "ros/header.h"
#include "common.h"
#include <boost/thread/mutex.hpp>
#include <boost/shared_array.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <queue>
namespace ros
{
class Header;
class Message;
class Subscription;
typedef boost::shared_ptr<Subscription> SubscriptionPtr;
typedef boost::weak_ptr<Subscription> SubscriptionWPtr;
class Connection;
typedef boost::shared_ptr<Connection> ConnectionPtr;
/**
* \brief Handles a connection to a single publisher on a given topic. Receives messages from a publisher
* and hands them off to its parent Subscription
*/
class ROSCPP_DECL PublisherLink : public boost::enable_shared_from_this<PublisherLink>
{
public:
class Stats
{
public:
uint64_t bytes_received_, messages_received_, drops_;
Stats()
: bytes_received_(0), messages_received_(0), drops_(0) { }
};
PublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri, const TransportHints& transport_hints);
virtual ~PublisherLink();
const Stats &getStats() { return stats_; }
const std::string& getPublisherXMLRPCURI();
int getConnectionID() const { return connection_id_; }
const std::string& getCallerID() { return caller_id_; }
bool isLatched() { return latched_; }
bool setHeader(const Header& header);
/**
* \brief Handles handing off a received message to the subscription, where it will be deserialized and called back
*/
virtual void handleMessage(const SerializedMessage& m, bool ser, bool nocopy) = 0;
virtual std::string getTransportType() = 0;
virtual std::string getTransportInfo() = 0;
virtual void drop() = 0;
const std::string& getMD5Sum();
protected:
SubscriptionWPtr parent_;
unsigned int connection_id_;
std::string publisher_xmlrpc_uri_;
Stats stats_;
TransportHints transport_hints_;
bool latched_;
std::string caller_id_;
Header header_;
std::string md5sum_;
};
} // namespace ros
#endif // ROSCPP_PUBLISHER_LINK_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/exceptions.h | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROSCPP_EXCEPTIONS_H
#define ROSCPP_EXCEPTIONS_H
#include <ros/exception.h>
namespace ros
{
/**
* \brief Thrown when an invalid node name is specified to ros::init()
*/
class InvalidNodeNameException : public ros::Exception
{
public:
InvalidNodeNameException(const std::string& name, const std::string& reason)
: Exception("Invalid node name [" + name + "]: " + reason)
{}
};
/**
* \brief Thrown when an invalid graph resource name is specified to any roscpp
* function.
*/
class InvalidNameException : public ros::Exception
{
public:
InvalidNameException(const std::string& msg)
: Exception(msg)
{}
};
/**
* \brief Thrown when a second (third,...) subscription is attempted with conflicting
* arguments.
*/
class ConflictingSubscriptionException : public ros::Exception
{
public:
ConflictingSubscriptionException(const std::string& msg)
: Exception(msg)
{}
};
/**
* \brief Thrown when an invalid parameter is passed to a method
*/
class InvalidParameterException : public ros::Exception
{
public:
InvalidParameterException(const std::string& msg)
: Exception(msg)
{}
};
/**
* \brief Thrown when an invalid port is specified
*/
class InvalidPortException : public ros::Exception
{
public:
InvalidPortException(const std::string& msg)
: Exception(msg)
{}
};
} // namespace ros
#endif
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.