vue 前端发布ros话题

199 阅读1分钟

第一步,先与ROS通信

//初始化ROS连接
connecToROS(){
  this.ros= new ROSLIB.Ros({
  url:'ws://localhost:9090' //
  });
  this.ros.on('connection',()=>{
  this.connected = true;
  });
  this.ros.on('error',(error)=>{
  console.log('ROS连接错误',,error);
  });
this.ros.on('close',()=>{
  this.connected = false
})
},
//发布ROS话题
publishRosTopic(topicName,value){
  if(!this.connected){
    console.log('ROS未连接');
    return
  }
  //每次点击都会新建Topic对象
  const topic = new ROSLIB.Topic({
    ros:this.ros,
    name:topicName, //动态创建名称
    messageType:'std_msgs/Bool'
  });
  
  const msg = new ROSLIB.Message({
    data:value
    });
    
  topic.publish(msg);
  
  console.log(`已发布话题${topicName}:${value}`);
  
},
mounted(){
  this.connecToROS();
  },
  beforeDestroy(){
    if(this.ros){
      this.ros.close();
    }
  
  }
  • 上面的方式,每次点击按钮,都会创建一个新的ROS Topic 对象,这频繁操作下会产生不必要的开销,更高效的做法是在初始化时一次性创建所有Topic对象,之后直接复用这些对象来发布消息

还有一种更高效的方式,高效改进方案

  • 初始化时预创建所有Topic;
data(){
  return {
    topicPubLishers: {
      start_operation:null,
      pull_over:null,
      //...其他话题...
    }
  }
},

mounted(){
  this.initPublishers();
},

methods:{
  initPublishers(){
    Object.keys(this.topicPublishers).forEach(name=>{
    this.topicPublishers[name] = new ROSLIB.Topic({
    ros:this.ros,
    name:`/${name}`,
    messageType:'std_mags/Bool'
    });
    })
  }
}

  • 发布时,直接复用预创建的Topic
publishRosTopic(topicName,value) {
   if(!this.connected ) return
   //直接使用预先创建的publisher
   const publisher = this.topicPublishers[topicName];
   publisher.publisher(new     ROSLIB.Message({data:value}))


}