Overview of Robot Web Tools JavaScript Client Libraries
developroslibjs for core functionality or roslib-examples for implementation patterns).repository·develop·Indexed 21 days ago
https://github.com/robotwebtools/roslibjsThe standard ROS JavaScript Library (version 2.1.0) that enables web applications to communicate with ROS (Robot Operating System) via WebSockets. It provides a central Ros client for managing connections to a rosbridge server, factory methods for creating Topic, Service, Param, ActionClient, and TFClient abstractions, and utilities for handling 3D spatial data via the Pose class.
roslibjs for core functionality or roslib-examples for implementation patterns).npm start command from the root of the roslib-examples package.npm startYou can install the roslib package using any NPM-compatible package manager.
npm install roslibTo ensure your connection is established and to debug issues, listen to the error and connection events on your ros instance. This allows you to report connection status or errors to the console.
ros.on("error", function (error) {
console.log(error);
});
ros.on("connection", function () {
console.log("Connection made!");
});The Ros class acts as an EventEmitter that routes incoming rosbridge protocol messages to specific event listeners based on their type:
publish type, the client emits an event named after the topic field.serviceResponse, the client emits an event named after the message id.callService type, the client emits an event named after the service field.sendGoal, cancelGoal, feedback, or result are emitted using their respective id.op: 'status' emit status:<id> or simply status if no ID is present.The UrdfVisual class supports several geometry types through the UrdfGeometryLike union type. When a <geometry> tag is parsed, it will be instantiated as one of the following based on its child element:
UrdfMesh: For <mesh> elements.UrdfSphere: For <sphere> elements.UrdfBox: For <box> elements.UrdfCylinder: For <cylinder> elements.If an unknown geometry type is encountered, a warning is logged to the console and the geometry is set to null.
The AbstractTransport class provides a default implementation for decoding raw data received from the transport layer into structured RosbridgeMessage objects. It automatically detects and handles several compression and serialization formats:
Blob.ArrayBuffer.RosbridgePngMessage is received, the transport decompresses the PNG data to extract the underlying RosbridgeMessage.RosbridgeFragmentMessage types by buffering fragments and reconstructing the full JSON message once all parts (identified by a unique id) are received.If any decoding step fails, an error event is emitted.
The Ros class is the central entry point for interacting with a ROS master via a rosbridge server. You can initialize it by providing a url in the constructor to attempt an immediate connection, or call .connect(url) manually.
By default, it uses a WebSocketTransportFactory. You can provide a custom transportFactory in the constructor if you need a different transport mechanism.
Common events emitted by the Ros instance:
connection: Emitted when successfully connected to the rosbridge server.close: Emitted when disconnected.error: Emitted when a transport or ROS error occurs.<topicName>: Emitted when a message is received on a specific topic (e.g., ros.emit('chatter', message)).<serviceID>: Emitted when a service response is received with a specific ID.import Ros from 'roslib';
const ros = new Ros({
url: 'ws://localhost:9090'
});
ros.on('connection', () => {
console.log('Connected to rosbridge!');
});
ros.on('error', (error) => {
console.error('ROS Error:', error);
});If you cannot connect, verify that your websocket server is running on port 9090. You can check for an active listener on that port using netstat.
netstat -a | grep 9090The ITransport interface defines the abstraction for sending and receiving messages between the client and the rosbridge server. It is inspired by the WebSocket API and provides methods for managing the connection lifecycle and message transmission.
Key capabilities include:
open, close, error, and message events.RosbridgeMessage objects via .send()..isConnecting(), .isOpen(), .isClosing(), and .isClosed()..close().// Example of how an ITransport implementation might be used
const transport: ITransport = getTransportInstance();
transport.on('open', () => console.log('Connected!'));
transport.on('message', (message) => console.log('Received:', message));
transport.on('error', (err) => console.error('Transport error:', err));
transport.send({ type: 'op', topic: '/chatter', msg: { data: 'hello' } });The library includes built-in math classes for handling common ROS geometry messages:
Pose: Represents a position and orientation.Quaternion: Represents a 4D rotation.Transform: Represents a translation and rotation.Vector3: Represents a 3D vector.You can turn an Action instance into an action server by calling advertise(). This allows the client to receive goal requests and manage their lifecycle.
actionCallback: Triggered when a new goal is received. It receives the goal data and a unique id for that goal.cancelCallback: Triggered when the specific goal associated with the provided id is canceled.Use the provided helper methods (sendFeedback, setSucceeded, setCanceled, setFailed) within your callbacks to communicate the status of the goal back to the client using the goal's id.
const action = new Action({
ros: ros,
name: '/fibonacci',
actionType: 'example_interfaces/Fibonacci'
});
action.advertise(
(goal, id) => {
console.log(`Received goal ${id}:`, goal);
// Simulate work and send feedback
action.sendFeedback(id, { current_value: 1 });
// Complete the action
action.setSucceeded(id, { result: 1 });
},
(id) => {
console.log(`Goal ${id} was canceled`);
}
);
// To stop advertising the action:
// action.unadvertise();