Skip to content

Instantly share code, notes, and snippets.

@minshallj
Last active March 13, 2023 18:28
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save minshallj/50e6b2e85985ca56e8e0 to your computer and use it in GitHub Desktop.
Save minshallj/50e6b2e85985ca56e8e0 to your computer and use it in GitHub Desktop.
roslibjs example
//* The Ros object, wrapping a web socket connection to rosbridge.
var ros = new ROSLIB.Ros({
url: 'ws://localhost:9090' // url to your rosbridge server
});
//* A topic for messaging.
var exampleTopic = new ROSLIB.Topic({
ros: ros,
name: '/com/endpoint/example', // use a sensible namespace
messageType: 'std_msgs/String'
});
/**
* Serializes an object and publishes it to a std_msgs/String topic.
* @param {ROSLIB.Topic} topic
* A topic to publish to. Must use messageType: std_msgs/String
* @param {Object} obj
* Any object that can be serialized with JSON.stringify
*/
function publishEncoded(topic, obj) {
var msg = new ROSLIB.Message({
data: JSON.stringify(obj)
});
topic.publish(msg);
}
/**
* Decodes an object from a std_msgs/String message.
* @param {Object} msg
* Message from a std_msgs/String topic.
* @return {Object}
* Decoded object from the message.
*/
function decodeMessage(msg) {
return JSON.parse(msg.data);
}
/**
* Typed messaging wrapper for a std_msgs/String ROS Topic.
* @param {ROSLIB.Topic} topic
* A std_msgs/String ROS Topic for multiplexed messaging.
* @constructor
*/
function RosTypedMessaging(topic) {
this.topic = topic;
this.topic.subscribe(this.handleMessage_.bind(this));
}
RosTypedMessaging.prototype.__proto__ = EventEmitter2.prototype;
/**
* Handles an incoming message from the topic by firing an event.
* @param {Object} msg
* @private
*/
RosTypedMessaging.prototype.handleMessage_ = function(msg) {
var decoded = decodeMessage(msg);
var type = decoded.type;
var data = decoded.data;
this.emit(type, data);
};
/**
* Sends a typed message to the topic.
* @param {String} type
* @param {Object} data
*/
RosTypedMessaging.prototype.sendMessage = function(type, data) {
var msg = {type: type, data: data};
publishEncoded(this.topic, msg);
};
//* Example implementation of RosTypedMessaging.
var myMessageChannel = new RosTypedMessaging(exampleTopic);
myMessageChannel.on('fooo', function(data) {
console.log('fooo!', data);
});
setInterval(function() {
var mySyncObject = {
time: Date.now(),
myFavoriteColor: 'red'
};
myMessageChannel.sendMessage('fooo', mySyncObject);
}, 1000);
@meitiever
Copy link

how to receive and parse a custom message?

@minshallj
Copy link
Author

I think roslibjs (and most other things through rosbridge) don't need any extra help for custom messages. Just define messageType: 'my_pkg/MessageTypeName' and see if you can subscribe, and print out the message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment