第一步,先与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
})
},
publishRosTopic(topicName,value){
if(!this.connected){
console.log('ROS未连接');
return
}
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对象,之后直接复用这些对象来发布消息
还有一种更高效的方式,高效改进方案
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'
});
})
}
}
publishRosTopic(topicName,value) {
if(!this.connected ) return
const publisher = this.topicPublishers[topicName];
publisher.publisher(new ROSLIB.Message({data:value}))
}