- 创建simple.html文件,将代码复制进去。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://cdn.robotwebtools.org /EventEmitter2/current/eventemitter2.min.js"></script>
<script type="text/javascript" src="http://cdn.robotwebtools.org/roslibjs/current/roslib.min.js"></script>
<script type="text/javascript" type="text/javascript">
// Connecting to ROS
// -----------------
var ros = new ROSLIB.Ros({
url : 'ws://localhost:9090'
});
ros.on('connection', function() {
console.log('Connected to websocket server.');
});
ros.on('error', function(error) {
console.log('Error connecting to websocket server: ', error);
});
ros.on('close', function() {
console.log('Connection to websocket server closed.');
});
// Publishing a Topic
// ------------------
var cmdVel = new ROSLIB.Topic({
ros : ros,
name : '/cmd_vel',
messageType : 'geometry_msgs/Twist'
});
var twist = new ROSLIB.Message({
linear : {
x : 0.1,
y : 0.2,
z : 0.3
},
angular : {
x : -0.1,
y : -0.2,
z : -0.3
}
});
cmdVel.publish(twist);
// Subscribing to a Topic
// ----------------------
var listener = new ROSLIB.Topic({
ros : ros,
name : '/listener',
messageType : 'std_msgs/String'
});
listener.subscribe(function(message) {
console.log('Received message on ' + listener.name + ': ' + message.data);
listener.unsubscribe();
});
// Calling a service
// -----------------
var addTwoIntsClient = new ROSLIB.Service({
ros : ros,
name : '/add_two_ints',
serviceType : 'rospy_tutorials/AddTwoInts'
});
var request = new ROSLIB.ServiceRequest({
a : 1,
b : 2
});
addTwoIntsClient.callService(request, function(result) {
console.log('Result for service call on '
+ addTwoIntsClient.name
+ ': '
+ result.sum);
});
// Getting and setting a param value
// ---------------------------------
ros.getParams(function(params) {
console.log(params);
});
var maxVelX = new ROSLIB.Param({
ros : ros,
name : 'max_vel_y'
});
maxVelX.set(0.8);
maxVelX.get(function(value) {
console.log('MAX VAL: ' + value);
});
</script>
</head>
<body>
<h1>Simple roslib Example</h1>
<p>Check your Web Console for output.</p>
</body>
</html>```
2. 运行实例
首先启动ROS,终端输入:
$ roscore
从server发布一条消息来测试我们的JavaScript subscriber:
$ rostopic pub /listener std_msg/String "hello world"
订阅一个topic来测试从浏览器发布消息:
$ rostopic echo /cmd_vel
运行一个service server,用来从从浏览器返回service调用:
$ rosrun rospy_tutorials add_two_ints_server
当所有命令都运行起来之后,我们启动rosbridge v2.0 server:
$ roslaunch rosbridge_server rosbridge_websocket.launch
3. 运行结果:
![simple_add_two_ints](https://img.haomeiwen.com/i3869738/fbe2fefd23ff74f8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![simple_cmd_vel](https://img.haomeiwen.com/i3869738/a01f48b014d6254c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![浏览器控制台输出](https://img.haomeiwen.com/i3869738/b96a39288a4ee68a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论