-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathService.ts
More file actions
293 lines (271 loc) · 9 KB
/
Service.ts
File metadata and controls
293 lines (271 loc) · 9 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* @fileOverview
* @author Brandon Alexander - baalexander@gmail.com
*/
import { EventEmitter } from "eventemitter3";
import type { RosbridgeMessage } from "../types/protocol.ts";
import {
isRosbridgeCallServiceMessage,
isRosbridgeServiceResponseMessage,
} from "../types/protocol.ts";
import type Ros from "./Ros.ts";
import { v4 as uuidv4 } from "uuid";
/**
* A ROS service client.
*/
export default class Service<
TRequest = unknown,
TResponse = unknown,
> extends EventEmitter {
/**
* Stores a reference to the most recent service callback advertised so it can be removed from the EventEmitter during un-advertisement
*/
#serviceCallback: ((rosbridgeRequest: RosbridgeMessage) => void) | null =
null;
isAdvertised = false;
/**
* Queue for serializing advertise/unadvertise operations to prevent race conditions
*/
#operationQueue = Promise.resolve();
/**
* Track if an unadvertise operation is pending to prevent double operations
*/
#pendingUnadvertise = false;
ros: Ros;
name: string;
serviceType: string;
/**
* @param options
* @param options.ros - The ROSLIB.Ros connection handle.
* @param options.name - The service name, like '/add_two_ints'.
* @param options.serviceType - The service type, like 'rospy_tutorials/AddTwoInts'.
*/
constructor({
ros,
name,
serviceType,
}: {
ros: Ros;
name: string;
serviceType: string;
}) {
super();
this.ros = ros;
this.name = name;
this.serviceType = serviceType;
}
/**
* Wrapper of callServiceAsync for synchronous use. Returns the service response in the
* callback.
* @see callService
*
* @param request - The service request to send.
* @param [callback] - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
* @param [timeout] - Optional timeout, in seconds, for the service call. A non-positive value means no timeout.
* If not provided, the rosbridge server will use its default value.
*/
callService(
request: TRequest,
callback?: (response: TResponse) => void,
failedCallback: (error: string) => void = console.error,
timeout?: number,
): void {
this.callServiceAsync(request, timeout).then(callback, failedCallback);
}
/**
* Call the service. Returns the service response in the form of a Promise.
* Returns a rejected promise if the service is currently advertised.
* @param request - The service request to send.
* @param [timeout] - Optional timeout, in seconds, for the service call. A non-positive value means no timeout.
* If not provided, the rosbridge server will use its default value.
*/
callServiceAsync(request: TRequest, timeout?: number): Promise<TResponse> {
if (this.isAdvertised) {
return Promise.reject(new Error("Service is currently advertised"));
}
return new Promise<TResponse>((resolve, reject) => {
const serviceCallId = `call_service:${this.name}:${uuidv4()}`;
this.ros.once(serviceCallId, (message) => {
if (!isRosbridgeServiceResponseMessage<TResponse>(message)) {
reject(new Error("Received an invalid service response message"));
return;
}
if (message.result) {
resolve(message.values);
} else {
reject(new Error(message.values ?? ""));
}
});
this.ros.callOnConnection({
op: "call_service",
id: serviceCallId,
service: this.name,
args: request,
timeout: timeout,
});
});
}
/**
* Advertise the service. This turns the Service object from a client
* into a server. The callback will be called with every request
* that's made on this service.
*
* @param callback This works similarly to the callback for a C++ service in that you should take care not to overwrite the response object.
* Instead, only modify the values within.
*/
async advertise(
callback: (request: TRequest, response: Partial<TResponse>) => boolean,
): Promise<void> {
// Queue this operation to prevent race conditions
this.#operationQueue = this.#operationQueue
.then(() => {
// If already advertised, unadvertise first
if (this.isAdvertised) {
this.#doUnadvertise();
}
// Store the new callback for removal during un-advertisement
this.#serviceCallback = (rosbridgeRequest) => {
if (!isRosbridgeCallServiceMessage<TRequest>(rosbridgeRequest)) {
throw new Error(
`Invalid message received on service channel: ${JSON.stringify(rosbridgeRequest)}`,
);
}
// @ts-expect-error -- TypeScript doesn't have a way to handle the out-parameter model used here.
const response: TResponse = {};
let success: boolean;
try {
success = callback(rosbridgeRequest.args, response);
} catch {
success = false;
}
if (success) {
this.ros.callOnConnection({
op: "service_response",
service: this.name,
values: response,
result: success,
id: rosbridgeRequest.id,
});
} else {
this.ros.callOnConnection({
op: "service_response",
service: this.name,
result: success,
id: rosbridgeRequest.id,
});
}
};
this.ros.on(this.name, this.#serviceCallback);
this.ros.callOnConnection({
op: "advertise_service",
type: this.serviceType,
service: this.name,
});
this.isAdvertised = true;
})
.catch((err: unknown) => {
this.emit("error", err);
throw err;
});
return this.#operationQueue;
}
/**
* Internal method to perform unadvertisement without queueing
*/
#doUnadvertise() {
if (!this.isAdvertised || this.#pendingUnadvertise) {
return;
}
this.#pendingUnadvertise = true;
try {
/*
* Mark as not advertised first to prevent new service calls
* This ensures callService() will not be blocked while we're unadvertising
*/
this.isAdvertised = false;
// Remove the registered callback to stop processing new requests
if (this.#serviceCallback) {
this.ros.off(this.name, this.#serviceCallback);
this.#serviceCallback = null;
}
/*
* Send the unadvertise message to the server
* Note: This is fire-and-forget, but the operation queue ensures
* no new advertise can start until this completes
*/
this.ros.callOnConnection({
op: "unadvertise_service",
service: this.name,
});
} finally {
this.#pendingUnadvertise = false;
}
}
async unadvertise(): Promise<void> {
// Queue this operation to prevent race conditions
this.#operationQueue = this.#operationQueue
.then(() => {
this.#doUnadvertise();
})
.catch((err: unknown) => {
this.emit("error", err);
throw err;
});
return this.#operationQueue;
}
/**
* An alternate form of Service advertisement that supports a modern Promise-based interface for use with async/await.
* @param callback An asynchronous callback processing the request and returning a response.
*/
async advertiseAsync(
callback: (request: TRequest) => Promise<TResponse>,
): Promise<void> {
// Queue this operation to prevent race conditions
this.#operationQueue = this.#operationQueue
.then(() => {
// If already advertised, unadvertise first
if (this.isAdvertised) {
this.#doUnadvertise();
}
this.#serviceCallback = (rosbridgeRequest) => {
if (!isRosbridgeCallServiceMessage<TRequest>(rosbridgeRequest)) {
throw new Error(
`Invalid message received on service channel: ${JSON.stringify(rosbridgeRequest)}`,
);
}
(async () => {
try {
this.ros.callOnConnection({
op: "service_response",
service: this.name,
result: true,
values: await callback(rosbridgeRequest.args),
id: rosbridgeRequest.id,
});
} catch (err) {
this.ros.callOnConnection({
op: "service_response",
service: this.name,
result: false,
values: String(err),
id: rosbridgeRequest.id,
});
}
})().catch(console.error);
};
this.ros.on(this.name, this.#serviceCallback);
this.ros.callOnConnection({
op: "advertise_service",
type: this.serviceType,
service: this.name,
});
this.isAdvertised = true;
})
.catch((err: unknown) => {
this.emit("error", err);
throw err;
});
return this.#operationQueue;
}
}