实习记录(一):用ros一个节点封装成类实现topic收发

用ros一个节点封装成类实现topic收发

2020.07.16~2020.07.17

1.任务

已有一个 filename.bag,其中有多个topic信息
点云 - topic名为 xxxx, 要求接收点云,发出点云的size (std_msgs/UInt32)
用一个类实现

2.环境 & 工具

ubuntu16.04
ROS kinetic
C++
git

3.准备工作

1)新建工作空间,新建包

$ source /opt/ros/kinetic/setup.bash
$ mkdir -p ~/catkin_ws/src
$ catkin_create_pkg pkg_name std_msgs rospy roscpp

2)vscode配置

#查看隐藏文件 ctrl + H
#工程文件夹路径下去生成.vscode文件夹,里面的c_cpp_properties.json
#配置完后的头文件报错点击vscode智能提示小灯泡解决
{
    "configurations": [
        {
            "browse": {
                "databaseFilename": "",
                "limitSymbolsToIncludedHeaders": true
            },
            "includePath": [
                "${workspaceFolder}/**",
                "/opt/ros/kinetic/include/**",
                "/usr/include/**",
                "/usr/local/include/**",
                "/opt/ros/kinetic/include",
                "${workspaceFolder}/src/serial_writer/include"
            ],
            "name": "Linux",
            "intelliSenseMode": "gcc-x64",
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "compileCommands": "${workspaceFolder}/build/compile_commands.json"
        }
    ],
    "version": 4
}

3)在filename.bag文件所在路径打开新的终端,查看点云的topic类型,然后查这个类型的成员变量有哪些,写代码会用到

$ rosbag info filename.bag

4.代码

//main.cpp
#include "points_size.h"

int main(int argc, char** argv)
{
  ros::init(argc, argv, "points_size_main");

  std::cout << "Program Start ..." << std::endl;
  xxxx::PointSizePublisher point_size_pub;
  ros::spin();

  return 0;
}

//类.h
#ifndef POINT_SIZE_H
#define POINT_SIZE_H

#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "std_msgs/UInt32.h"
#include 

namespace xxxx
{
class PointSizePublisher
{
public:
  PointSizePublisher()
  {
    pointscloud_sub_ = n_pointscloud_.subscribe("lidar_points", 20, &PointsSize::lidarpointsCallback, this);
    pointscloud_pub_ = n_pointscloud_.advertise<std_msgs::UInt32>("size", 20);
  };
  ~PointSizePublisher() = default;

private:
  void lidarpointsCallback(const sensor_msgs::PointCloud2::ConstPtr& _msg);

private:
  ros::NodeHandle n_pointscloud_;
  ros::Subscriber pointscloud_sub_;
  ros::Publisher pointscloud_pub_;
};
}  // namespace xxxx

#endif

//类.cpp
#include "points_size.h"

namespace xxxx
{
void PointSizePublisher::lidarpointsCallback(const sensor_msgs::PointCloud2::ConstPtr& _msg)
{
  std_msgs::UInt32 size_;
  size_.data = _msg->height * _msg->width;
  pointscloud_pub_.publish(size_);
  ROS_INFO("size_of_lidar_points : %d", size_.data);
};

}  // namespace xxxx

//cmakelist
cmake_minimum_required(VERSION 3.0.2) 
project(pkg_name)
 
find_package(catkin REQUIRED COMPONENTS 
    roscpp 
    rospy 
    std_msgs 
    sensor_msgs ) 

catkin_package() 

include_directories( 
include ${catkin_INCLUDE_DIRS} ) 

add_library(points_size 
include/points_size.h 
    src/points_size.cpp ) 

add_dependencies(
    points_size 
    ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) 

add_executable(
    points_size_main 
    src/points_size_main.cpp) 

target_link_libraries( 
    points_size_main 
    points_size 
    ${catkin_LIBRARIES} )

5.运行测试

1)打开新的终端启动roscore
2)在filename.bag文件所在路径打开新的终端,循环播包

$ rosbag play -l filename.bag

3)在工作空间路径打开新的终端,编译运行

$ catkin_make
$ source devel/setup.bash
$ rosrun pkg_name points_size_main

6.提交

1)仓库里记得添加LICENCE(公司的)、.gitignore(git提交时会忽略哪些文件在里面定义)、.clang-format(代码格式配置)

#.gitignore
# GNU global tags
GTAGS
GRTAGS
GSYMS
GPATH
tags

debian
obj-x86_64-linux-gnu

# Python byte-compile file
__pycache__/
*.py[co]

# editor backup files
*~
\#*\#
build/
utest/data/
installer/
# backup files
*.bak

# Eclipse
.cproject
.project
.pydevproject
.settings/



# CLion
.idea/
cmake-build-*/

# vs code
.vscode

# clang-format
# .clang-format

# ROSBag files
*.bag
*.pcd
*.pcap

# Environments
.env
.venv
env/
venv/
ENV/

# gvim ycm
.ycm_extra_conf.py

# lidar hardware config file
*.csv



配置.clang-format

sudo apt-get install clang-format
ln -s dir_to_git_template ~/.git_template
git config --global init.templatedir ~/.git_template
git config --global commit.template ~/.git_templates/.gitmessage.txt
cp clang-format your_git_root_project/.clang-format
#.clang-format
---
BasedOnStyle:  Google
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 2
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: true
BinPackParameters: true
ColumnLimit:    120
ConstructorInitializerAllOnOneLineOrOnePerLine: true
DerivePointerBinding: false
PointerBindsToType: true
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 60
PenaltyBreakString: 1
PenaltyBreakFirstLessLess: 1000
PenaltyExcessCharacter: 1000
PenaltyReturnTypeOnItsOwnLine: 90
SpacesBeforeTrailingComments: 2
Cpp11BracedListStyle: false
Standard:        Auto
IndentWidth:     2
TabWidth:        2
UseTab:          Never
IndentFunctionDeclarationAfterType: false
SpacesInParentheses: false
SpacesInAngles:  false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
# if else for 后的空格
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
SortIncludes: false
SpaceAfterCStyleCast: false

# Configure each individual brace in BraceWrapping
BreakBeforeBraces: Custom

# Control of individual brace wrapping cases
BraceWrapping: {
    AfterClass: 'true'
    AfterControlStatement: 'true'
    AfterEnum : 'true'
    AfterFunction : 'true'
    AfterNamespace : 'true'
    AfterStruct : 'true'
    AfterUnion : 'true'
    BeforeCatch : 'true'
    BeforeElse : 'true'
    IndentBraces : 'false'
}
...

2)gitlab 和 github 用法是一样的

#第一次要全局配置git
$ git config --global user.name "name"
$ git config --global user.email [email protected]
#进入远程仓库查看地址,将仓库下载下来
$ git clone 地址
#进入下载好的本地仓库路径,打开新的终端
#如果要删掉提交过的仓库里本来有的文件,用git命令去删,不能直接删除,后续git会匹配出错,解决非常麻烦,哭~
#此时仓库路径分支默认为 master
#新建分支,并且切换过去
$ git checkout -b 分支名
#将需要提交的内容放进本地仓库的文件夹内
#将所有修改提交到暂存区,如果要取消本次全部add使用 git reset HEAD
$ git add .
#查看add修改内容
$ git status
#正式提交,如果要取消本次commit使用 git reset --soft HEAD^,
#^个数表示回退版本数,soft表示不改变文件状态只取消commit记录,
#特别注意改成hard表示文件一并回退到之前的版本,新文件会全被删掉,记得备份,哭~
$ git commit -m "备注"
#查看所有commit提交记录
$ git log
#提交到远程仓库
$ git push origin 分支名

结语:进入实习第一个任务,是前辈为了让我们熟悉流程规范用的,本来一个感觉还挺简单的任务,具体做起来疯狂踩坑,代码命名与格式规范也是写完之后发现不符然后一点点改正,用了两个工作日才彻底完成,知行合一还是不容易啊

另注:本文为自用实习记录,以上涉及公司名称的部分全部采用xxxx处理

你可能感兴趣的:(实习,git,c++,ubuntu)