Repository navigation
Expand file tree
/
Copy pathruntime.mjs
More file actions
189 lines (177 loc) · 6.8 KB
/
Copy pathruntime.mjs
File metadata and controls
189 lines (177 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// rclnodejs/web demo — runtime side (rclnodejs/web runtime + the demo's
// ROS 2 nodes; named `runtime.mjs` to avoid being confused with the
// page-side `static.mjs`).
//
// 1. Source ROS 2 (`source /opt/ros/<distro>/setup.bash`)
// 2. From this folder run `node runtime.mjs`
// 3. In another shell run `node static.mjs` to host
// `index.html` on http://localhost:8080/ — same split as the
// TypeScript playground's `tsx server.ts` + `vite`.
import rclnodejs from '../../../../index.js';
// In a downstream project this is the public, supported import:
// import { createRuntime, WebSocketTransport, HttpTransport } from
// 'rclnodejs/web/server';
// Inside this in-repo demo we use the relative path so the file runs
// from a checkout after the repository dependencies are installed;
// no separate demo installation or dist build is required.
import {
createRuntime,
WebSocketTransport,
HttpTransport,
} from '../../../../lib/runtime/index.js';
const RUNTIME_PORT = Number(process.env.RUNTIME_PORT || 9000);
const HTTP_PORT = Number(process.env.HTTP_PORT || 9001);
function displayHost(host) {
return host === '0.0.0.0' || host === '::' ? 'localhost' : host;
}
// Render the registry as a small human-readable table:
// call /add_two_ints example_interfaces/srv/AddTwoInts
// publish /web_demo_chatter std_msgs/msg/String
// subscribe /web_demo_chatter std_msgs/msg/String
function formatCapabilities(caps) {
const rows = [];
for (const verb of ['call', 'publish', 'subscribe', 'action']) {
for (const [topic, type] of Object.entries(caps[verb] || {})) {
rows.push([verb, topic, type]);
}
}
if (rows.length === 0) return ' (none)';
const w0 = Math.max(...rows.map((r) => r[0].length));
const w1 = Math.max(...rows.map((r) => r[1].length));
return rows
.map(([v, t, ty]) => ` ${v.padEnd(w0)} ${t.padEnd(w1)} ${ty}`)
.join('\n');
}
// ---- Layer 1: rclnodejs core ----------------------------------------
await rclnodejs.init();
const node = rclnodejs.createNode('rclnodejs_web_demo_node');
let stopping = false;
// A real ROS 2 service the browser can call.
node.createService(
'example_interfaces/srv/AddTwoInts',
'/add_two_ints',
(request, response) => {
const reply = response.template;
reply.sum = request.a + request.b;
response.send(reply);
}
);
const Fibonacci = rclnodejs.require('example_interfaces/action/Fibonacci');
new rclnodejs.ActionServer(
node,
'example_interfaces/action/Fibonacci',
'/fibonacci',
async (goalHandle) => {
const sequence = [0, 1];
for (let index = 1; index < goalHandle.request.order; index++) {
await new Promise((resolve) => setTimeout(resolve, 500));
if (stopping || !goalHandle.isActive) {
return new Fibonacci.Result({ sequence });
}
if (goalHandle.isCancelRequested) {
goalHandle.canceled();
return new Fibonacci.Result({ sequence });
}
sequence.push(sequence[index] + sequence[index - 1]);
goalHandle.publishFeedback(new Fibonacci.Feedback({ sequence }));
}
goalHandle.succeed();
return new Fibonacci.Result({ sequence });
},
(goal) =>
Number.isInteger(goal.order) && goal.order >= 2 && goal.order <= 12
? rclnodejs.GoalResponse.ACCEPT
: rclnodejs.GoalResponse.REJECT,
null,
() => rclnodejs.CancelResponse.ACCEPT
);
rclnodejs.spin(node);
// ---- Layer 2 + 3: capability runtime over WebSocket *and* HTTP -------
// The same dispatcher / registry serves both transports — the L2 seam
// is what proves the runtime is transport-agnostic. Browser SDK picks
// a transport from the URL scheme; curl / Postman / AI agents use the
// HTTP one directly.
const runtime = createRuntime({
node,
transports: [
new WebSocketTransport({
port: RUNTIME_PORT,
// '::' = dual-stack: accepts both IPv6 and IPv4-mapped
// connections. Matches Node's http server default and avoids
// the WSL2 / glibc "localhost → ::1" mismatch where
// 0.0.0.0-only servers appear unreachable from the browser.
host: '::',
}),
new HttpTransport({
port: HTTP_PORT,
host: '::',
// Opt-in Server-Sent Events for `subscribe` over plain HTTP:
// GET /capability/subscribe/<name> (text/event-stream)
// Intended for clients that can't hold a WebSocket open (curl,
// AI agents, serverless / edge functions). Browser apps should
// still prefer the WebSocket transport, which multiplexes many
// topics on one connection. Off by default in HttpTransport.
sse: true,
cors: true,
}),
],
});
runtime.expose({
call: { '/add_two_ints': 'example_interfaces/srv/AddTwoInts' },
publish: { '/web_demo_chatter': 'std_msgs/msg/String' },
action: { '/fibonacci': 'example_interfaces/action/Fibonacci' },
subscribe: {
// Shared talker/listener topic: panels 2 (WebSocket), 3 (round-trip),
// and 6 (SSE) all use it — so a browser publish is visible across
// every subscriber at once.
'/web_demo_chatter': 'std_msgs/msg/String',
// Pairs with the stock publisher example so developers can feed the
// demo from their own node:
// node ../../../../example/topics/publisher/publisher-example.mjs
// then subscribe to `/topic` from the browser / curl / EventSource.
'/topic': 'std_msgs/msg/String',
},
});
await runtime.start();
const caps = runtime.registry.list();
const total =
Object.keys(caps.call || {}).length +
Object.keys(caps.publish || {}).length +
Object.keys(caps.subscribe || {}).length +
Object.keys(caps.action || {}).length;
console.log('rclnodejs/web API playground running (JavaScript)');
console.log(
` WebSocket : ws://${displayHost('::')}:${runtime.transports[0].port}/capability`
);
console.log(
` HTTP : http://${displayHost('::')}:${runtime.transports[1].port}/capability (call / publish / action, curl-able)`
);
console.log(
` HTTP SSE : http://${displayHost('::')}:${runtime.transports[1].port}/capability/subscribe/<name> (subscribe via text/event-stream)`
);
console.log();
console.log(`Exposed capabilities (${total}):`);
console.log(formatCapabilities(caps));
console.log();
console.log(
'Static page: run `node static.mjs` in another shell, then open http://localhost:8080/'
);
// ---- Graceful shutdown ----------------------------------------------
const stop = async () => {
if (stopping) return;
stopping = true;
console.log('\nstopping…');
await runtime.stop();
rclnodejs.shutdown();
process.exit(0);
};
process.once('SIGINT', stop);
process.once('SIGTERM', stop);