#include<ros/ros.h>#include<sensor_msgs/Imu.h>#include<gazebo_msgs/GetModelState.h>#include<fstream>// Global variables
std::ofstream csv_file;
ros::ServiceClient model_state_client;
std::string filename;
// Frequency variablesdouble desired_frequency = 10.0; // Desired frequency in Hz
ros::Rate* rate;
// Callback function for the IMU data subscribervoidimuDataCallback(const sensor_msgs::Imu::ConstPtr& msg){
// Get the current location of the "husky" robot from Gazebo
gazebo_msgs::GetModelState model_state;
model_state.request.model_name = "husky";
model_state_client.call(model_state);
// Write the IMU data and robot location to the CSV file
csv_file << msg->header.seq << ","
<< msg->angular_velocity.x << "," << msg->angular_velocity.y << "," << msg->angular_velocity.z << ","
<< msg->linear_acceleration.x << "," << msg->linear_acceleration.y << "," << msg->linear_acceleration.z << ","
<< model_state.response.pose.position.x << "," << model_state.response.pose.position.y << "," << model_state.response.pose.position.z << "\n";
// Sleep to achieve the desired frequency
rate->sleep();
}
intmain(int argc, char** argv){
// Initialize the ROS node and create a node handle
ros::init(argc, argv, "imu_data_logger_node");
ros::NodeHandle nh;
// Create a service client to call the GetModelState service
model_state_client = nh.serviceClient<gazebo_msgs::GetModelState>("/gazebo/model_states");
// Get the filename from the launch argumentif (argc < 2) {
ROS_ERROR("Please provide the filename as an argument!");
return1;
}
filename = argv[1];
// Open the CSV file for writing
csv_file.open(filename);
csv_file << "seq,angular_velocity_x,angular_velocity_y,angular_velocity_z,linear_acceleration_x,linear_acceleration_y,linear_acceleration_z,position_x,position_y,position_z\n";
// Subscribe to the IMU data topic
ros::Subscriber imu_data_sub = nh.subscribe("/imu/data", 10, imuDataCallback);
// Set the desired frequency
rate = new ros::Rate(desired_frequency);
// Spin the node and wait for callbacks
ros::spin();
// Close the CSV file
csv_file.close();
delete rate;
return0;
}