### Start rclnodejs Action Server Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/actions/README.md Starts the basic action server for demonstrating action communication. Ensure ROS 2 is installed and sourced, and navigate to the example directory. ```bash cd example/actions node action_server/action-server-example.mjs ``` -------------------------------- ### Run Lifecycle Node Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/lifecycle/README.md Execute the lifecycle node example using Node.js. Ensure you have the necessary dependencies installed. ```bash node lifecycle-node-example.mjs ``` -------------------------------- ### Install and Run Manipulator Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/electron/manipulator/README.md Installs dependencies and starts the Electron-based manipulator demo. Ensure ROS 2 is sourced before running these commands. ```bash cd demo/electron/manipulator source /opt/ros//setup.bash # required before install and launch npm install npm start ``` -------------------------------- ### Start rclnodejs Action Client Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/actions/README.md Starts the basic action client to communicate with an action server. This client sends a goal, receives feedback, and processes the final result. ```bash cd example/actions node action_client/action-client-example.mjs ``` -------------------------------- ### Run ParameterClient Basic Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md This example shows basic usage of the ParameterClient to get and set parameter values. It requires the turtlesim node to be running in a separate terminal. ```bash ros2 run turtlesim turtlesim_node ``` ```bash cd example/parameter node parameter-client-basic-example.mjs ``` -------------------------------- ### Controlled Startup Sequences with Lifecycle Nodes Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/lifecycle-nodes.md Implement controlled startup sequences by defining node states like 'configure' and 'activate'. This example shows a camera node initializing hardware and starting capture. ```javascript onConfigure() { // Initialize camera hardware // Allocate memory buffers // Set up image processing pipeline } onActivate() { // Start camera capture // Begin publishing images } ``` -------------------------------- ### Run Parameter Declaration Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md Execute this script to declare and inspect a parameter. Ensure ROS 2 is installed and sourced, and navigate to the example directory. ```bash cd example/parameter node parameter-declaration-example.mjs ``` -------------------------------- ### Install and Run ROS 2 Car Control Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/electron/car/README.md Steps to install dependencies and start the car control demo application. Ensure ROS 2 is sourced before running these commands. ```bash cd demo/electron/car source /opt/ros//setup.bash # required before install and launch npm install npm start ``` -------------------------------- ### Run Publisher Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/README.md Executes a ROS 2 publisher example. Ensure you are in a cloned repository and have sourced your ROS 2 environment. ```bash node example/topics/publisher/publisher-example.mjs ``` -------------------------------- ### Run Packaged Turtle TF2 Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/electron/turtle_tf2/README.md Example of how to run the packaged standalone application. ROS 2 must be installed and sourced. ```bash source /opt/ros/$ROS_DISTRO/setup.bash ./out/rclnodejs-turtle-tf2-demo-linux-x64/rclnodejs-turtle-tf2-demo ``` -------------------------------- ### Package Installation Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/rclcpp/CMakeLists.txt Marks the package for installation. ```cmake ament_package() ``` -------------------------------- ### Run rclnodejs Action Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/actionlib.md Starts the action server example. Navigate to the rclnodejs directory and execute the provided Node.js script. ```bash # Terminal 1 - Start the action server cd /path/to/rclnodejs node example/actions/action_server/action-server-example.js ``` -------------------------------- ### Install Dependencies Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/web/typescript/README.md Installs the necessary npm packages for the demo. ```bash cd demo/web/typescript npm install ``` -------------------------------- ### Install and Run Electron Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/electron/topics/README.md Steps to install dependencies and launch the rclnodejs Electron demo. Ensure ROS 2 is sourced before running. ```bash cd demo/electron/topics source /opt/ros//setup.bash # required before launch npm install npm start ``` -------------------------------- ### Run GetMap Examples with Test Script Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/services/README.md Executes the GetMap service and client examples using a convenience test script. This script automates the process of starting the service, testing the client, and cleaning up. ```bash cd /path/to/rclnodejs ./test_getmap_examples.sh ``` -------------------------------- ### Start rclnodejs Action Cancellation Client Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/actions/README.md Starts an action client designed to demonstrate goal cancellation. This client sends a goal, receives feedback for a period, and then cancels the ongoing goal. ```bash node action_client/action-client-cancel-example.mjs ``` -------------------------------- ### ParameterClient Advanced Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md A comprehensive example showcasing all features of ParameterClient, including declaring parameters, describing parameters, getting parameter types, handling timeouts, and request cancellation. ```APIDOC ## ParameterClient Advanced Example ### Description Provides a comprehensive demonstration of all `ParameterClient` features and capabilities. This includes declaring parameters on a target node and utilizing all client operations such as listing, getting/setting single/multiple parameters, describing parameters, retrieving parameter types, and handling timeouts and request cancellation. ### Run Command `node parameter-client-advanced-example.mjs` ``` -------------------------------- ### Run Built-in Observable Subscription Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/observable-subscriptions.md Execute the pre-built rclnodejs observable subscription example. This requires running a publisher in a separate terminal. ```bash # Terminal 1 - Start a publisher node example/topics/publisher/publisher-example.js # Terminal 2 - Run the observable subscription example node example/topics/subscriber/subscription-observable-example.js ``` -------------------------------- ### Hardware Driver Initialization Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/lifecycle/README.md Example of initializing hardware connections in the onConfigure state and starting hardware communication in the onActivate state for a hardware driver lifecycle node. ```javascript onConfigure() { // Initialize hardware connections this.initializeHardware(); return rclnodejs.lifecycle.CallbackReturnCode.SUCCESS; } onActivate() { // Start hardware communication this.startHardwareStreaming(); return rclnodejs.lifecycle.CallbackReturnCode.SUCCESS; } ``` -------------------------------- ### Run Parameter Declaration Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/parameter-service.md Execute the parameter declaration example script from the rclnodejs repository. ```bash cd /path/to/rclnodejs node example/parameter/parameter-declaration-example.js ``` -------------------------------- ### Run Subscriber Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/topics/README.md Starts the subscriber node to receive ROS 2 messages. This should be run in a separate terminal after the publisher. ```bash node subscriber/subscription-example.mjs ``` -------------------------------- ### Implement Parameter Service Node Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/parameter-service.md Create a node that starts the parameter service, which is enabled by default but can be explicitly controlled. This example shows declaring multiple parameters with their descriptors. ```javascript class ParameterServiceNode { constructor() { // Parameter services are enabled by default // You can explicitly control them via NodeOptions const NodeOptions = rclnodejs.NodeOptions; const options = new NodeOptions(); options.startParameterServices = true; // default is true this.node = rclnodejs.createNode('param_service_node', options); // Declare some parameters this.declareParameters(); console.log('Parameter services are running'); } declareParameters() { const parameters = [ new Parameter('device_name', ParameterType.PARAMETER_STRING, 'sensor_1'), new Parameter('sample_rate', ParameterType.PARAMETER_DOUBLE, 100.0), new Parameter('enable_debug', ParameterType.PARAMETER_BOOL, false), ]; const descriptors = parameters.map( (param) => new ParameterDescriptor( param.name, param.type, `Parameter: ${param.name}` ) ); this.node.declareParameters(parameters, descriptors); } async run() { console.log('Node running with parameter services...'); rclnodejs.spin(this.node); } } // Usage async function main() { await rclnodejs.init(); const paramNode = new ParameterServiceNode(); await paramNode.run(); } main().catch(console.error); ``` -------------------------------- ### Install Demo Dependencies Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/actions/README.md Install the demo's npm dependencies, ignoring scripts to use the prebuilt rclnodejs package. ```bash npm install --ignore-scripts ``` -------------------------------- ### Run Parameter Override Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md Run this example to demonstrate overriding a declared parameter's value from the command line. Prerequisites include sourcing ROS 2 and navigating to the example directory. ```bash cd example/parameter node parameter-override-example.mjs ``` -------------------------------- ### Manage Service and Introspection Resource Cleanup Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/service-introspection.md This example demonstrates creating a managed service that includes starting the service, configuring introspection, and ensuring proper cleanup by disabling introspection before shutting down. It also handles SIGINT and SIGTERM signals for graceful exit. ```javascript function createManagedIntrospectionService() { let service; let node; async function start() { await rclnodejs.init(); node = new rclnodejs.Node('managed_service'); service = node.createService( 'example_interfaces/srv/AddTwoInts', 'managed_service', handleRequest ); configureIntrospectionSafely( service, node.getClock(), rclnodejs.QoS.profileSystemDefault, rclnodejs.ServiceIntrospectionStates.CONTENTS ); rclnodejs.spin(node); } function stop() { if (service) { // Disable introspection before cleanup try { service.configureIntrospection( node.getClock(), rclnodejs.QoS.profileSystemDefault, rclnodejs.ServiceIntrospectionStates.OFF ); } catch (error) { console.warn('Failed to disable introspection:', error.message); } } rclnodejs.shutdown(); } function handleRequest(request, response) { const result = response.template; result.sum = request.a + request.b; response.send(result); } // Handle cleanup on exit process.on('SIGINT', stop); process.on('SIGTERM', stop); return { start, stop }; } ``` -------------------------------- ### Install rclnodejs Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/services/README.md Installs the rclnodejs demo package, linking the local rclnodejs repository. Use --ignore-scripts to prevent native addon rebuilds. ```bash cd demo/typescript/services npm install --ignore-scripts ``` -------------------------------- ### Run rclnodejs Single Goal Action Server Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/actions/README.md Runs an action server example configured to handle only a single goal at a time, useful for testing goal abortion behavior when a new goal arrives. ```bash node action_server/action-server-single-goal-example.mjs ``` -------------------------------- ### Run ParameterWatcher Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md This example showcases the ParameterWatcher, allowing you to monitor specific parameters for changes. It requires the turtlesim node to be running and involves setting parameters in a third terminal to observe updates. ```bash ros2 run turtlesim turtlesim_node ``` ```bash cd example/parameter node parameter-watcher-example.mjs ``` ```bash ros2 param set /turtlesim background_r 200 ros2 param set /turtlesim background_b 100 ros2 param set /turtlesim background_g 50 # This won't trigger (removed from watch list) ``` -------------------------------- ### Run rclnodejs Deferred Execution Action Server Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/actions/README.md Runs an action server example that implements deferred execution, introducing a 3-second delay before processing goals. ```bash node action_server/action-server-defer-example.mjs ``` -------------------------------- ### Install rclnodejs Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/topics/README.md Install rclnodejs and its dependencies. Ensure you are in the correct directory. ```bash cd demo/typescript/topics npm install ``` -------------------------------- ### Start rclnodejs-web Runtime with JSON Configuration Source: https://github.com/robotwebtools/rclnodejs/blob/develop/web/README.md Starts the rclnodejs-web runtime by loading its configuration from a specified JSON file. This method is an alternative to using command-line arguments for configuration. ```bash npx -p rclnodejs rclnodejs-web web.json ``` -------------------------------- ### Full Service and Client with Introspection Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/service-introspection.md This example sets up a service, a client, and a monitor node to demonstrate service introspection. It configures introspection for both the service and client, sends requests, and logs service events. Introspection configuration is conditional based on the ROS 2 distribution. ```javascript const rclnodejs = require('rclnodejs'); async function runIntrospectionExample() { await rclnodejs.init(); // Create nodes const serviceNode = new rclnodejs.Node('introspection_service_node'); const clientNode = new rclnodejs.Node('introspection_client_node'); const monitorNode = new rclnodejs.Node('introspection_monitor_node'); // Create service const service = serviceNode.createService( 'example_interfaces/srv/AddTwoInts', 'add_two_ints_introspection', (request, response) => { console.log(`Service processing: ${request.a} + ${request.b}`); const result = response.template; result.sum = request.a + request.b; response.send(result); } ); // Create client const client = clientNode.createClient( 'example_interfaces/srv/AddTwoInts', 'add_two_ints_introspection' ); // Create event monitor subscription const eventSubscription = monitorNode.createSubscription( 'example_interfaces/srv/AddTwoInts_Event', '/add_two_ints_introspection/_service_event', (eventMsg) => { console.log('=== Service Event ==='); console.log(`Event Type: ${getEventTypeName(eventMsg.info.event_type)}`); console.log( `Timestamp: ${eventMsg.info.stamp.sec}.${eventMsg.info.stamp.nanosec}` ); console.log(`Sequence: ${eventMsg.info.sequence_number}`); if (eventMsg.request && eventMsg.request.length > 0) { console.log( `Request: a=${eventMsg.request[0].a}, b=${eventMsg.request[0].b}` ); } if (eventMsg.response && eventMsg.response.length > 0) { console.log(`Response: sum=${eventMsg.response[0].sum}`); } console.log('====================\n'); } ); // Configure introspection if supported if ( rclnodejs.DistroUtils.getDistroId() > rclnodejs.DistroUtils.getDistroId('humble') ) { const clock = serviceNode.getClock(); const qos = rclnodejs.QoS.profileSystemDefault; // Configure both service and client introspection service.configureIntrospection( clock, qos, rclnodejs.ServiceIntrospectionStates.CONTENTS ); client.configureIntrospection( clock, qos, rclnodejs.ServiceIntrospectionStates.CONTENTS ); console.log('Introspection configured for both service and client'); } else { console.log('Introspection not supported in this ROS 2 version'); } // Wait for service if (!(await client.waitForService(5000))) { console.error('Service not available'); return; } // Start spinning all nodes serviceNode.spin(); clientNode.spin(); monitorNode.spin(); // Make multiple service calls for (let i = 0; i < 3; i++) { const request = { a: BigInt(Math.floor(Math.random() * 100)), b: BigInt(Math.floor(Math.random() * 100)), }; console.log(`\nSending request ${i + 1}: ${request.a} + ${request.b}`); client.sendRequest(request, (response) => { console.log(`Received response ${i + 1}: ${response.sum}`); }); // Wait between calls await new Promise((resolve) => setTimeout(resolve, 2000)); } } function getEventTypeName(eventType) { const eventTypes = { 0: 'REQUEST_SENT', 1: 'REQUEST_RECEIVED', 2: 'RESPONSE_SENT', 3: 'RESPONSE_RECEIVED', }; return eventTypes[eventType] || `UNKNOWN(${eventType})`; } // Run the example runIntrospectionExample().catch(console.error); ``` -------------------------------- ### Run AddTwoInts Service Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/services/README.md Starts the AddTwoInts service server. This script should be run in a separate terminal before starting the client. ```bash cd /path/to/rclnodejs node example/services/service/service-example.mjs ``` -------------------------------- ### Start Server and Client Simultaneously Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/actions/README.md Execute both the action server and client concurrently using npm scripts. ```bash npm run start:both ``` -------------------------------- ### Parameter Declaration Example Output Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/parameter-service.md Expected output when running the parameter declaration example, showing declared parameter name, type, value, and descriptor. ```bash Declared parameter: param1 Parameter details: Parameter { name: 'param1', type: 4, value: 'hello world' } ParameterDescriptor { name: 'param1', type: 4, description: '', additionalConstraints: '', readOnly: false } ``` -------------------------------- ### Install and Run Turtle TF2 Demo Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/electron/turtle_tf2/README.md Steps to install the demo and run the turtlesim node and the Electron app. Ensure ROS 2 is sourced in the same terminal as npm commands. ```bash cd demo/electron/turtle_tf2 source /opt/ros//setup.bash # required, in the same terminal as npm install / npm start npm install ros2 run turtlesim turtlesim_node # in another sourced terminal npm start ``` -------------------------------- ### Start rclnodejs-web Runtime with Command Line Arguments Source: https://github.com/robotwebtools/rclnodejs/blob/develop/web/README.md Starts the rclnodejs-web runtime using command-line arguments to configure ports and expose ROS 2 services, topics, and actions for browser access. Ensure ROS 2 environment is sourced before execution. ```bash source /opt/ros//setup.bash npx -p rclnodejs rclnodejs-web \ --port 9000 --http-port 9001 \ --call /add_two_ints=example_interfaces/srv/AddTwoInts \ --publish /chatter=std_msgs/msg/String \ --subscribe /scan=sensor_msgs/msg/LaserScan ``` -------------------------------- ### Start Action Client Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/actions/README.md Run the TypeScript action client demo in a separate terminal to interact with the server. ```bash npm run start:client ``` -------------------------------- ### Start Action Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/typescript/actions/README.md Run the TypeScript action server demo in a separate terminal. ```bash npm run start:server ``` -------------------------------- ### Manual Landing Page Rebuild Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tools/jsdoc/README.md Example script to manually rebuild the `build/gh-pages-docs/docs/index.html` file for a specific published version. It requires setting several environment variables to point to the correct paths for package metadata and documentation roots. ```bash mkdir -p build/gh-pages-docs/.tmp git show 1.8.0:package.json > build/gh-pages-docs/.tmp/package-1.8.0.json export RCLNODEJS_DOCS_ROOT="$PWD/build/gh-pages-docs/docs" export RCLNODEJS_DOCS_INDEX_PATH="$PWD/build/gh-pages-docs/docs/index.html" export RCLNODEJS_LOCAL_INDEX_PATH='' export RCLNODEJS_PACKAGE_JSON_PATH="$PWD/build/gh-pages-docs/.tmp/package-1.8.0.json" node tools/jsdoc/build-index.js rm -rf build/gh-pages-docs/.tmp ``` -------------------------------- ### Allow-list Rejection Example (curl) Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/web/javascript/index.html Example using curl to demonstrate an allow-list rejection scenario, resulting in a 404 status and a structured error body. ```bash curl -sS -X POST http://localhost:9001/capability/call/dangerous \ -H 'content-type: application/json' -d '{}' # => {"ok":false,"error":"capability not exposed: call /dangerous","code":"not_exposed"} ``` -------------------------------- ### Start ROSocket Server with Pre-declared Types Source: https://github.com/robotwebtools/rclnodejs/blob/develop/rosocket/README.md Initialize ROS, start a node, and then launch the ROSocket server on port 9000. Pre-declare topic and service types for client convenience. ```javascript const rclnodejs = require('rclnodejs'); const { startRosocket } = require('rclnodejs/rosocket'); await rclnodejs.init(); const node = new rclnodejs.Node('rosocket_node'); rclnodejs.spin(node); await startRosocket({ node, port: 9000, // optional: pre-declare types so clients can omit ?type= topicTypes: { '/chatter': 'std_msgs/msg/String' }, serviceTypes: { '/add_two_ints': 'example_interfaces/srv/AddTwoInts' }, }); ``` -------------------------------- ### System Orchestration with Lifecycle Node Commands Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/lifecycle-nodes.md Orchestrate the startup of multiple nodes in a specific order using lifecycle commands. This example configures camera nodes before processing nodes, then activates all. ```bash # Start all camera nodes first ros2 lifecycle set /camera_left configure ros2 lifecycle set /camera_right configure # Then start processing nodes ros2 lifecycle set /image_processor configure ros2 lifecycle set /object_detector configure # Finally activate everything ros2 lifecycle set /camera_left activate ros2 lifecycle set /camera_right activate ros2 lifecycle set /image_processor activate ros2 lifecycle set /object_detector activate ``` -------------------------------- ### Run ROS Graph Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/graph/README.md Execute the comprehensive ROS graph introspection example using Node.js. Ensure you have rclnodejs installed and a ROS 2 environment sourced. ```bash node ros-graph-example.mjs ``` -------------------------------- ### Start Static File Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/web/javascript/README.md Run the static file server in the second shell to host the HTML page and map SDK requests. This makes the SDK importable via a URL. ```bash node static.mjs ``` -------------------------------- ### Node Creation and Service/Client Setup in rclnodejs Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/service-introspection.md Demonstrates how to create an rclnodejs Node, and then set up a service and a client. It emphasizes the importance of waiting for service availability before proceeding. ```javascript // Use the constructor pattern (as in tests) const node = new rclnodejs.Node('node_name'); // Create service and client const service = node.createService('srv_type', 'service_name', callback); const client = node.createClient('srv_type', 'service_name'); // Always wait for service availability if (!(await client.waitForService(1000))) { throw new Error('client unable to access service'); } // Start spinning node.spin(); ``` -------------------------------- ### System Management Script for Orchestrating Nodes Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/lifecycle-nodes.md An example JavaScript script demonstrating how to orchestrate the startup sequence of multiple lifecycle nodes, including configuring and activating them in a defined order. ```javascript // system-manager.js const rclnodejs = require('rclnodejs'); class SystemManager { constructor() { this.nodes = [ 'camera_left', 'camera_right', 'image_processor', 'robot_controller', ]; } async init() { await rclnodejs.init(); this.node = rclnodejs.createNode('system_manager'); } async startupSequence() { console.log('🚀 Starting system startup sequence...'); // Phase 1: Configure all nodes for (const nodeName of this.nodes) { await this.transitionNode(nodeName, 'configure'); } // Phase 2: Activate in specific order const activationOrder = [ 'camera_left', 'camera_right', 'image_processor', 'robot_controller', ]; for (const nodeName of activationOrder) { await this.transitionNode(nodeName, 'activate'); await this.sleep(1000); // Wait 1 second between activations } console.log('✅ System startup complete!'); } async transitionNode(nodeName, transition) { // Implementation would call lifecycle service console.log(`🔄 ${transition} ${nodeName}`); } sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } } ``` -------------------------------- ### Complete Test-Based Example for Type Description Service Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/type-description-service.md This example showcases the full workflow of using the Type Description Service. It initializes rclnodejs, creates a node and publisher, retrieves publisher information, and then uses a client to request and process the type description for a given topic type. It includes checks for ROS 2 version compatibility and handles service availability and response processing. ```javascript const rclnodejs = require('rclnodejs'); const TypeDescriptionService = require('rclnodejs/lib/type_description_service'); const DistroUtils = require('rclnodejs/lib/distro'); async function testTypeDescriptionService() { // Check if Type Description Service is supported if (DistroUtils.getDistroId() < DistroUtils.getDistroId('jazzy')) { console.log( 'Type Description Service is not supported in this ROS 2 version' ); return; } await rclnodejs.init(); const nodeName = 'test_type_description_service'; const node = rclnodejs.createNode(nodeName); rclnodejs.spin(node); // Create a publisher (this registers the type with the node) const topic = 'test_get_type_description_publisher'; const topicType = 'std_msgs/msg/String'; node.createPublisher(topicType, topic); // Get publisher information to extract type hash const infos = node.getPublishersInfoByTopic( '/test_get_type_description_publisher', false ); if (infos.length === 0) { throw new Error('Publisher info not found'); } console.log('Publisher info found:', infos[0]); // Create a client to get the type description const request = { type_name: topicType, type_hash: TypeDescriptionService.toTypeHash(infos[0].topic_type_hash), include_type_sources: true, }; const serviceName = `/test_type_description_service/get_type_description`; const GetTypeDescription = 'type_description_interfaces/srv/GetTypeDescription'; const client = node.createClient(GetTypeDescription, serviceName); const result = await client.waitForService(5000); if (!result) { throw new Error('Service not available'); } // Send request and handle response const promise = new Promise((resolve, reject) => { const timer = setInterval(() => { client.sendRequest(request, (response) => { clearInterval(timer); console.log('Response received:'); console.log('- Successful:', response.successful); if (response.successful) { console.log( '- Type name:', response.type_description.type_description.type_name ); console.log( '- Number of fields:', response.type_description.type_description.fields.length ); console.log('- Type sources length:', response.type_sources.length); // Print field information response.type_description.type_description.fields.forEach( (field, index) => { console.log( ` Field ${index}: ${field.name} (${JSON.stringify(field.type)})` ); } ); // Print source if available if (response.type_sources.length > 0) { console.log('- Raw file contents:'); console.log(response.type_sources[0].raw_file_contents); } resolve(response); } else { reject( new Error( `Type description request failed: ${response.failure_reason}` ) ); } }); }, 2000); }); await promise; console.log('Test completed successfully'); rclnodejs.shutdown(); } // Run the test testTypeDescriptionService().catch(console.error); ``` -------------------------------- ### Robot Configuration Service Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/ros2-basic-concepts.md A practical example of a service server managing robot configuration. It provides services to get the current configuration and to set the safety mode. ```javascript const rclnodejs = require('rclnodejs'); class RobotConfigurationService { constructor() { this.robotConfig = { maxSpeed: 2.0, safetyEnabled: true, operationMode: 'autonomous', }; } async start() { await rclnodejs.init(); this.node = rclnodejs.createNode('robot_config_service'); // Service to get robot configuration this.node.createService( 'example_interfaces/srv/Trigger', 'get_robot_config', (request, response) => { const result = response.template; result.success = true; result.message = JSON.stringify(this.robotConfig); response.send(result); } ); // Service to set max speed this.node.createService( 'example_interfaces/srv/SetBool', 'set_safety_mode', (request, response) => { this.robotConfig.safetyEnabled = request.data; const result = response.template; result.success = true; result.message = `Safety mode set to: ${request.data}`; response.send(result); } ); console.log('Robot configuration services ready'); rclnodejs.spin(this.node); } } const configService = new RobotConfigurationService(); configService.start().catch(console.error); ``` -------------------------------- ### Resource Management with Lifecycle Node States Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/lifecycle-nodes.md Manage resource consumption by activating expensive operations only when the node is active. This example starts GPU processing on activation and stops it on deactivation. ```javascript onActivate() { // Only start expensive GPU processing when active this.startGPUProcessing(); } onDeactivate() { // Free GPU resources when inactive this.stopGPUProcessing(); } ``` -------------------------------- ### Start WebSocket Gateway (rosocket) Source: https://github.com/robotwebtools/rclnodejs/blob/develop/README.md Launches the rosocket WebSocket gateway. This is a thin gateway with zero browser dependencies, suitable for quick prototypes. ```bash npx rosocket --port 9000 --topic /chatter:std_msgs/msg/String ``` -------------------------------- ### Run MessageIntrospector Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/message-introspector/README.md Execute the message introspection example script. ```bash node message-introspector-example.mjs ``` -------------------------------- ### Navigate to Demo Directory Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/web/javascript/README.md Change the current directory to the JavaScript demo folder. ```bash cd demo/web/javascript ``` -------------------------------- ### Run ParameterClient Advanced Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md Demonstrates advanced ParameterClient functionality, including listing available parameters and retrieving parameter descriptors. This script should be run after the turtlesim node is active. ```bash cd example/parameter node parameter-client-advanced-example.mjs ``` -------------------------------- ### Install rclnodejs from npm Source: https://github.com/robotwebtools/rclnodejs/blob/develop/README.md Use this command to install rclnodejs as a dependency for your Node.js application. This is the recommended method for most users. ```bash npm i rclnodejs ``` -------------------------------- ### Install rclnodejs Module Source: https://github.com/robotwebtools/rclnodejs/blob/develop/docs/BUILDING.md Install the rclnodejs module using npm. This command builds the native addon using node-gyp. ```javascript npm install ``` -------------------------------- ### Run ROS 2 Runtime and Demo Server Source: https://github.com/robotwebtools/rclnodejs/blob/develop/demo/web/typescript/README.md Starts the ROS 2 runtime and a local demo server that includes a service and a publisher. This is a convenience script for the demo. ```bash source /opt/ros//setup.bash npm run server # rclnodejs/web : ws://localhost:9000/capability # also http://localhost:9001/capability ``` -------------------------------- ### Parameter Override Example Output Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/parameter-service.md Expected output when running the parameter override example, indicating the parameter name and its overridden value. ```bash Declared parameter: param1 Parameter overridden: Parameter { name: 'param1', type: 4, value: 'hello ros2' } ``` -------------------------------- ### ParameterClient Basic Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/parameter/README.md Demonstrates basic access and modification of parameters on a remote node using ParameterClient. It covers connecting to a node, listing parameters, and getting/setting individual and multiple parameters. ```APIDOC ## ParameterClient Basic Example ### Description Demonstrates accessing and modifying parameters on a remote node using `ParameterClient`. This example covers connecting to a target node, listing available parameters, and performing single and batch get/set operations. ### Target Node `turtlesim` (run: `ros2 run turtlesim turtlesim_node`) ### Run Command `node parameter-client-basic-example.mjs` ``` -------------------------------- ### Start rclnodejs Service for Service Test Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/README.md Start the rclnodejs service in one terminal for the service test. This should be run before the client benchmark. ```bash # Terminal 1: Start service (adjust for your language) node benchmark/rclnodejs/service/service-stress-test.js -s 1024 # Node.js ``` -------------------------------- ### Basic CMake Project Setup Source: https://github.com/robotwebtools/rclnodejs/blob/develop/test/custom_msg_test/CMakeLists.txt Sets the minimum CMake version and project name. Essential for any CMake project. ```cmake cmake_minimum_required(VERSION 3.8) project(custom_msg_test) ``` -------------------------------- ### Start C++ Service for Service Test Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/README.md Start the C++ service in one terminal for the service test. This should be run before the client benchmark. ```bash # Terminal 1: Start service (adjust for your language) ./service-stress-test -s 1024 # C++ (from build dir) ``` -------------------------------- ### Start Python Service for Service Test Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/README.md Start the Python service in one terminal for the service test. This should be run before the client benchmark. ```bash # Terminal 1: Start service (adjust for your language) python3 service/service-stress-test.py -s 1024 # Python ``` -------------------------------- ### Start rclnodejs Subscriber for Topic Test Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/README.md Start the rclnodejs subscriber in one terminal for the topic test. This should be run before the publisher benchmark. ```bash # Terminal 1: Start subscriber (adjust for your language) node benchmark/rclnodejs/topic/subscription-stress-test.js # Node.js ``` -------------------------------- ### Start Python Subscriber for Topic Test Source: https://github.com/robotwebtools/rclnodejs/blob/develop/benchmark/README.md Start the Python subscriber in one terminal for the topic test. This should be run before the publisher benchmark. ```bash # Terminal 1: Start subscriber (adjust for your language) python3 topic/subscription-stress-test.py # Python ``` -------------------------------- ### Testing and Linting Setup Source: https://github.com/robotwebtools/rclnodejs/blob/develop/test/custom_msg_test/CMakeLists.txt Configures testing and linting dependencies if testing is enabled. Includes options to skip copyright and cpplint checks. ```cmake if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) # the following line skips the linter which checks for copyrights # comment the line when a copyright and license is added to all source files set(ament_cmake_copyright_FOUND TRUE) # the following line skips cpplint (only works in a git repo) # comment the line when this package is in a git repo and when # a copyright and license is added to all source files set(ament_cmake_cpplint_FOUND TRUE) ament_lint_auto_find_test_dependencies() endif() ``` -------------------------------- ### Run Error Handling Example Source: https://github.com/robotwebtools/rclnodejs/blob/develop/example/error-handling/README.md Execute the main error handling example script for rclnodejs. This script demonstrates all 10 error handling patterns. ```bash node example/error-handling/error-handling-example.mjs ``` -------------------------------- ### Build and Source Custom Message Test Package Source: https://github.com/robotwebtools/rclnodejs/blob/develop/test/custom_msg_test/README.md Navigate to the custom message test directory and build the package. Then, source the setup script to make the custom messages available. ```bash # From the test directory cd custom_msg_test colcon build source install/setup.bash ``` -------------------------------- ### Start the Node and Trigger Transitions Source: https://github.com/robotwebtools/rclnodejs/blob/develop/tutorials/lifecycle-nodes.md Starts the node's event loop and manually triggers state transitions. This is used to initiate the lifecycle process. ```javascript // Start spinning the node rclnodejs.spin(lifecycleNode); // Trigger state transitions lifecycleNode.configure(); lifecycleNode.activate(); ```