如何将从 rospy.Subscriber 数据获得的数据输入到变量中?

2023-11-21

我写了一个示例订阅者。我想将从 rospy.Subscriber 获得的数据提供给另一个变量,以便稍后在程序中使用它进行处理。目前,我可以看到订阅者正在运行,因为当我使用 rospy.loginfo() 函数时,我可以看到打印的订阅值。虽然我不知道如何将这些数据存储到另一个变量中。我尝试使用赋值运算符“=”将其直接分配给变量,但出现错误。

我尝试使用 rospy.loginfo 编写回调函数来打印订阅对象的位置数据。我已经订阅了 JointState,它包含标题、位置、速度和努力数组。使用 rospy.loginfo 我可以验证订阅者是否正在订阅。但是当我尝试将其直接分配给变量时,出现错误。

我正在显示来自回调函数的日志信息,如下所示

def callback(data):
   rospy.loginfo(data.position)
   global listen
    listen = rospy.Subscriber("joint_states", JointState, 
    callback)
    rospy.spin()

这很好用。但是当我稍微修改代码来分配订阅值时,我收到以下错误,即

   listen1 = rospy.Subscriber("joint_states", JointState, 
   callback=None)
   listen = listen1.position
   #rospy.loginfo(listen)
   print(listen)
   rospy.spin()```

The error is as follows, 
 ```listen = listen1.position
    AttributeError: 'Subscriber' object has no attribute 'position'

编辑: 这是我在程序中定义的节点,

    #rospy.loginfo(msg.data)
    global tactile_states
    tactile_states = data.data

def joint_callback(data):
    #rospy.loginfo(data.position)
    global g_joint_states 
    global g_position
    global g_pos1
    g_joint_states = data
    #for i in len(data.position):
        #g_position[i] = data.position[i]
    g_position = data.position
    if len(data.position) > 0:
        print("jointstate more than 0")
        g_pos1 = data.position[0]
    #print(g_position)


def joint_modifier(*args):
    #choice describes what the node is supposed to do whether act as publisher or subscribe to joint states or tactile sensors
    rospy.init_node('joint_listener_publisher', anonymous=True)
    pub1 = rospy.Publisher('joint_states', JointState, queue_size = 10)
    if(len(args)>1):
        choice = args[0]
        joint_name = args[1]
        position = args[2]
    else:
        choice = args[0]
    if (choice == 1):
        rate = rospy.Rate(1)
        robot_configuration = JointState()
        robot_configuration.header = Header()
        robot_configuration.name = [joint_name]
        robot_configuration.position = [position]
        robot_configuration.velocity = [10]
        robot_configuration.effort = [100]
        while not rospy.is_shutdown():
            robot_configuration.header.stamp = rospy.Time.now()
            rospy.loginfo(robot_configuration)
            break
        pub1.publish(robot_configuration)
        rospy.sleep(2)
    if (choice == 2):
        #rospy.Timer(rospy.Duration(2), joint_modifier)
        listen = rospy.Subscriber("joint_states", JointState, joint_callback)
        rospy.spin()
    if (choice == 3):
        #rospy.Timer(rospy.Duration(2), joint_modifier)
        tactile_sub = rospy.Subscriber("/sr_tactile/touch/ff", Float64, tactile_callback)
        rospy.spin()

这就是我在程序主体内调用节点的方式,

           joint_modifier(2)
           print("printing g_position")
           print(g_position)#to check the format of g_position
           print("printed g _position")
           leg_1 = Leg_attribute(g_position[0], g_position[1], g_position[2], velocity1 = 10, velocity2 = 10, velocity3 = 10, effort1 = 100, effort2 = 100, effort3 = 100, acceleration=1)

当这样调用时,程序卡在joint_modifier(2)因为该函数有rospy.spin().



您使用的样式不是很标准。我假设你已经看过example在 ROS wiki 上,我对其进行了修改以演示下面的标准用法。

主要是,解决您发布的代码,您需要制作listen在回调之外具有全局范围。这是为了存储data你想要的,而不是 Subscriber 对象。 rospy.spin() 永远不会进入回调,只会进入主节点函数/部分。订阅者对象,listen1不经常使用,不返回任何内容,也不存储它获取的数据。也就是说,您需要 Subscriber() 来进行非 None 回调。 它更多的是一个bind,给出data to the callback而不是从订阅者返回它。这就是为什么listen1 (订户)没有属性position (联合国家).

