-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathRos.ts
More file actions
790 lines (735 loc) · 21.3 KB
/
Copy pathRos.ts
File metadata and controls
790 lines (735 loc) · 21.3 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/**
* @fileOverview
* @author Brandon Alexander - baalexander@gmail.com
*/
import type {
RosbridgeMessage,
RosbridgeSetStatusLevelMessage,
} from "../types/protocol.js";
import {
isRosbridgeActionFeedbackMessage,
isRosbridgeActionResultMessage,
isRosbridgeCallServiceMessage,
isRosbridgeCancelActionGoalMessage,
isRosbridgePublishMessage,
isRosbridgeSendActionGoalMessage,
isRosbridgeServiceResponseMessage,
isRosbridgeStatusMessage,
} from "../types/protocol.js";
import Topic from "./Topic.js";
import Service from "./Service.js";
import Param from "./Param.js";
import TFClient from "../tf/TFClient";
import ActionClient from "../actionlib/ActionClient.js";
import SimpleActionServer from "../actionlib/SimpleActionServer.js";
import { EventEmitter } from "eventemitter3";
import type { rosapi } from "../types/rosapi.ts";
import type {
ITransport,
ITransportFactory,
TransportEvent,
} from "./transport/Transport.js";
import { WebSocketTransportFactory } from "./transport/WebSocketTransportFactory.ts";
export interface TypeDefDict {
[key: string]: string | string[] | TypeDefDict | TypeDefDict[];
}
/**
* Manages connection to the rosbridge server and all interactions with ROS.
*
* Emits the following events:
* * 'open' - Connected to the rosbridge server.
* * 'close' - Disconnected to the rosbridge server.
* * 'error' - There was an error with ROS.
* * <topicName> - A message came from rosbridge with the given topic name.
* * <serviceID> - A service response came from rosbridge with the given ID.
*/
export default class Ros extends EventEmitter<
{
open: [TransportEvent];
close: [TransportEvent];
error: [TransportEvent];
// Any dynamically-named event should correspond to a rosbridge protocol message
} & Record<string, [RosbridgeMessage]>
> {
// private write, public read via getter method
#isConnected: boolean;
private transport?: ITransport;
private transportFactory: ITransportFactory;
constructor({
url,
transportFactory = WebSocketTransportFactory,
}: {
/**
* The rosbridge server URL. Can be specified later with `connect`.
* If specified, then will immediately try to connect to the server.
*/
url?: string;
/**
* The factory to use to create a transport.
* Defaults to a WebSocket transport factory.
*/
transportFactory?: ITransportFactory;
} = {}) {
super();
this.#isConnected = false;
this.transportFactory = transportFactory;
if (url) {
this.connect(url).catch(console.error);
}
}
public isConnected(): boolean {
return this.#isConnected;
}
public async connect(url: string): Promise<void> {
if (this.transport && !this.transport.isClosed()) {
return; // Already connected
}
const transport = await this.transportFactory(url);
this.transport = transport;
transport.on("open", (event: TransportEvent) => {
this.#isConnected = true;
this.emit("open", event);
});
transport.on("close", (event: TransportEvent) => {
this.#isConnected = false;
this.emit("close", event);
});
transport.on("error", (event: TransportEvent) => {
this.emit("error", event);
});
transport.on("message", (message: RosbridgeMessage) => {
this.handleMessage(message);
});
}
public close() {
this.transport?.close();
}
private handleMessage(message: RosbridgeMessage) {
if (isRosbridgePublishMessage(message)) {
this.emit(message.topic, message);
} else if (isRosbridgeServiceResponseMessage(message)) {
if (message.id) {
this.emit(message.id, message);
} else {
console.error("Received service response without ID");
}
} else if (isRosbridgeCallServiceMessage(message)) {
this.emit(message.service, message);
} else if (isRosbridgeSendActionGoalMessage(message)) {
this.emit(message.action, message);
} else if (isRosbridgeCancelActionGoalMessage(message)) {
this.emit(message.id, message);
} else if (isRosbridgeActionFeedbackMessage(message)) {
this.emit(message.id, message);
} else if (isRosbridgeActionResultMessage(message)) {
this.emit(message.id, message);
} else if (isRosbridgeStatusMessage(message)) {
if (message.id) {
this.emit(`status:${message.id}`, message);
} else {
this.emit("status", message);
}
}
}
/**
* Send an authorization request to the server.
*
* @param mac - MAC (hash) string given by the trusted source.
* @param client - IP of the client.
* @param dest - IP of the destination.
* @param rand - Random string given by the trusted source.
* @param t - Time of the authorization request.
* @param level - User level as a string given by the client.
* @param end - End time of the client's session.
*/
public authenticate(
mac: string,
client: string,
dest: string,
rand: string,
t: object,
level: string,
end: object,
) {
// create the request
const auth = {
op: "auth",
mac: mac,
client: client,
dest: dest,
rand: rand,
t: t,
level: level,
end: end,
};
// send the request
this.callOnConnection(auth);
}
/**
* Sends the message to the transport.
* If not connected, queues the message to send once reconnected.
*/
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- to broaden argument type to any RosbridgeMessage variant
public callOnConnection<T extends RosbridgeMessage = RosbridgeMessage>(
message: T,
) {
if (this.isConnected()) {
this.transport?.send(message);
} else {
this.once("open", () => {
this.transport?.send(message);
});
}
}
/**
* Send a set_level request to the server.
*
* @param level - Status level (none, error, warning, info).
* @param [id] - Operation ID to change status level on.
*/
public setStatusLevel(level: string, id?: string) {
const levelMsg: RosbridgeSetStatusLevelMessage = {
op: "set_level",
level,
id,
};
this.callOnConnection(levelMsg);
}
/**
* Retrieve a list of action servers in ROS as an array of string.
*
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getActionServers(
callback: (actionservers: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const getActionServers = new Service<
rosapi.GetActionServersRequest,
rosapi.GetActionServersResponse
>({
ros: this,
name: "rosapi/action_servers",
serviceType: "rosapi/GetActionServers",
});
const request = {};
getActionServers.callService(
request,
function (result) {
callback(result.action_servers);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of topics in ROS as an array.
*
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getTopics(
callback: (result: rosapi.TopicsResponse) => void,
failedCallback: (error: string) => void = console.error,
) {
const topicsClient = new Service<
rosapi.TopicsRequest,
rosapi.TopicsResponse
>({
ros: this,
name: "rosapi/topics",
serviceType: "rosapi/Topics",
});
const request = {};
topicsClient.callService(
request,
function (result) {
callback(result);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of topics in ROS as an array of a specific type.
*
* @param topicType - The topic type to find.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getTopicsForType(
topicType: string,
callback: (topics: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const topicsForTypeClient = new Service<
rosapi.TopicsForTypeRequest,
rosapi.TopicsForTypeResponse
>({
ros: this,
name: "rosapi/topics_for_type",
serviceType: "rosapi/TopicsForType",
});
const request = {
type: topicType,
};
topicsForTypeClient.callService(
request,
function (result) {
callback(result.topics);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of active service names in ROS.
*
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getServices(
callback: (services: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const servicesClient = new Service<
rosapi.ServicesRequest,
rosapi.ServicesResponse
>({
ros: this,
name: "rosapi/services",
serviceType: "rosapi/Services",
});
const request = {};
servicesClient.callService(
request,
function (result) {
callback(result.services);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of services in ROS as an array as specific type.
*
* @param serviceType - The service type to find.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getServicesForType(
serviceType: string,
callback: (services: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const servicesForTypeClient = new Service<
rosapi.ServicesForTypeRequest,
rosapi.ServicesForTypeResponse
>({
ros: this,
name: "rosapi/services_for_type",
serviceType: "rosapi/ServicesForType",
});
const request = {
type: serviceType,
};
servicesForTypeClient.callService(
request,
function (result) {
callback(result.services);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve the details of a ROS service request.
*
* @param type - The type of the service.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getServiceRequestDetails(
type: string,
callback: (result: rosapi.ServiceRequestDetailsResponse) => void,
failedCallback: (error: string) => void = console.error,
) {
const serviceTypeClient = new Service<
rosapi.ServiceRequestDetailsRequest,
rosapi.ServiceRequestDetailsResponse
>({
ros: this,
name: "rosapi/service_request_details",
serviceType: "rosapi/ServiceRequestDetails",
});
const request = {
type: type,
};
serviceTypeClient.callService(
request,
function (result) {
callback(result);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve the details of a ROS service response.
*
* @param type - The type of the service.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getServiceResponseDetails(
type: string,
callback: (result: rosapi.ServiceResponseDetailsResponse) => void,
failedCallback: (error: string) => void = console.error,
) {
const serviceTypeClient = new Service<
rosapi.ServiceResponseDetailsRequest,
rosapi.ServiceResponseDetailsResponse
>({
ros: this,
name: "rosapi/service_response_details",
serviceType: "rosapi/ServiceResponseDetails",
});
const request = {
type: type,
};
serviceTypeClient.callService(
request,
function (result) {
callback(result);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of active node names in ROS.
*
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getNodes(
callback: (result: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const nodesClient = new Service<rosapi.NodesRequest, rosapi.NodesResponse>({
ros: this,
name: "rosapi/nodes",
serviceType: "rosapi/Nodes",
});
const request = {};
nodesClient.callService(
request,
function (result) {
callback(result.nodes);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve a list of subscribed topics, publishing topics and services of a specific node.
*
* @param node - Name of the node.
*/
public getNodeDetails(
node: string,
callback: (result: rosapi.NodeDetailsResponse) => void,
failedCallback: (error: string) => void = console.error,
) {
const nodesClient = new Service<
rosapi.NodeDetailsRequest,
rosapi.NodeDetailsResponse
>({
ros: this,
name: "rosapi/node_details",
serviceType: "rosapi/NodeDetails",
});
nodesClient.callService({ node }, callback, failedCallback);
}
/**
* Retrieve a list of parameter names from the ROS Parameter Server.
*
* @param callback - Function with the following params:
* @param failedCallback - The callback function when the service call failed with params:
*/
public getParams(
callback: (names: string[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const paramsClient = new Service<
rosapi.GetParamNamesRequest,
rosapi.GetParamNamesResponse
>({
ros: this,
name: "rosapi/get_param_names",
serviceType: "rosapi/GetParamNames",
});
const request = {};
paramsClient.callService(
request,
function (result) {
callback(result.names);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve the type of a ROS topic.
*
* @param topic - Name of the topic.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getTopicType(
topic: string,
callback: (type: string) => void,
failedCallback: (error: string) => void = console.error,
) {
const topicTypeClient = new Service<
rosapi.TopicTypeRequest,
rosapi.TopicTypeResponse
>({
ros: this,
name: "rosapi/topic_type",
serviceType: "rosapi/TopicType",
});
const request = {
topic: topic,
};
topicTypeClient.callService(
request,
function (result) {
callback(result.type);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve the type of a ROS service.
*
* @param service - Name of the service.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getServiceType(
service: string,
callback: (type: string) => void,
failedCallback: (error: string) => void = console.error,
) {
const serviceTypeClient = new Service<
rosapi.ServiceTypeRequest,
rosapi.ServiceTypeResponse
>({
ros: this,
name: "rosapi/service_type",
serviceType: "rosapi/ServiceType",
});
const request = {
service: service,
};
serviceTypeClient.callService(
request,
function (result) {
callback(result.type);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Retrieve the details of a ROS message.
*
* @param message - The name of the message type.
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getMessageDetails(
message: string,
callback: (typedefs: rosapi.TypeDef[]) => void,
failedCallback: (error: string) => void = console.error,
) {
const messageDetailClient = new Service<
rosapi.MessageDetailsRequest,
rosapi.MessageDetailsResponse
>({
ros: this,
name: "rosapi/message_details",
serviceType: "rosapi/MessageDetails",
});
const request = {
type: message,
};
messageDetailClient.callService(
request,
function (result) {
callback(result.typedefs);
},
function (message) {
failedCallback(message);
},
);
}
/**
* Decode a typedef array into a dictionary like `rosmsg show foo/bar`.
*
* @param defs - Array of type_def dictionary.
*/
public decodeTypeDefs(defs: rosapi.TypeDef[]) {
const decodeTypeDefsRec = (
theType: rosapi.TypeDef,
hints: rosapi.TypeDef[],
) => {
// calls itself recursively to resolve type definition using hints.
const typeDefDict: TypeDefDict = {};
for (let i = 0; i < theType.fieldnames.length; i++) {
const arrayLen = theType.fieldarraylen[i];
const fieldName = theType.fieldnames[i];
const fieldType = theType.fieldtypes[i];
if (fieldName === undefined || fieldType === undefined) {
throw new Error(
"Received mismatched type definition vector lengths!",
);
}
if (!fieldType.includes("/")) {
// check the fieldType includes '/' or not
if (arrayLen === -1) {
typeDefDict[fieldName] = fieldType;
} else {
typeDefDict[fieldName] = [fieldType];
}
} else {
// lookup the name
let sub: rosapi.TypeDef | undefined = undefined;
for (const hint of hints) {
if (hint.type === fieldType) {
sub = hint;
break;
}
}
if (sub) {
const subResult = decodeTypeDefsRec(sub, hints);
if (arrayLen === -1) {
typeDefDict[fieldName] = subResult; // add this decoding result to dictionary
} else {
typeDefDict[fieldName] = [subResult];
}
} else {
this.emit("error", `Cannot find ${fieldType} in decodeTypeDefs`);
}
}
}
return typeDefDict;
};
if (defs[0]) {
return decodeTypeDefsRec(defs[0], defs);
} else {
return {};
}
}
/**
* @callback getTopicsAndRawTypesCallback
* @param {Object} result - The result object with the following params:
* @param {string[]} result.topics - Array of topic names.
* @param {string[]} result.types - Array of message type names.
* @param {string[]} result.typedefs_full_text - Array of full definitions of message types, similar to `gendeps --cat`.
*/
/**
* @callback getTopicsAndRawTypesFailedCallback
* @param {string} error - The error message reported by ROS.
*/
/**
* Retrieve a list of topics and their associated type definitions.
*
* @param callback - Function with the following params:
* @param [failedCallback] - The callback function when the service call failed with params:
*/
public getTopicsAndRawTypes(
callback: (result: rosapi.TopicsAndRawTypesResponse) => void,
failedCallback: (error: string) => void = console.error,
) {
const topicsAndRawTypesClient = new Service<
rosapi.TopicsAndRawTypesRequest,
rosapi.TopicsAndRawTypesResponse
>({
ros: this,
name: "rosapi/topics_and_raw_types",
serviceType: "rosapi/TopicsAndRawTypes",
});
const request = {};
topicsAndRawTypesClient.callService(
request,
function (result) {
callback(result);
},
function (message) {
failedCallback(message);
},
);
}
public Topic<T>(
options: Omit<ConstructorParameters<typeof Topic<T>>[0], "ros">,
) {
return new Topic<T>({ ros: this, ...options });
}
public Param<T>(
options: Omit<ConstructorParameters<typeof Param<T>>[0], "ros">,
) {
return new Param<T>({ ros: this, ...options });
}
public Service<TRequest, TResponse>(
options: Omit<
ConstructorParameters<typeof Service<TRequest, TResponse>>[0],
"ros"
>,
) {
return new Service<TRequest, TResponse>({ ros: this, ...options });
}
public TFClient(
options: Omit<ConstructorParameters<typeof TFClient>[0], "ros">,
) {
return new TFClient({ ros: this, ...options });
}
public ActionClient<TGoal, TFeedback, TResult>(
options: Omit<
ConstructorParameters<typeof ActionClient<TGoal, TFeedback, TResult>>[0],
"ros"
>,
) {
return new ActionClient<TGoal, TFeedback, TResult>({
ros: this,
...options,
});
}
public SimpleActionServer<TGoal, TFeedback, TResult>(
options: Omit<
ConstructorParameters<
typeof SimpleActionServer<TGoal, TFeedback, TResult>
>[0],
"ros"
>,
) {
return new SimpleActionServer<TGoal, TFeedback, TResult>({
ros: this,
...options,
});
}
}