ROS服务无法保存文件

时间:2018-06-19 17:10:14

标签: json service ros

我想要一个服务“ save_readings”,该服务可以将rostopic中的数据自动保存到文件中。但是,每次调用该服务时,它都不会保存任何文件。 我试图在不使用rosservice的情况下在python中运行那些保存文件的代码,并且代码工作正常。 我不明白为什么会这样。

#!/usr/bin/env python
# license removed for brevity

import rospy,numpy
from std_msgs.msg import String,Int32MultiArray,Float32MultiArray,Bool
from std_srvs.srv import Empty,EmptyResponse
import geometry_msgs.msg
from geometry_msgs.msg import WrenchStamped
import json
# import settings
pos_record = []
wrench_record = []
def ftmsg2listandflip(ftmsg):
    return [ftmsg.wrench.force.x,ftmsg.wrench.force.y,ftmsg.wrench.force.z, ftmsg.wrench.torque.x,ftmsg.wrench.torque.y,ftmsg.wrench.torque.z]

def callback_pos(data):
    global pos_record
    pos_record.append(data.data)

def callback_wrench(data):
    global wrench_record
    ft = ftmsg2listandflip(data)
    wrench_record.append([data.header.stamp.to_sec()] + ft)

def exp_listener():
    stop_sign = False
    rospy.Subscriber("stage_pos", Float32MultiArray, callback_pos)
    rospy.Subscriber("netft_data", WrenchStamped, callback_wrench)
    rospy.spin()

def start_read(req):
    global pos_record
    global wrench_record
    pos_record = []
    wrench_record = []
    return EmptyResponse()

def save_readings(req):
    global pos_record
    global wrench_record
    filename = rospy.get_param('save_file_name')
    output_data = {'pos_list':pos_record, 'wrench_list': wrench_record }
    rospy.loginfo("output_data %s",output_data)

    with open(filename, 'w') as outfile:  # write data to 'data.json'
        print('dumping json file')
        json.dump(output_data, outfile)   #TODO: find out why failing to save the file.
    outfile.close()
    print("file saved")
    rospy.sleep(2)
    return EmptyResponse()


if __name__ == '__main__':
    try:
        rospy.init_node('lisener_node', log_level = rospy.INFO)
        s_1 = rospy.Service('start_read', Empty, start_read)
        s_1 = rospy.Service('save_readings', Empty, save_readings)
        exp_listener()
        print ('mylistener ready!')
    except rospy.ROSInterruptException:
        pass

1 个答案:

答案 0 :(得分:0)

知道了。我需要指定要保存文件的路径。

save_path = '/home/user/catkin_ws/src/motionstage/'
filename = save_path + filename