import rospy
from sensor_msgs.msg import JointState

# Subscribers
#     joint_sub (sensor_msgs/JointState): "joint_states"

# This is where you store all your data you recieve
g_joint_states = None
g_positions = None
g_pos1 = None

def timer_callback(event): # Type rospy.TimerEvent
    print('timer_cb (' + str(event.current_real) + '): g_positions is')
    print(str(None) if g_positions is None else str(g_positions))

def joint_callback(data): # data of type JointState
    # Each subscriber gets 1 callback, and the callback either
    # stores information and/or computes something and/or publishes
    # It _does not!_ return anything
    global g_joint_states, g_positions, g_pos1
    rospy.loginfo(data.position)
    g_joint_states = data
    g_positions = data.position
    if len(data.position) > 0:
        g_pos1 = data.position[0]
    print(g_positions)

# In your main function, only! here do you subscribe to topics
def joint_logger_node():
    # Init ROS
    rospy.init_node('joint_logger_node', anonymous=True)

    # Subscribers
    # Each subscriber has the topic, topic type, AND the callback!
    rospy.Subscriber('joint_states', JointState, joint_callback)
    # Rarely need to hold onto the object with a variable: 
    #     joint_sub = rospy.Subscriber(...)
    rospy.Timer(rospy.Duration(2), timer_callback)

    # spin() simply keeps python from exiting until this node is stopped
    # This is an infinite loop, the only code that gets ran are callbacks
    rospy.spin()
    # NO CODE GOES AFTER THIS, NONE! USE TIMER CALLBACKS!
    # unless you need to clean up resource allocation, close(), etc when program dies

if __name__ == '__main__':
    joint_logger_node()

编辑1: Subscriber()、spin() 和 _callback(s) 的作用似乎有些混乱。 在Python中有点晦涩难懂,但是有一个主程序来管理所有节点,并在它们之间发送节点。在每个节点中,我们向主程序注册该节点存在以及它有哪些发布者和订阅者。通过注册,意味着我们告诉主程序,“嘿,我想要那个主题!”;就您而言,对于您的(未声明的)joint_sub 订阅者,“嘿,我想要所有JointState消息来自joint_states主题!”主程序每次(从某处的某个发布者那里)获得一个新的joint_states JointStatemsg,将其发送给该订阅者。 订阅者处理、处理和处理消息(数据)callback:当(!)我收到一条消息时,运行回调。

所以主程序收到一个新的joint_states JointState来自某个出版商的消息。然后,因为我们向它注册了订阅者,所以它会将其发送到该节点。 rospy.spin() 是一个等待该数据的无限循环。这就是它的作用(主要是):

def rospy.spin():
    while rospy.ok():
        for new_msg in get_new_messages from master():
            if I have a subscriber to new_msg:
                my_subscriber.callback(new_msg)

rospy.spin() 是回调、joint_callback(和/或timer_callback等)实际被调用和执行的地方。它only当有数据时运行。

更根本的是,我认为由于这种混乱,你的程序结构是有缺陷的;你的功能并没有像你想象的那样做。这就是你应该如何制作你的节点。

  1. 将执行神经网络的数学部分(所有真正的非 ros 代码)放入一个单独的模块中,并创建一个函数来运行它。
  2. 如果您只想在收到数据时运行它,请在回调中运行它。如果要发布结果,请在回调中发布。
  3. 不要调用main函数!这if __name__ == '__main__': my_main_function()应该是它被调用的唯一地方,这将调用您的代码。我重复一遍:声明订阅者/发布者/init/定时器/参数的主函数仅在if __name__ ...,并且该函数运行您的代码。要让它运行您的代码,请将您的代码放在回调中。定时器回调对此很方便。

我希望这个代码示例能够澄清:

import rospy
from std_msgs.msg import Header
from sensor_msgs.msg import JointState
import my_nn as nn # nn.run(data)

# Subscribers
#     joint_sub (sensor_msgs/JointState): "joint_states"

# Publishers
#     joint_pub (sensor_msgs/JointState): "target_joint_states"

joint_pub = None

