当前位置:网站首页>3.ROS通信机制进阶
3.ROS通信机制进阶
2022-08-07 08:45:00 【janedipan】
3.ROS通信机制进阶
本篇实际ROS常用API介绍;ROS中自定义头文件与源文件是使用
常用API
应用程序编程接口
可参考官方API文档或参考源码 官方文档
- ROS节点初始化相关API
- NodeHandle的基本使用相关API
- 话题的发布方,订阅方对象相关API
- 服务的服务端,客户端对象相关API
- 时间相关API
- 日志输出相关API
初始化(python)—rospy.init_node()
rospy.init_node()
可传入的参数:
- name —设置节点名称
- argv=None —封装节点调用时传递的参数
- annoymous=False — 可以为界定名称生成随机后缀,解决重名问题
agrv使用:可以按照ROS中指定的语法格式传参,ROS可以解析并加以使用
annoymous使用:在init_node('node_name', anonymous=True)
# plumbing_apis/scripts/demo01_apis_pub_p.py
#! /usr/bin/env python
import rospy
rospy.init_node('china', anonymous=True)
pub=rospy.Publisher('person', String, queue_size=10)
msg=String()
msg='Lihua'
rate=rospy.Rate(0.5)
count=0
while not rospy.is_shutdown():
rosloginfo('the published messages is: {}'.formate(msg))
rate.sleep()
# 一个简单publisher
在cmd中运行此节点文件
rosrun plumbing_apis demo01_apis_pub_p.py
rosrun plumbing_apis demo02_apis_pub_p.py _A:10000 #传入参数_A,其值为10000,ROS将其解析转换为param中的一个变量
rosparam list #可查看新增变量A
rosparam get <key> #查看变量A的值
话题与服务相关对象—发布方Publisher
发布方Publisher
latch参数
在创建发布者对象时pub=rospy.Publisher(<topic>, <Type>),可传入的参数还有latch,输入一个布尔值,当latch=true时发布方Publisher最后一个消息将被保存,待新的订阅者Listener于发布者连接后会立即发送给订阅者
# plumbing_apis_p.py
#! /usr/bin/env python
import rospy
from std_msgs.msg import String
rospy.init_node('china', anonymous=True)
pub = rospy.Publisher('person', String, latch=True, queue_size=10)
msg = String()
rate = rospy.Rate(0.5)
count = 0
while not rospy.is_shutdown():
while count <= 10:
msg.data = "hello"+str(count)
pub.publish(msg)
rospy.loginfo('the publish message is: {}'.format(msg.data))
count += 1
rate.sleep()
# rostopic echo /person ---此时收集到的信息是最后发布的hello10
时间
需求1:获取当前时刻+设置指定时刻
# plumbing_apis/scripts/demo02_apis_times_p.py
# /usr/bin/env python
import rospy
if __name__=='__main__':
rospy.init_node('hello_time')
right_now=rospy.Time.now()
# 将当前的时刻获取并封装(1.运行该代码的时刻 2.参考的是1970年1月1日00:00:00)
rospy.loginfo('right now is: {:.2f}'.format(right_now.to_sec()) #秒-浮点数
rospy.loginfo('right now is: {}'.format(right_now.secs) #秒-整数
time1=rospy.Time(100.5) # 将时间距参考时间过了100.5s封装成Time实例
time2=rospy.Time(100,312345678) # 将时间距参考时间过个100s又31234567纳秒封装成Time实例
time3=rospy.Time.from_sec(210.12) # 从输入的具体时间封装成Time实例
需求2:程序执行中断5s
# plumbing_apis/scripts/demo02_apis_times_p.py
--snip--
du=rospy.Duration(<sec>, <nsec>)
rospy.sleep(du)
需求3:获取程序开始执行的时刻,且已知持续运行的时间,计算程序结束的时间
# plumbing_apis/scripts/demo02_apis_times_p.py
--snip--
t1=rospy.Time.now()
sl1=rospy.Duration(<sec>,<nsec>)
t2=t1+sl1
# 时间数值处理
rospy.loginfo('the begin time is: {}, the end time is: {}'.format(t1, t2))
需求4:设置运行频率
# plumbing_apis/scripts/demo02_apis_times_p.py
--snip--
def doMsg(event):
# event是TimerEvent
rospy.loginfo(event.current_real) # 打印回调函数的时刻
timer=rospy.Timer(rospy.Duration(2), doMsg, True) #创建一个定时器对象,rospy.Duration(2)是定义的时间段,doMsg是要运行的函数,参数True doMsg只执行一次,不会参与循环r
rospy.spin() #循环执行
其他函数
节点相关
节点判断—rospy.is_shutdown(),返回一个bool
节点关闭—rospy.signal_shutdown(<str>)
节点关闭时执行的函数—on_shutdown(<type>), type:fn
日志相关
# plumbing_apis/scripts/demo03_apis_log_p.py
#! /usr/bin/env python
import rospy
if __name__=='__main__':
rospy.init_node('hello log')
rospy.logdebug(<str1>) # str1默认不会输出在控制台
rospy.loginfo(<str2>) # 打印str2
rospy.logwarn(<str3>) # 警告消息
rospy.logerr(<str4>) # 错误消息
rospy.logfatal(<str5>) # 崩溃消息
ROS中的头文件与源文件
python模块导入
存在问题:一般情况下,注意模块的导入是在 同一目录下的.py文件-即为模块,否则就要添加环境变量,而启用ROS节点文件,需要用到rosrun指令,而该指令的参考路径是demo下(即ros-project工作空间下),而并非scripts存放节点文件的目录下
解决问题:可以声明python的环境变量,当依赖某个模块时,先去指定的环境变量中查找依赖即 设置临时环境变量;
import sys
sys.path.insert(0, 'home/Documents/ros_dc/..../scripts') #需要传入两个参数,第一个是索引位置,第二是物理路径
以上添加临时环境变量的做法虽然能解决无法搜索引用库的问题,但不具有可移植性,因为不同设备的物理地址是不同的,因此需改为动态的物理地址
import sys
import os
path = os.path.abspath('.')
sys.path.insert(0, path+'/src/<package_name>/scripts')
边栏推荐
- Canvas image drawing (with zoom in, zoom out and drag functions)
- Spark SQL深入分析之图解五种Join策略的执行流程与应用场景
- 2022华数杯数学建模-在线文档
- The principle and source code of redis - the principle and source code analysis of cluster (on)
- 30.01 C/S、TCP/IP协议妙趣横生、惟妙惟肖谈
- MySQL:事务的概念 | ACID特性 | 事务并发存在的问题 | 事务处理命令
- 岛屿的最大面积
- 哈希-闭散列
- Sort---Insertion sort
- rest client: a lightweight vscode plugin for api requests
猜你喜欢

微服务系列一:微服务的优势与劣势

Jenkins configures automatic packaging

ABP 6.0.0-rc.1的新特性

redis的原理和源码-redis各数据类型的编码格式和数据结构SDS、list、dict、zskiplist、intset、ziplist、quicklist、listpack、rax、stream

The use of modules in ansible

The baud rate of STM32 is wrong. The baud rate we want to set is 9600, but the actual baud rate is 14400. Why is this?

MySQL:事务的概念 | ACID特性 | 事务并发存在的问题 | 事务处理命令

Addition, deletion, search and modification of doubly linked list

DeFi Prospects: An Overview of Q2 Progress of Mainstream DeFi Protocols

ABP 6.0.0-rc.1的新特性
随机推荐
3D~RPG game production
pip3升级后报错f“pip[sys.version_info.major)“
The third bullet of FPGA development: button control LED experiment
Canvas image drawing (with zoom in, zoom out and drag functions)
[Punctuality Atom STM32 Serial] Chapter 7 Understanding the HAL Library Excerpted from [Punctual Atom] MiniPro STM32H750 Development Guide_V1.1
背包理论之01背包(滚动数组)
【正点原子STM32连载】第五章 STM32基础知识入门 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
Prediction of Operations Research Fundamentals [2]
The fifth bullet of FPGA development: hand rubbing breathing light code
数据库连接池commons-pool源码分析
Transport layer (UDP protocol, TCP protocol three-way handshake, four-way wave)
#yyds Dry Goods Inventory# [Yugong Series] August 2022 Go Teaching Course 004-Go Code Comments
哈希——开散列
DCDC电源方案设计踩坑
jenkins配置自动打包
如何配置百度地图应用访问白名单
RestTemplate
DeFi Prospects: An Overview of Q2 Progress of Mainstream DeFi Protocols
Exploration and practice of Redis fixed-length queue
Swap sort (bubble sort, quick sort)