roslibjs

repository·develop·Indexed 21 days ago

https://github.com/robotwebtools/roslibjs

The 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.

Tokens
7.5K
Snippets
30
Records
44
Agent score
71%

What's inside roslibjs

  1. Overview of Robot Web Tools JavaScript Client Libraries

    develop
    Robot Web Tools provides a suite of JavaScript client libraries designed to interact with ROS (Robot Operating System). The project is organized as a monorepo containing several specialized packages. To use these tools, you should refer to the specific documentation for the package that meets your needs (e.g., roslibjs for core functionality or roslib-examples for implementation patterns).
  2. Monitor ROS connection events

    develop

    To 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!");
    });
  3. How the Ros client manages events and messages

    develop

    The Ros class acts as an EventEmitter that routes incoming rosbridge protocol messages to specific event listeners based on their type:

    1. Topic Messages: If a message is a publish type, the client emits an event named after the topic field.
    2. Service Responses: If a message is a serviceResponse, the client emits an event named after the message id.
    3. Service Calls: If a message is a callService type, the client emits an event named after the service field.
    4. Action Messages: Messages for sendGoal, cancelGoal, feedback, or result are emitted using their respective id.
    5. Status Messages: Messages with op: 'status' emit status:<id> or simply status if no ID is present.
  4. Supported URDF geometry types

    develop

    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.

  5. How transport layers handle different message formats

    develop

    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:

    • JSON: Standard JSON strings.
    • BSON: Handled if the data is a Blob.
    • CBOR: Handled if the data is an ArrayBuffer.
    • PNG Compression: If a RosbridgePngMessage is received, the transport decompresses the PNG data to extract the underlying RosbridgeMessage.
    • Message Fragmentation: The transport manages 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.

  6. Initialize and connect the Ros client

    develop

    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);
    });
  7. The ITransport interface

    develop

    The 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:

    • Event Listening: Listen for open, close, error, and message events.
    • Message Transmission: Send RosbridgeMessage objects via .send().
    • Connection State: Query the current state using .isConnecting(), .isOpen(), .isClosing(), and .isClosed().
    • Lifecycle Management: Explicitly terminate the connection using .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' } });
  8. Use the Action class as a server to advertise actions

    develop

    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();