def joint_callback(data): # data of type JointState
    pub_msg = JointState() # Make a new msg to publish results
    pub_msg.header = Header()
    pub_msg.name = data.name
    pub_msg.velocity = [10] * len(data.name)
    pub_msg.effort = [100] * len(data.name)
    # This next line might not be quite right for what you want to do,
    # But basically, run the "real code" on the data, and get the
    # result to publish back out
    pub_msg.position = nn.run(data.position) # Run NN on data, store results
    joint_pub.publish(pub_msg) # Send it when ready!

if __name__ == '__main__':
    # Init ROS
    rospy.init_node('joint_logger_node', anonymous=True)
    # Subscribers
    rospy.Subscriber('joint_states', JointState, joint_callback)
    # Publishers
    joint_pub = rospy.Publisher('target_joint_states', JointState, queue_size = 10)
    # Spin
    rospy.spin()
    # No more code! This is not a function to call, but its
    # own program! This is an executable! Run your code in
    # a callback!

请注意,我们设计为 ros 节点的 python 模块具有no要调用的函数。它具有定义的回调结构和它们之间共享的全局数据,所有这些都在主函数中初始化和注册/if __name__ == '__main__'.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将从 rospy.Subscriber 数据获得的数据输入到变量中? 的相关文章

  • 如何使用 pandas 选择所有非 NaN 列和非 NaN 最后一列?

    如果标题有点令人困惑 请原谅我 假设我有test h5 下面是使用读取该文件的结果df read hdf test h5 testdata 0 1 2 3 4 5 6 0 123 444 111 321 NaN NaN NaN 1 12 2
  • 静态文件配置不正确

    我已经在 Heroku 上部署了简单的博客应用程序 它运行在Django 1 8 4 我在静态文件方面遇到了一些问题 当打开我的应用程序时 我看到Application Error页面 所以我尝试调试它并发现当我提交到 Heroku 时它无
  • 我怎样才能在python cgi中找到上传的文件名

    我制作了如下简单的网络服务器 import BaseHTTPServer os cgi import cgitb cgitb enable html
  • 使用信号时出现 django TransactionManagementError

    我有一个与 django 的用户和 UserInfo 一对一的字段 我想订阅用户模型上的 post save 回调函数 以便我也可以保存 UserInfo receiver post save sender User def saveUse
  • Python 使用 M2Crypto 通过 S/MIME 对消息进行签名

    我现在花了几个小时 但找不到我的错误 我想要一个简单的例程来创建 S MIME 签名消息 稍后可以与 smtplib 一起使用 这是我到目前为止所拥有的 usr bin python2 7 coding utf 8 from future
  • 使用 Python 的文本中的词频但忽略停用词

    这给了我文本中单词的频率 fullWords re findall r w allText d defaultdict int for word in fullWords d word 1 finalFreq sorted d iterit
  • Pandas Pivot_Table :非数字值的行计算百分比

    这是我在数据框 df 中的数据 Document Name Time SPS2315511 A 1 HOUR SPS2315512 B 1 2 HOUR SPS2315513 C 2 3 HOUR SPS2315514 C 1 HOUR S
  • 在函数调用之间保存数据的Pythonic方式是什么?

    对我来说 上下文是我需要在调用修改该值的函数之间保留的单个 int 的信息 我可以使用全局 但我知道这是不鼓励的 现在 我使用了包含 int 的列表形式的默认参数 并利用了可变性 以便在调用之间保留对值的更改 如下所示 def increm
  • 向 Python 2.6 添加 SSL 支持

    我尝试使用sslPython 2 6 中的模块 但我被告知它不可用 安装OpenSSL后 我重新编译2 6 但问题仍然存在 有什么建议么 您安装了 OpenSSL 开发库吗 我必须安装openssl devel例如 在 CentOS 上 在
  • 如何使用 jira-python 设置 fixVersions 字段

    我正在尝试使用 jira python 模块 http jira python readthedocs org en latest 更新现有的 JIRA 具体来说 我正在尝试设置问题的fixesVersion 列表 我已经尝试了一段时间但没
  • 提交表格并上传带有请求的文件

    我正在努力提交特定的表格蟒蛇请求 http www python requests org 我想使用它的网站上的其他表单工作正常 我可以提交登录表单等 这只是我遇到问题的文件上传 显然 提交表单效果很好 因为我从网站收到一条消息 说 请返回
  • 在Python中计算结构体的CRC

    我有以下结构 来自 C 中的 NRPE 守护程序代码 typedef struct packet struct int16 t packet version int16 t packet type uint32 t crc32 value
  • 如何在 Python 中执行相当于预处理器指令的操作?

    有没有办法在 Python 中执行以下预处理器指令 if DEBUG lt do some code gt else lt do some other code gt endif There s debug 这是编译器预处理的特殊值 if
  • python中打印字符串的长度

    有没有什么方法可以找到 即使是最好的猜测 Python中字符串的 打印 长度 例如 potaa bto 是 8 个字符len但 tty 上只打印 6 个字符宽 预期用途 s potato x1b 01 32mpotato x1b 0 0mp
  • 网页抓取 - 如何识别网页上的主要内容

    给定一个新闻文章网页 来自任何主要新闻来源 例如时报或彭博社 我想识别该页面上的主要文章内容 并丢弃其他杂项元素 例如广告 菜单 侧边栏 用户评论 在大多数主要新闻网站上都可以使用的通用方法是什么 有哪些好的数据挖掘工具或库 最好是基于Py
  • 在 Tensorflow 2.0 中的简单 LSTM 层之上添加 Attention

    我有一个由一个 LSTM 和两个 Dense 层组成的简单网络 如下所示 model tf keras Sequential model add layers LSTM 20 input shape train X shape 1 trai
  • 测试中的模型 - Django 1.7 问题

    我正在尝试将我的项目移植为使用 Django 1 7 除了一件事之外 一切都很好 测试文件夹内的模型 Django 1 7 新迁移在内部运行 migrate 命令 在运行syncdb之前 这意味着如果模型未包含在迁移中 它将不会填充到数据库
  • 在Python中从列表中获取n个项目组的惯用方法? [复制]

    这个问题在这里已经有答案了 给定一个列表 A 1 2 3 4 5 6 是否有任何惯用的 Pythonic 方式来迭代它 就好像它是 B 1 2 3 4 5 6 除了索引之外 这感觉像是 C 的遗留物 for a1 a2 in A i A i
  • Selenium Python 使用代理运行浏览器[重复]

    这个问题在这里已经有答案了 我正在尝试编写一个非常简单的脚本 该脚本从 txt 文件获取代理 不需要身份验证 并用它打开浏览器 然后沿着代理列表循环此操作一定次数 我确实知道如何打开 txt 文件并使用它 我的主要问题是让代理正常工作 我见
  • Shap - 颜色条不显示在摘要图中

    显示summary plot时 不显示颜色条 shap summary plot shap values X train 我尝试过改变plot size 当绘图较高时 会出现颜色条 但它非常小 看起来不应该 shap summary plo

