0
votes

I want to have a service 'save_readings' that automatically saves data from a rostopic into a file. But each time the service gets called, it doesn't save any file. I've tried to run those saving-file code in python without using a rosservice and the code works fine. I don't understand why this is happening.

#!/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

1 Answers

0
votes

Got it. I need to specify a path for the file to be saved.

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