|
| 1 | +// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + |
| 9 | +// rosocket demo server. |
| 10 | +// |
| 11 | +// Bridges two ROS 2 endpoints to plain WebSocket URLs so a browser can |
| 12 | +// drive them with built-in `WebSocket` + `JSON`, no client library: |
| 13 | +// |
| 14 | +// ws://<host>:9000/topic/chatter std_msgs/msg/String |
| 15 | +// ws://<host>:9000/service/add_two_ints example_interfaces/srv/AddTwoInts |
| 16 | +// |
| 17 | +// Run inside WSL (where ROS 2 is sourced): |
| 18 | +// node demo/rosocket/server.mjs |
| 19 | +// |
| 20 | +// To exercise the service, start the existing AddTwoInts example in a |
| 21 | +// second terminal (it implements `/add_two_ints`): |
| 22 | +// node example/services/service/service-example.mjs |
| 23 | +// |
| 24 | +// Then open demo/rosocket/index.html on the Windows host browser. WSL2 |
| 25 | +// forwards localhost so `ws://localhost:9000` works as-is. See README.md |
| 26 | +// for fallback instructions. |
| 27 | + |
| 28 | +import rclnodejs from '../../index.js'; |
| 29 | +import { startRosocket } from '../../rosocket/index.js'; |
| 30 | + |
| 31 | +const PORT = Number(process.env.PORT) || 9000; |
| 32 | +const HOST = process.env.HOST || '0.0.0.0'; |
| 33 | + |
| 34 | +await rclnodejs.init(); |
| 35 | +const node = rclnodejs.createNode('rosocket_demo_node'); |
| 36 | +rclnodejs.spin(node); |
| 37 | + |
| 38 | +const bridge = await startRosocket({ |
| 39 | + node, |
| 40 | + port: PORT, |
| 41 | + host: HOST, |
| 42 | + topicTypes: { |
| 43 | + '/chatter': 'std_msgs/msg/String', |
| 44 | + }, |
| 45 | + serviceTypes: { |
| 46 | + '/add_two_ints': 'example_interfaces/srv/AddTwoInts', |
| 47 | + }, |
| 48 | +}); |
| 49 | + |
| 50 | +const displayHost = HOST === '0.0.0.0' || HOST === '::' ? 'localhost' : HOST; |
| 51 | +const baseUrl = `ws://${displayHost}:${bridge.port}`; |
| 52 | +console.log( |
| 53 | + `[rosocket-demo] listening on ${baseUrl} (bind=${HOST}:${bridge.port})` |
| 54 | +); |
| 55 | +console.log('[rosocket-demo] endpoints:'); |
| 56 | +console.log(` ${baseUrl}/topic/chatter`); |
| 57 | +console.log(` ${baseUrl}/service/add_two_ints`); |
| 58 | +console.log('Open demo/rosocket/index.html in the host browser to try it.'); |
| 59 | + |
| 60 | +const shutdown = () => { |
| 61 | + bridge.close().finally(() => { |
| 62 | + try { |
| 63 | + rclnodejs.shutdown(); |
| 64 | + } catch (_) {} |
| 65 | + process.exit(0); |
| 66 | + }); |
| 67 | +}; |
| 68 | +process.on('SIGINT', shutdown); |
| 69 | +process.on('SIGTERM', shutdown); |
0 commit comments