随机推荐

  • Python 请求 - 在 HTTP POST 之后是否可以收到部分响应?

    我正在使用Python 请求模块对网站进行数据挖掘 作为数据挖掘的一部分 我必须通过 HTTP POST 发送表单 并通过检查生成的 URL 来检查它是否成功 我的问题是 在POST之后 是否可以请求服务器不发送整个页面 我只需要检查 UR
  • 如何比较 WiX 中的注册表版本?

    在我的 wix 安装程序中 我想检查 ESRI ArcMap 的版本 可以通过以下方式找到
  • 在一个语句中对 GETDATE 求值两次 - 它的求值结果总是相同吗?

    suppose isnull some column getdate gt getdate 其中逻辑是如果 some column 为 null 则该表达式应始终为 true 然而 这是否总是如此 因为在 getdate 的两次评估之间已经
  • 如何生成给定大小的所有子集?

    给定某个数字 n 和子集大小 我想获取集合 1 n 的指定大小的所有可能子集 预期结果为n 5 and subsetSize 4 1 2 3 4 1 2 3 5 1 3 4 5 1 2 4 5 2 3 4 5 那将是一个List
  • 使用 Tomcat,但出现 ClassNotFoundException:org.jboss.logging.BasicLogger

    我在 Eclipse 中使用 Tomcat 7 通过 JPA Hibernate 运行 REST Spring Web 应用程序 我在尝试启动部署了我的应用程序的 Tomcat 时遇到奇怪的 JBoss 错误 我不明白为什么在使用 Tomc
  • SQL 存储过程中的动态排序

    这是我过去花了几个小时研究的一个问题 在我看来 这是现代应该解决的问题RDBMS解决方案 但到目前为止 我还没有找到任何能够真正满足我认为在任何具有数据库后端的 Web 或 Windows 应用程序中非常常见的需求的东西 我说的是动态排序
  • 当我不使用 Promise 的“then”功能时,是否会产生任何(负面)副作用?

    我有一个返回 Promise 的函数 现在 有时消费者在该 Promise 上使用 then 功能是有意义的 但有时消费者根本不关心 Promise 何时解析 也不关心结果 换句话说 相同的函数也应该能够以 即发即忘 的方式调用 所以我想要
  • 在java中寻找CSS解析器[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 我正在寻找 java 中的 CSS 解析器 特别是 我的要求是 对于 HTML 文档中的给定节点 元素 能够从解析器询问 获取该元素的 css 样式
  • 使用 python mechanize 进行复选框输入

    我想使用 python mechanize 填写表格 形式看起来像
  • 在 DOM 中存储数据

    我有一个书籍列表 我想存储每本书的数据 例如价格 数量 id 类别id 尺寸 重量等 我正在考虑通过使用数据属性扩展表示列表中每本书的 li 元素来将所有这些存储在 dom 中 然后可以通过 JavaScript 直接使用这些数据 然而 我
  • 调试 IIS 中托管的 asp.net WCF 服务

    我使用以下模板创建了 WCF 服务 http visualstudiogallery msdn microsoft com fbc7e5c1 a0d2 41bd 9d7b e54c845394cd 该服务有一个这样的方法 ServiceCo
  • 缩小图像以适合 ScrollViewer 尺寸

    我在相应地缩放图像时遇到了一些问题 我有一个Image在我的 XAML 中 带有ScrollViewer附加以便可以缩放 像这样
  • heroku:bash:捆绑:找不到命令

    我正在按照他们的说明将 Heroku 应用程序从 Aspen 移植到 Heroku 的 Cedar 堆栈 我正在进行最后的部署步骤 我收到此错误 2012 10 22T11 23 53 00 00 heroku web 1 Starting
  • 安全与不安全代码

    Read 这个问题今天关于安全和不安全的代码 然后我在MSDN但我还是不明白 为什么要在 C 中使用指针 这纯粹是为了速度吗 使用不安全代码有以下三个原因 API 如 John 所言 获取数据的实际内存地址 例如访问内存映射硬件 访问和修改
  • 用JS获取元素CSS3背景色渐变

    目前 我使用以下 JS jQuery 来查找其他几个 div 的背景颜色 作为 rgb theColor this css background color 除了 CSS3 渐变之外 它工作得很好 作为示例 我使用以下 css 使 div
  • TypeError: $(...).modal 不是带有 bootstrap Modal 的函数

    我有一个 bootstrap 2 32 模式 我试图将其动态插入到另一个视图的 HTML 中 我正在使用 Codeigniter 2 1 下列的将引导模式部分视图动态插入视图中 我有 div div 作为插入的目标 div 我的视图中有一个
  • Tomcat 上的 Cobertura

    我正在尝试使用 Cobertura 应用代码覆盖率 该应用程序是 部署在 Tomcat 5 中 但是当我检测 class 文件时 应用程序停止工作 这是我的步骤 编译应用程序 在 tomcat 中运行 检测类文件 D test cobert
  • GIT:提交时文件中有当前提交哈希和最新标签

    这可能更多是一个技术问题 我使用 git 进行版本控制 并使用 rsync 将 PHP CMS 的文件发送到测试或生产站点 现在我想使用一个万无一失的自动化系统来跟踪当前部署的提交 我在想 设置 git hook 以使用最新标签添加 更新文
  • python byRef // 复制 [重复]

    这个问题在这里已经有答案了 我是Python新手 而且对编程不太了解 但我记得读过Python通常不会复制值 因此任何语句a b都会使b指向a 如果我跑 a 1 b a a 2 print b 给出结果 1 那不应该是 2 吗 不 结果应该
  • 如何将从 rospy.Subscriber 数据获得的数据输入到变量中?

    我写了一个示例订阅者 我想将从 rospy Subscriber 获得的数据提供给另一个变量 以便稍后在程序中使用它进行处理 目前 我可以看到订阅者正在运行 因为当我使用 rospy loginfo 函数时 我可以看到打印的订阅值 虽然我不