• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RobotWebTools / rclnodejs / 14330121487

08 Apr 2025 09:30AM UTC coverage: 85.045% (-0.03%) from 85.075%
14330121487

push

github

minggangw
feat: add descriptor namespaces (#1095)

This will add a new namespace called `descriptor` for each ROS package interface generated by `generate-ros-messages`. The new namespace is found inside the msg|srv|action namespace for each package. For example:

```typescript
namespace builtin_interfaces {
    namespace msg {
      export interface Duration {
        sec: number;
        nanosec: number;
      }
      export interface DurationConstructor {
        new(other?: Duration): Duration;
      }
      export interface Time {
        sec: number;
        nanosec: number;
      }
      export interface TimeConstructor {
        new(other?: Time): Time;
      }
      namespace descriptor {
        export interface Duration {
          sec: 'int32';
          nanosec: 'uint32';
        }
        export interface Time {
          sec: 'int32';
          nanosec: 'uint32';
        }
      }
    }
  }
``` 
The descriptor interfaces always have the format `{field: "<interface_type>"}`. For example:

```typescript
  namespace geometry_msgs {
    namespace msg {
      namespace descriptor {
        export interface PointStamped {
          header: 'std_msgs/msg/Header';
          point: 'geometry_msgs/msg/Point';
        }
      }
    } 
  }  
```

Here is the discussion: [discussions/1091](https://github.com/RobotWebTools/rclnodejs/discussions/1091)

706 of 920 branches covered (76.74%)

Branch coverage included in aggregate %.

1728 of 1942 relevant lines covered (88.98%)

1005.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.58
/lib/node.js
1
// Copyright (c) 2017 Intel Corporation. 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
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
'use strict';
16

17
const rclnodejs = require('bindings')('rclnodejs');
78✔
18

19
const ActionInterfaces = require('./action/interfaces.js');
78✔
20
const Client = require('./client.js');
78✔
21
const Clock = require('./clock.js');
78✔
22
const Context = require('./context.js');
78✔
23
const debug = require('debug')('rclnodejs:node');
78✔
24
const GuardCondition = require('./guard_condition.js');
78✔
25
const loader = require('./interface_loader.js');
78✔
26
const Logging = require('./logging.js');
78✔
27
const NodeOptions = require('./node_options.js');
78✔
28
const {
29
  ParameterType,
30
  Parameter,
31
  ParameterDescriptor,
32
} = require('./parameter.js');
78✔
33
const ParameterService = require('./parameter_service.js');
78✔
34
const Publisher = require('./publisher.js');
78✔
35
const QoS = require('./qos.js');
78✔
36
const Rates = require('./rate.js');
78✔
37
const Service = require('./service.js');
78✔
38
const Subscription = require('./subscription.js');
78✔
39
const TimeSource = require('./time_source.js');
78✔
40
const Timer = require('./timer.js');
78✔
41
const Entity = require('./entity.js');
78✔
42

43
// Parameter event publisher constants
44
const PARAMETER_EVENT_MSG_TYPE = 'rcl_interfaces/msg/ParameterEvent';
78✔
45
const PARAMETER_EVENT_TOPIC = 'parameter_events';
78✔
46

47
/**
48
 * @class - Class representing a Node in ROS
49
 */
50

51
class Node extends rclnodejs.ShadowNode {
52
  /**
53
   * Create a ROS2Node.
54
   * model using the {@link https://github.com/ros2/rcl/tree/master/rcl_lifecycle|ros2 client library (rcl) lifecyle api}.
55
   * @param {string} nodeName - The name used to register in ROS.
56
   * @param {string} [namespace=''] - The namespace used in ROS.
57
   * @param {Context} [context=Context.defaultContext()] - The context to create the node in.
58
   * @param {NodeOptions} [options=NodeOptions.defaultOptions] - The options to configure the new node behavior.
59
   * @throws {Error} If the given context is not registered.
60
   */
61
  constructor(
62
    nodeName,
63
    namespace = '',
93✔
64
    context = Context.defaultContext(),
198✔
65
    options = NodeOptions.defaultOptions
204✔
66
  ) {
67
    super();
1,752✔
68

69
    if (typeof nodeName !== 'string' || typeof namespace !== 'string') {
1,752✔
70
      throw new TypeError('Invalid argument.');
66✔
71
    }
72

73
    this._init(nodeName, namespace, options, context);
1,686✔
74
    debug(
1,665✔
75
      'Finish initializing node, name = %s and namespace = %s.',
76
      nodeName,
77
      namespace
78
    );
79
  }
80

81
  _init(name, namespace, options, context) {
82
    this.handle = rclnodejs.createNode(name, namespace, context.handle);
1,686✔
83
    Object.defineProperty(this, 'handle', {
1,665✔
84
      configurable: false,
85
      writable: false,
86
    }); // make read-only
87

88
    this._context = context;
1,665✔
89
    this.context.onNodeCreated(this);
1,665✔
90

91
    this._publishers = [];
1,665✔
92
    this._subscriptions = [];
1,665✔
93
    this._clients = [];
1,665✔
94
    this._services = [];
1,665✔
95
    this._timers = [];
1,665✔
96
    this._guards = [];
1,665✔
97
    this._actionClients = [];
1,665✔
98
    this._actionServers = [];
1,665✔
99
    this._rateTimerServer = null;
1,665✔
100
    this._parameterDescriptors = new Map();
1,665✔
101
    this._parameters = new Map();
1,665✔
102
    this._parameterService = null;
1,665✔
103
    this._parameterEventPublisher = null;
1,665✔
104
    this._setParametersCallbacks = [];
1,665✔
105
    this._logger = new Logging(rclnodejs.getNodeLoggerName(this.handle));
1,665✔
106
    this._spinning = false;
1,665✔
107

108
    this._parameterEventPublisher = this.createPublisher(
1,665✔
109
      PARAMETER_EVENT_MSG_TYPE,
110
      PARAMETER_EVENT_TOPIC
111
    );
112

113
    // initialize _parameterOverrides from parameters defined on the commandline
114
    this._parameterOverrides = this._getNativeParameterOverrides();
1,665✔
115

116
    // override cli parameterOverrides with those specified in options
117
    if (options.parameterOverrides.length > 0) {
1,665✔
118
      for (const parameter of options.parameterOverrides) {
24✔
119
        if ((!parameter) instanceof Parameter) {
24!
120
          throw new TypeError(
×
121
            'Parameter-override must be an instance of Parameter.'
122
          );
123
        }
124
        this._parameterOverrides.set(parameter.name, parameter);
24✔
125
      }
126
    }
127

128
    // initialize _parameters from parameterOverrides
129
    if (options.automaticallyDeclareParametersFromOverrides) {
1,665✔
130
      for (const parameter of this._parameterOverrides.values()) {
15✔
131
        parameter.validate();
15✔
132
        const descriptor = ParameterDescriptor.fromParameter(parameter);
15✔
133
        this._parameters.set(parameter.name, parameter);
15✔
134
        this._parameterDescriptors.set(parameter.name, descriptor);
15✔
135
      }
136
    }
137

138
    // Clock that has support for ROS time.
139
    // Note: parameter overrides and parameter event publisher need to be ready at this point
140
    // to be able to declare 'use_sim_time' if it was not declared yet.
141
    this._clock = new Clock.ROSClock();
1,665✔
142
    this._timeSource = new TimeSource(this);
1,665✔
143
    this._timeSource.attachClock(this._clock);
1,665✔
144

145
    if (options.startParameterServices) {
1,665✔
146
      this._parameterService = new ParameterService(this);
1,647✔
147
      this._parameterService.start();
1,647✔
148
    }
149
  }
150

151
  execute(handles) {
152
    let timersReady = this._timers.filter((timer) =>
11,336✔
153
      handles.includes(timer.handle)
9,332✔
154
    );
155
    let guardsReady = this._guards.filter((guard) =>
11,336✔
156
      handles.includes(guard.handle)
9✔
157
    );
158
    let subscriptionsReady = this._subscriptions.filter((subscription) =>
11,336✔
159
      handles.includes(subscription.handle)
1,429✔
160
    );
161
    let clientsReady = this._clients.filter((client) =>
11,336✔
162
      handles.includes(client.handle)
302✔
163
    );
164
    let servicesReady = this._services.filter((service) =>
11,336✔
165
      handles.includes(service.handle)
14,376✔
166
    );
167
    let actionClientsReady = this._actionClients.filter((actionClient) =>
11,336✔
168
      handles.includes(actionClient.handle)
473✔
169
    );
170
    let actionServersReady = this._actionServers.filter((actionServer) =>
11,336✔
171
      handles.includes(actionServer.handle)
473✔
172
    );
173

174
    timersReady.forEach((timer) => {
11,336✔
175
      if (timer.isReady()) {
9,302✔
176
        rclnodejs.callTimer(timer.handle);
9,193✔
177
        timer.callback();
9,193✔
178
      }
179
    });
180

181
    for (const subscription of subscriptionsReady) {
11,336✔
182
      if (subscription.isDestroyed()) continue;
1,314✔
183
      if (subscription.isRaw) {
1,284✔
184
        let rawMessage = rclnodejs.rclTakeRaw(subscription.handle);
3✔
185
        if (rawMessage) {
3!
186
          subscription.processResponse(rawMessage);
3✔
187
        }
188
        continue;
3✔
189
      }
190

191
      this._runWithMessageType(
1,281✔
192
        subscription.typeClass,
193
        (message, deserialize) => {
194
          let success = rclnodejs.rclTake(subscription.handle, message);
1,281✔
195
          if (success) {
1,281✔
196
            subscription.processResponse(deserialize());
1,062✔
197
          }
198
        }
199
      );
200
    }
201

202
    for (const guard of guardsReady) {
11,336✔
203
      if (guard.isDestroyed()) continue;
9!
204

205
      guard.callback();
9✔
206
    }
207

208
    for (const client of clientsReady) {
11,336✔
209
      if (client.isDestroyed()) continue;
150!
210
      this._runWithMessageType(
150✔
211
        client.typeClass.Response,
212
        (message, deserialize) => {
213
          let sequenceNumber = rclnodejs.rclTakeResponse(
150✔
214
            client.handle,
215
            message
216
          );
217
          if (sequenceNumber !== undefined) {
150✔
218
            client.processResponse(sequenceNumber, deserialize());
90✔
219
          }
220
        }
221
      );
222
    }
223

224
    for (const service of servicesReady) {
11,336✔
225
      if (service.isDestroyed()) continue;
180!
226
      this._runWithMessageType(
180✔
227
        service.typeClass.Request,
228
        (message, deserialize) => {
229
          let header = rclnodejs.rclTakeRequest(
180✔
230
            service.handle,
231
            this.handle,
232
            message
233
          );
234
          if (header) {
180✔
235
            service.processRequest(header, deserialize());
93✔
236
          }
237
        }
238
      );
239
    }
240

241
    for (const actionClient of actionClientsReady) {
11,336✔
242
      if (actionClient.isDestroyed()) continue;
222!
243

244
      const properties = actionClient.handle.properties;
222✔
245

246
      if (properties.isGoalResponseReady) {
222✔
247
        this._runWithMessageType(
102✔
248
          actionClient.typeClass.impl.SendGoalService.Response,
249
          (message, deserialize) => {
250
            let sequence = rclnodejs.actionTakeGoalResponse(
102✔
251
              actionClient.handle,
252
              message
253
            );
254
            if (sequence != undefined) {
102✔
255
              actionClient.processGoalResponse(sequence, deserialize());
90✔
256
            }
257
          }
258
        );
259
      }
260

261
      if (properties.isCancelResponseReady) {
222✔
262
        this._runWithMessageType(
18✔
263
          actionClient.typeClass.impl.CancelGoal.Response,
264
          (message, deserialize) => {
265
            let sequence = rclnodejs.actionTakeCancelResponse(
18✔
266
              actionClient.handle,
267
              message
268
            );
269
            if (sequence != undefined) {
18✔
270
              actionClient.processCancelResponse(sequence, deserialize());
12✔
271
            }
272
          }
273
        );
274
      }
275

276
      if (properties.isResultResponseReady) {
222✔
277
        this._runWithMessageType(
47✔
278
          actionClient.typeClass.impl.GetResultService.Response,
279
          (message, deserialize) => {
280
            let sequence = rclnodejs.actionTakeResultResponse(
47✔
281
              actionClient.handle,
282
              message
283
            );
284
            if (sequence != undefined) {
47✔
285
              actionClient.processResultResponse(sequence, deserialize());
45✔
286
            }
287
          }
288
        );
289
      }
290

291
      if (properties.isFeedbackReady) {
222✔
292
        this._runWithMessageType(
22✔
293
          actionClient.typeClass.impl.FeedbackMessage,
294
          (message, deserialize) => {
295
            let success = rclnodejs.actionTakeFeedback(
22✔
296
              actionClient.handle,
297
              message
298
            );
299
            if (success) {
22✔
300
              actionClient.processFeedbackMessage(deserialize());
15✔
301
            }
302
          }
303
        );
304
      }
305

306
      if (properties.isStatusReady) {
222✔
307
        this._runWithMessageType(
115✔
308
          actionClient.typeClass.impl.GoalStatusArray,
309
          (message, deserialize) => {
310
            let success = rclnodejs.actionTakeStatus(
115✔
311
              actionClient.handle,
312
              message
313
            );
314
            if (success) {
115✔
315
              actionClient.processStatusMessage(deserialize());
103✔
316
            }
317
          }
318
        );
319
      }
320
    }
321

322
    for (const actionServer of actionServersReady) {
11,336✔
323
      if (actionServer.isDestroyed()) continue;
280!
324

325
      const properties = actionServer.handle.properties;
280✔
326

327
      if (properties.isGoalRequestReady) {
280✔
328
        this._runWithMessageType(
92✔
329
          actionServer.typeClass.impl.SendGoalService.Request,
330
          (message, deserialize) => {
331
            const result = rclnodejs.actionTakeGoalRequest(
92✔
332
              actionServer.handle,
333
              message
334
            );
335
            if (result) {
92✔
336
              actionServer.processGoalRequest(result, deserialize());
90✔
337
            }
338
          }
339
        );
340
      }
341

342
      if (properties.isCancelRequestReady) {
280✔
343
        this._runWithMessageType(
21✔
344
          actionServer.typeClass.impl.CancelGoal.Request,
345
          (message, deserialize) => {
346
            const result = rclnodejs.actionTakeCancelRequest(
21✔
347
              actionServer.handle,
348
              message
349
            );
350
            if (result) {
21✔
351
              actionServer.processCancelRequest(result, deserialize());
12✔
352
            }
353
          }
354
        );
355
      }
356

357
      if (properties.isResultRequestReady) {
280✔
358
        this._runWithMessageType(
68✔
359
          actionServer.typeClass.impl.GetResultService.Request,
360
          (message, deserialize) => {
361
            const result = rclnodejs.actionTakeResultRequest(
68✔
362
              actionServer.handle,
363
              message
364
            );
365
            if (result) {
68✔
366
              actionServer.processResultRequest(result, deserialize());
45✔
367
            }
368
          }
369
        );
370
      }
371

372
      if (properties.isGoalExpired) {
280✔
373
        let GoalInfoArray = ActionInterfaces.GoalInfo.ArrayType;
16✔
374
        let message = new GoalInfoArray(actionServer._goalHandles.size);
16✔
375
        let count = rclnodejs.actionExpireGoals(
16✔
376
          actionServer.handle,
377
          actionServer._goalHandles.size,
378
          message._refArray.buffer
379
        );
380
        if (count > 0) {
16✔
381
          actionServer.processGoalExpired(message, count);
9✔
382
        }
383
        GoalInfoArray.freeArray(message);
16✔
384
      }
385
    }
386

387
    // At this point it is safe to clear the cache of any
388
    // destroyed entity references
389
    Entity._gcHandles();
11,336✔
390
  }
391

392
  /**
393
   * Determine if this node is spinning.
394
   * @returns {boolean} - true when spinning; otherwise returns false.
395
   */
396
  get spinning() {
397
    return this._spinning;
12,024✔
398
  }
399

400
  /**
401
   * Trigger the event loop to continuously check for and route.
402
   * incoming events.
403
   * @param {Node} node - The node to be spun up.
404
   * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0.
405
   * @throws {Error} If the node is already spinning.
406
   * @return {undefined}
407
   */
408
  spin(timeout = 10) {
45✔
409
    if (this.spinning) {
1,260!
410
      throw new Error('The node is already spinning.');
×
411
    }
412
    this.start(this.context.handle, timeout);
1,260✔
413
    this._spinning = true;
1,260✔
414
  }
415

416
  /**
417
   * Use spin().
418
   * @deprecated, since 0.18.0
419
   */
420
  startSpinning(timeout) {
421
    this.spin(timeout);
×
422
  }
423

424
  /**
425
   * Terminate spinning - no further events will be received.
426
   * @returns {undefined}
427
   */
428
  stop() {
429
    super.stop();
1,260✔
430
    this._spinning = false;
1,260✔
431
  }
432

433
  /**
434
   * Terminate spinning - no further events will be received.
435
   * @returns {undefined}
436
   * @deprecated since 0.18.0, Use stop().
437
   */
438
  stopSpinning() {
439
    super.stop();
×
440
    this._spinning = false;
×
441
  }
442

443
  /**
444
   * Spin the node and trigger the event loop to check for one incoming event. Thereafter the node
445
   * will not received additional events until running additional calls to spin() or spinOnce().
446
   * @param {Node} node - The node to be spun.
447
   * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0.
448
   * @throws {Error} If the node is already spinning.
449
   * @return {undefined}
450
   */
451
  spinOnce(timeout = 10) {
6✔
452
    if (this.spinning) {
9,027✔
453
      throw new Error('The node is already spinning.');
6✔
454
    }
455
    super.spinOnce(this.context.handle, timeout);
9,021✔
456
  }
457

458
  _removeEntityFromArray(entity, array) {
459
    let index = array.indexOf(entity);
324✔
460
    if (index > -1) {
324✔
461
      array.splice(index, 1);
318✔
462
    }
463
  }
464

465
  _destroyEntity(entity, array, syncHandles = true) {
330✔
466
    if (entity['isDestroyed'] && entity.isDestroyed()) return;
348✔
467

468
    this._removeEntityFromArray(entity, array);
324✔
469
    if (syncHandles) {
324✔
470
      this.syncHandles();
312✔
471
    }
472

473
    if (entity['_destroy']) {
324✔
474
      entity._destroy();
306✔
475
    } else {
476
      // guards and timers
477
      entity.handle.release();
18✔
478
    }
479
  }
480

481
  _validateOptions(options) {
482
    if (
14,292✔
483
      options !== undefined &&
14,430✔
484
      (options === null || typeof options !== 'object')
485
    ) {
486
      throw new TypeError('Invalid argument of options');
60✔
487
    }
488

489
    if (options === undefined) {
14,232✔
490
      return Node.getDefaultOptions();
14,193✔
491
    }
492

493
    if (options.enableTypedArray === undefined) {
39✔
494
      options = Object.assign(options, { enableTypedArray: true });
3✔
495
    }
496

497
    if (options.qos === undefined) {
39✔
498
      options = Object.assign(options, { qos: QoS.profileDefault });
12✔
499
    }
500

501
    if (options.isRaw === undefined) {
39✔
502
      options = Object.assign(options, { isRaw: false });
9✔
503
    }
504

505
    return options;
39✔
506
  }
507

508
  /**
509
   * Create a Timer.
510
   * @param {bigint} period - The number representing period in nanoseconds.
511
   * @param {function} callback - The callback to be called when timeout.
512
   * @param {Clock} [clock] - The clock which the timer gets time from.
513
   * @return {Timer} - An instance of Timer.
514
   */
515
  createTimer(period, callback, clock = null) {
165✔
516
    if (arguments.length === 3 && !(arguments[2] instanceof Clock)) {
165!
517
      clock = null;
×
518
    } else if (arguments.length === 4) {
165!
519
      clock = arguments[3];
×
520
    }
521

522
    if (typeof period !== 'bigint' || typeof callback !== 'function') {
165✔
523
      throw new TypeError('Invalid argument');
6✔
524
    }
525

526
    const timerClock = clock || this._clock;
159✔
527
    let timerHandle = rclnodejs.createTimer(
159✔
528
      timerClock.handle,
529
      this.context.handle,
530
      period
531
    );
532
    let timer = new Timer(timerHandle, period, callback);
159✔
533
    debug('Finish creating timer, period = %d.', period);
159✔
534
    this._timers.push(timer);
159✔
535
    this.syncHandles();
159✔
536

537
    return timer;
159✔
538
  }
539

540
  /**
541
   * Create a Rate.
542
   *
543
   * @param {number} hz - The frequency of the rate timer; default is 1 hz.
544
   * @returns {Promise<Rate>} - Promise resolving to new instance of Rate.
545
   */
546
  async createRate(hz = 1) {
12✔
547
    if (typeof hz !== 'number') {
27!
548
      throw new TypeError('Invalid argument');
×
549
    }
550

551
    const MAX_RATE_HZ_IN_MILLISECOND = 1000.0;
27✔
552
    if (hz <= 0.0 || hz > MAX_RATE_HZ_IN_MILLISECOND) {
27✔
553
      throw new RangeError(
6✔
554
        `Hz must be between 0.0 and ${MAX_RATE_HZ_IN_MILLISECOND}`
555
      );
556
    }
557

558
    // lazy initialize rateTimerServer
559
    if (!this._rateTimerServer) {
21✔
560
      this._rateTimerServer = new Rates.RateTimerServer(this);
15✔
561
      await this._rateTimerServer.init();
15✔
562
    }
563

564
    const period = Math.round(1000 / hz);
21✔
565
    const timer = this._rateTimerServer.createTimer(BigInt(period) * 1000000n);
21✔
566
    const rate = new Rates.Rate(hz, timer);
21✔
567

568
    return rate;
21✔
569
  }
570

571
  /**
572
   * Create a Publisher.
573
   * @param {function|string|object} typeClass - The ROS message class,
574
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
575
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
576
   * @param {string} topic - The name of the topic.
577
   * @param {object} options - The options argument used to parameterize the publisher.
578
   * @param {boolean} options.enableTypedArray - The topic will use TypedArray if necessary, default: true.
579
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the publisher, default: QoS.profileDefault.
580
   * @return {Publisher} - An instance of Publisher.
581
   */
582
  createPublisher(typeClass, topic, options) {
583
    return this._createPublisher(typeClass, topic, options, Publisher);
2,721✔
584
  }
585

586
  _createPublisher(typeClass, topic, options, publisherClass) {
587
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
2,730✔
588
      typeClass = loader.loadInterface(typeClass);
2,658✔
589
    }
590
    options = this._validateOptions(options);
2,709✔
591

592
    if (typeof typeClass !== 'function' || typeof topic !== 'string') {
2,709✔
593
      throw new TypeError('Invalid argument');
60✔
594
    }
595

596
    let publisher = publisherClass.createPublisher(
2,649✔
597
      this.handle,
598
      typeClass,
599
      topic,
600
      options
601
    );
602
    debug('Finish creating publisher, topic = %s.', topic);
2,619✔
603
    this._publishers.push(publisher);
2,619✔
604
    return publisher;
2,619✔
605
  }
606

607
  /**
608
   * This callback is called when a message is published
609
   * @callback SubscriptionCallback
610
   * @param {Object} message - The message published
611
   * @see [Node.createSubscription]{@link Node#createSubscription}
612
   * @see [Node.createPublisher]{@link Node#createPublisher}
613
   * @see {@link Publisher}
614
   * @see {@link Subscription}
615
   */
616

617
  /**
618
   * Create a Subscription with optional content-filtering.
619
   * @param {function|string|object} typeClass - The ROS message class,
620
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
621
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
622
   * @param {string} topic - The name of the topic.
623
   * @param {object} options - The options argument used to parameterize the subscription.
624
   * @param {boolean} options.enableTypedArray - The topic will use TypedArray if necessary, default: true.
625
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the subscription, default: QoS.profileDefault.
626
   * @param {boolean} options.isRaw - The topic is serialized when true, default: false.
627
   * @param {object} [options.contentFilter=undefined] - The content-filter, default: undefined.
628
   *  Confirm that your RMW supports content-filtered topics before use. 
629
   * @param {string} options.contentFilter.expression - Specifies the criteria to select the data samples of
630
   *  interest. It is similar to the WHERE part of an SQL clause.
631
   * @param {string[]} [options.contentFilter.parameters=undefined] - Array of strings that give values to
632
   *  the ‘parameters’ (i.e., "%n" tokens) in the filter_expression. The number of supplied parameters must
633
   *  fit with the requested values in the filter_expression (i.e., the number of %n tokens). default: undefined.
634
   * @param {SubscriptionCallback} callback - The callback to be call when receiving the topic subscribed. The topic will be an instance of null-terminated Buffer when options.isRaw is true.
635
   * @return {Subscription} - An instance of Subscription.
636
   * @throws {ERROR} - May throw an RMW error if content-filter is malformed. 
637
   * @see {@link SubscriptionCallback}
638
   * @see {@link https://www.omg.org/spec/DDS/1.4/PDF|Content-filter details at DDS 1.4 specification, Annex B}
639
   */
640
  createSubscription(typeClass, topic, options, callback) {
641
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
1,113✔
642
      typeClass = loader.loadInterface(typeClass);
1,086✔
643
    }
644

645
    if (typeof options === 'function') {
1,092✔
646
      callback = options;
999✔
647
      options = undefined;
999✔
648
    }
649
    options = this._validateOptions(options);
1,092✔
650

651
    if (
1,062✔
652
      typeof typeClass !== 'function' ||
3,144✔
653
      typeof topic !== 'string' ||
654
      typeof callback !== 'function'
655
    ) {
656
      throw new TypeError('Invalid argument');
30✔
657
    }
658

659
    let subscription = Subscription.createSubscription(
1,032✔
660
      this.handle,
661
      typeClass,
662
      topic,
663
      options,
664
      callback
665
    );
666
    debug('Finish creating subscription, topic = %s.', topic);
999✔
667
    this._subscriptions.push(subscription);
999✔
668
    this.syncHandles();
999✔
669

670
    return subscription;
999✔
671
  }
672

673
  /**
674
   * Create a Client.
675
   * @param {function|string|object} typeClass - The ROS message class,
676
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
677
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
678
   * @param {string} serviceName - The service name to request.
679
   * @param {object} options - The options argument used to parameterize the client.
680
   * @param {boolean} options.enableTypedArray - The response will use TypedArray if necessary, default: true.
681
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the client, default: QoS.profileDefault.
682
   * @return {Client} - An instance of Client.
683
   */
684
  createClient(typeClass, serviceName, options) {
685
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
243✔
686
      typeClass = loader.loadInterface(typeClass);
213✔
687
    }
688
    options = this._validateOptions(options);
222✔
689

690
    if (typeof typeClass !== 'function' || typeof serviceName !== 'string') {
222✔
691
      throw new TypeError('Invalid argument');
60✔
692
    }
693

694
    let client = Client.createClient(
162✔
695
      this.handle,
696
      serviceName,
697
      typeClass,
698
      options
699
    );
700
    debug('Finish creating client, service = %s.', serviceName);
132✔
701
    this._clients.push(client);
132✔
702
    this.syncHandles();
132✔
703

704
    return client;
132✔
705
  }
706

707
  /**
708
   * This callback is called when a request is sent to service
709
   * @callback RequestCallback
710
   * @param {Object} request - The request sent to the service
711
   * @param {Response} response - The response to client.
712
        Use [response.send()]{@link Response#send} to send response object to client
713
   * @return {undefined}
714
   * @see [Node.createService]{@link Node#createService}
715
   * @see [Client.sendRequest]{@link Client#sendRequest}
716
   * @see {@link Client}
717
   * @see {@link Service}
718
   * @see {@link Response#send}
719
   */
720

721
  /**
722
   * Create a Service.
723
   * @param {function|string|object} typeClass - The ROS message class,
724
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
725
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
726
   * @param {string} serviceName - The service name to offer.
727
   * @param {object} options - The options argument used to parameterize the service.
728
   * @param {boolean} options.enableTypedArray - The request will use TypedArray if necessary, default: true.
729
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the service, default: QoS.profileDefault.
730
   * @param {RequestCallback} callback - The callback to be called when receiving request.
731
   * @return {Service} - An instance of Service.
732
   * @see {@link RequestCallback}
733
   */
734
  createService(typeClass, serviceName, options, callback) {
735
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
10,086✔
736
      typeClass = loader.loadInterface(typeClass);
10,056✔
737
    }
738

739
    if (typeof options === 'function') {
10,065✔
740
      callback = options;
10,002✔
741
      options = undefined;
10,002✔
742
    }
743
    options = this._validateOptions(options);
10,065✔
744

745
    if (
10,035✔
746
      typeof typeClass !== 'function' ||
30,063✔
747
      typeof serviceName !== 'string' ||
748
      typeof callback !== 'function'
749
    ) {
750
      throw new TypeError('Invalid argument');
30✔
751
    }
752

753
    let service = Service.createService(
10,005✔
754
      this.handle,
755
      serviceName,
756
      typeClass,
757
      options,
758
      callback
759
    );
760
    debug('Finish creating service, service = %s.', serviceName);
9,975✔
761
    this._services.push(service);
9,975✔
762
    this.syncHandles();
9,975✔
763

764
    return service;
9,975✔
765
  }
766

767
  /**
768
   * Create a guard condition.
769
   * @param {Function} callback - The callback to be called when the guard condition is triggered.
770
   * @return {GuardCondition} - An instance of GuardCondition.
771
   */
772
  createGuardCondition(callback) {
773
    if (typeof callback !== 'function') {
9!
774
      throw new TypeError('Invalid argument');
×
775
    }
776

777
    let guard = GuardCondition.createGuardCondition(callback, this.context);
9✔
778
    debug('Finish creating guard condition');
9✔
779
    this._guards.push(guard);
9✔
780
    this.syncHandles();
9✔
781

782
    return guard;
9✔
783
  }
784

785
  /**
786
   * Destroy all resource allocated by this node, including
787
   * <code>Timer</code>s/<code>Publisher</code>s/<code>Subscription</code>s
788
   * /<code>Client</code>s/<code>Service</code>s
789
   * @return {undefined}
790
   */
791
  destroy() {
792
    if (this.spinning) {
1,731✔
793
      this.stop();
1,257✔
794
    }
795

796
    // Action servers/clients require manual destruction due to circular reference with goal handles.
797
    this._actionClients.forEach((actionClient) => actionClient.destroy());
1,731✔
798
    this._actionServers.forEach((actionServer) => actionServer.destroy());
1,731✔
799

800
    this.context.onNodeDestroyed(this);
1,731✔
801

802
    this.handle.release();
1,731✔
803
    this._clock = null;
1,731✔
804
    this._timers = [];
1,731✔
805
    this._publishers = [];
1,731✔
806
    this._subscriptions = [];
1,731✔
807
    this._clients = [];
1,731✔
808
    this._services = [];
1,731✔
809
    this._guards = [];
1,731✔
810
    this._actionClients = [];
1,731✔
811
    this._actionServers = [];
1,731✔
812

813
    if (this._rateTimerServer) {
1,731✔
814
      this._rateTimerServer.shutdown();
15✔
815
      this._rateTimerServer = null;
15✔
816
    }
817
  }
818

819
  /**
820
   * Destroy a Publisher.
821
   * @param {Publisher} publisher - The Publisher to be destroyed.
822
   * @return {undefined}
823
   */
824
  destroyPublisher(publisher) {
825
    if (!(publisher instanceof Publisher)) {
24✔
826
      throw new TypeError('Invalid argument');
6✔
827
    }
828
    this._destroyEntity(publisher, this._publishers, false);
18✔
829
  }
830

831
  /**
832
   * Destroy a Subscription.
833
   * @param {Subscription} subscription - The Subscription to be destroyed.
834
   * @return {undefined}
835
   */
836
  destroySubscription(subscription) {
837
    if (!(subscription instanceof Subscription)) {
63✔
838
      throw new TypeError('Invalid argument');
6✔
839
    }
840
    this._destroyEntity(subscription, this._subscriptions);
57✔
841
  }
842

843
  /**
844
   * Destroy a Client.
845
   * @param {Client} client - The Client to be destroyed.
846
   * @return {undefined}
847
   */
848
  destroyClient(client) {
849
    if (!(client instanceof Client)) {
24✔
850
      throw new TypeError('Invalid argument');
6✔
851
    }
852
    this._destroyEntity(client, this._clients);
18✔
853
  }
854

855
  /**
856
   * Destroy a Service.
857
   * @param {Service} service - The Service to be destroyed.
858
   * @return {undefined}
859
   */
860
  destroyService(service) {
861
    if (!(service instanceof Service)) {
24✔
862
      throw new TypeError('Invalid argument');
6✔
863
    }
864
    this._destroyEntity(service, this._services);
18✔
865
  }
866

867
  /**
868
   * Destroy a Timer.
869
   * @param {Timer} timer - The Timer to be destroyed.
870
   * @return {undefined}
871
   */
872
  destroyTimer(timer) {
873
    if (!(timer instanceof Timer)) {
24✔
874
      throw new TypeError('Invalid argument');
6✔
875
    }
876
    this._destroyEntity(timer, this._timers);
18✔
877
  }
878

879
  /**
880
   * Destroy a guard condition.
881
   * @param {GuardCondition} guard - The guard condition to be destroyed.
882
   * @return {undefined}
883
   */
884
  destroyGuardCondition(guard) {
885
    if (!(guard instanceof GuardCondition)) {
9!
886
      throw new TypeError('Invalid argument');
×
887
    }
888
    this._destroyEntity(guard, this._guards);
9✔
889
  }
890

891
  /**
892
   * Get the name of the node.
893
   * @return {string}
894
   */
895
  name() {
896
    return rclnodejs.getNodeName(this.handle);
5,166✔
897
  }
898

899
  /**
900
   * Get the namespace of the node.
901
   * @return {string}
902
   */
903
  namespace() {
904
    return rclnodejs.getNamespace(this.handle);
3,651✔
905
  }
906

907
  /**
908
   * Get the context in which this node was created.
909
   * @return {Context}
910
   */
911
  get context() {
912
    return this._context;
15,510✔
913
  }
914

915
  /**
916
   * Get the nodes logger.
917
   * @returns {Logger} - The logger for the node.
918
   */
919
  getLogger() {
920
    return this._logger;
423✔
921
  }
922

923
  /**
924
   * Get the clock used by the node.
925
   * @returns {Clock} - The nodes clock.
926
   */
927
  getClock() {
928
    return this._clock;
243✔
929
  }
930

931
  /**
932
   * Get the current time using the node's clock.
933
   * @returns {Time} - The current time.
934
   */
935
  now() {
936
    return this.getClock().now();
6✔
937
  }
938

939
  /**
940
   * Get the list of published topics discovered by the provided node for the remote node name.
941
   * @param {string} nodeName - The name of the node.
942
   * @param {string} namespace - The name of the namespace.
943
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
944
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
945
   */
946
  getPublisherNamesAndTypesByNode(nodeName, namespace, noDemangle = false) {
×
947
    return rclnodejs.getPublisherNamesAndTypesByNode(
×
948
      this.handle,
949
      nodeName,
950
      namespace,
951
      noDemangle
952
    );
953
  }
954

955
  /**
956
   * Get the list of published topics discovered by the provided node for the remote node name.
957
   * @param {string} nodeName - The name of the node.
958
   * @param {string} namespace - The name of the namespace.
959
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
960
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
961
   */
962
  getSubscriptionNamesAndTypesByNode(nodeName, namespace, noDemangle = false) {
×
963
    return rclnodejs.getSubscriptionNamesAndTypesByNode(
×
964
      this.handle,
965
      nodeName,
966
      namespace,
967
      noDemangle
968
    );
969
  }
970

971
  /**
972
   * Get service names and types for which a remote node has servers.
973
   * @param {string} nodeName - The name of the node.
974
   * @param {string} namespace - The name of the namespace.
975
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
976
   */
977
  getServiceNamesAndTypesByNode(nodeName, namespace) {
978
    return rclnodejs.getServiceNamesAndTypesByNode(
×
979
      this.handle,
980
      nodeName,
981
      namespace
982
    );
983
  }
984

985
  /**
986
   * Get service names and types for which a remote node has clients.
987
   * @param {string} nodeName - The name of the node.
988
   * @param {string} namespace - The name of the namespace.
989
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
990
   */
991
  getClientNamesAndTypesByNode(nodeName, namespace) {
992
    return rclnodejs.getClientNamesAndTypesByNode(
×
993
      this.handle,
994
      nodeName,
995
      namespace
996
    );
997
  }
998

999
  /**
1000
   * Get the list of topics discovered by the provided node.
1001
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
1002
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1003
   */
1004
  getTopicNamesAndTypes(noDemangle = false) {
×
1005
    return rclnodejs.getTopicNamesAndTypes(this.handle, noDemangle);
×
1006
  }
1007

1008
  /**
1009
   * Get the list of services discovered by the provided node.
1010
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1011
   */
1012
  getServiceNamesAndTypes() {
1013
    return rclnodejs.getServiceNamesAndTypes(this.handle);
6✔
1014
  }
1015

1016
  /**
1017
   * Get the list of nodes discovered by the provided node.
1018
   * @return {Array<string>} - An array of the names.
1019
   */
1020
  getNodeNames() {
1021
    return this.getNodeNamesAndNamespaces().map((item) => item.name);
120✔
1022
  }
1023

1024
  /**
1025
   * Get the list of nodes and their namespaces discovered by the provided node.
1026
   * @return {Array<{name: string, namespace: string}>} An array of the names and namespaces.
1027
   */
1028
  getNodeNamesAndNamespaces() {
1029
    return rclnodejs.getNodeNames(this.handle);
51✔
1030
  }
1031

1032
  /**
1033
   * Return the number of publishers on a given topic.
1034
   * @param {string} topic - The name of the topic.
1035
   * @returns {number} - Number of publishers on the given topic.
1036
   */
1037
  countPublishers(topic) {
1038
    let expandedTopic = rclnodejs.expandTopicName(
18✔
1039
      topic,
1040
      this.name(),
1041
      this.namespace()
1042
    );
1043
    rclnodejs.validateTopicName(expandedTopic);
18✔
1044

1045
    return rclnodejs.countPublishers(this.handle, expandedTopic);
18✔
1046
  }
1047

1048
  /**
1049
   * Return the number of subscribers on a given topic.
1050
   * @param {string} topic - The name of the topic.
1051
   * @returns {number} - Number of subscribers on the given topic.
1052
   */
1053
  countSubscribers(topic) {
1054
    let expandedTopic = rclnodejs.expandTopicName(
18✔
1055
      topic,
1056
      this.name(),
1057
      this.namespace()
1058
    );
1059
    rclnodejs.validateTopicName(expandedTopic);
18✔
1060

1061
    return rclnodejs.countSubscribers(this.handle, expandedTopic);
18✔
1062
  }
1063

1064
  /**
1065
   * Get the list of parameter-overrides found on the commandline and
1066
   * in the NodeOptions.parameter_overrides property.
1067
   *
1068
   * @return {Array<Parameter>} - An array of Parameters.
1069
   */
1070
  getParameterOverrides() {
1071
    return Array.from(this._parameterOverrides.values());
24✔
1072
  }
1073

1074
  /**
1075
   * Declare a parameter.
1076
   *
1077
   * Internally, register a parameter and it's descriptor.
1078
   * If a parameter-override exists, it's value will replace that of the parameter
1079
   * unless ignoreOverride is true.
1080
   * If the descriptor is undefined, then a ParameterDescriptor will be inferred
1081
   * from the parameter's state.
1082
   *
1083
   * If a parameter by the same name has already been declared then an Error is thrown.
1084
   * A parameter must be undeclared before attempting to redeclare it.
1085
   *
1086
   * @param {Parameter} parameter - Parameter to declare.
1087
   * @param {ParameterDescriptor} [descriptor] - Optional descriptor for parameter.
1088
   * @param {boolean} [ignoreOveride] - When true disregard any parameter-override that may be present.
1089
   * @return {Parameter} - The newly declared parameter.
1090
   */
1091
  declareParameter(parameter, descriptor, ignoreOveride = false) {
1,767✔
1092
    const parameters = this.declareParameters(
1,770✔
1093
      [parameter],
1094
      descriptor ? [descriptor] : [],
1,770✔
1095
      ignoreOveride
1096
    );
1097
    return parameters.length == 1 ? parameters[0] : null;
1,770!
1098
  }
1099

1100
  /**
1101
   * Declare a list of parameters.
1102
   *
1103
   * Internally register parameters with their corresponding descriptor one by one
1104
   * in the order they are provided. This is an atomic operation. If an error
1105
   * occurs the process halts and no further parameters are declared.
1106
   * Parameters that have already been processed are undeclared.
1107
   *
1108
   * While descriptors is an optional parameter, when provided there must be
1109
   * a descriptor for each parameter; otherwise an Error is thrown.
1110
   * If descriptors is not provided then a descriptor will be inferred
1111
   * from each parameter's state.
1112
   *
1113
   * When a parameter-override is available, the parameter's value
1114
   * will be replaced with that of the parameter-override unless ignoreOverrides
1115
   * is true.
1116
   *
1117
   * If a parameter by the same name has already been declared then an Error is thrown.
1118
   * A parameter must be undeclared before attempting to redeclare it.
1119
   *
1120
   * Prior to declaring the parameters each SetParameterEventCallback registered
1121
   * using setOnParameterEventCallback() is called in succession with the parameters
1122
   * list. Any SetParameterEventCallback that retuns does not return a successful
1123
   * result will cause the entire operation to terminate with no changes to the
1124
   * parameters. When all SetParameterEventCallbacks return successful then the
1125
   * list of parameters is updated.
1126
   *
1127
   * @param {Parameter[]} parameters - The parameters to declare.
1128
   * @param {ParameterDescriptor[]} [descriptors] - Optional descriptors,
1129
   *    a 1-1 correspondence with parameters.
1130
   * @param {boolean} ignoreOverrides - When true, parameter-overrides are
1131
   *    not considered, i.e.,ignored.
1132
   * @return {Parameter[]} - The declared parameters.
1133
   */
1134
  declareParameters(parameters, descriptors = [], ignoreOverrides = false) {
×
1135
    if (!Array.isArray(parameters)) {
1,770!
1136
      throw new TypeError('Invalid parameter: expected array of Parameter');
×
1137
    }
1138
    if (!Array.isArray(descriptors)) {
1,770!
1139
      throw new TypeError(
×
1140
        'Invalid parameters: expected array of ParameterDescriptor'
1141
      );
1142
    }
1143
    if (descriptors.length > 0 && parameters.length !== descriptors.length) {
1,770!
1144
      throw new TypeError(
×
1145
        'Each parameter must have a cooresponding ParameterDescriptor'
1146
      );
1147
    }
1148

1149
    const declaredDescriptors = [];
1,770✔
1150
    const declaredParameters = [];
1,770✔
1151
    const declaredParameterCollisions = [];
1,770✔
1152
    for (let i = 0; i < parameters.length; i++) {
1,770✔
1153
      let parameter =
1154
        !ignoreOverrides && this._parameterOverrides.has(parameters[i].name)
1,770✔
1155
          ? this._parameterOverrides.get(parameters[i].name)
1156
          : parameters[i];
1157

1158
      // stop processing parameters that have already been declared
1159
      if (this._parameters.has(parameter.name)) {
1,770!
1160
        declaredParameterCollisions.push(parameter);
×
1161
        continue;
×
1162
      }
1163

1164
      // create descriptor for parameter if not provided
1165
      let descriptor =
1166
        descriptors.length > 0
1,770✔
1167
          ? descriptors[i]
1168
          : ParameterDescriptor.fromParameter(parameter);
1169

1170
      descriptor.validate();
1,770✔
1171

1172
      declaredDescriptors.push(descriptor);
1,770✔
1173
      declaredParameters.push(parameter);
1,770✔
1174
    }
1175

1176
    if (declaredParameterCollisions.length > 0) {
1,770!
1177
      const errorMsg =
1178
        declaredParameterCollisions.length == 1
×
1179
          ? `Parameter(${declaredParameterCollisions[0]}) already declared.`
1180
          : `Multiple parameters already declared, e.g., Parameter(${declaredParameterCollisions[0]}).`;
1181
      throw new Error(errorMsg);
×
1182
    }
1183

1184
    // register descriptor
1185
    for (const descriptor of declaredDescriptors) {
1,770✔
1186
      this._parameterDescriptors.set(descriptor.name, descriptor);
1,770✔
1187
    }
1188

1189
    const result = this._setParametersAtomically(declaredParameters, true);
1,770✔
1190
    if (!result.successful) {
1,770!
1191
      // unregister descriptors
1192
      for (const descriptor of declaredDescriptors) {
×
1193
        this._parameterDescriptors.delete(descriptor.name);
×
1194
      }
1195

1196
      throw new Error(result.reason);
×
1197
    }
1198

1199
    return this.getParameters(declaredParameters.map((param) => param.name));
1,770✔
1200
  }
1201

1202
  /**
1203
   * Undeclare a parameter.
1204
   *
1205
   * Readonly parameters can not be undeclared or updated.
1206
   * @param {string} name - Name of parameter to undeclare.
1207
   * @return {undefined} -
1208
   */
1209
  undeclareParameter(name) {
1210
    if (!this.hasParameter(name)) return;
3!
1211

1212
    const descriptor = this.getParameterDescriptor(name);
3✔
1213
    if (descriptor.readOnly) {
3!
1214
      throw new Error(
×
1215
        `${name} parameter is read-only and can not be undeclared`
1216
      );
1217
    }
1218

1219
    this._parameters.delete(name);
3✔
1220
    this._parameterDescriptors.delete(name);
3✔
1221
  }
1222

1223
  /**
1224
   * Determine if a parameter has been declared.
1225
   * @param {string} name - name of parameter
1226
   * @returns {boolean} - Return true if parameter is declared; false otherwise.
1227
   */
1228
  hasParameter(name) {
1229
    return this._parameters.has(name);
5,169✔
1230
  }
1231

1232
  /**
1233
   * Get a declared parameter by name.
1234
   *
1235
   * If unable to locate a declared parameter then a
1236
   * parameter with type == PARAMETER_NOT_SET is returned.
1237
   *
1238
   * @param {string} name - The name of the parameter.
1239
   * @return {Parameter} - The parameter.
1240
   */
1241
  getParameter(name) {
1242
    return this.getParameters([name])[0];
1,701✔
1243
  }
1244

1245
  /**
1246
   * Get a list of parameters.
1247
   *
1248
   * Find and return the declared parameters.
1249
   * If no names are provided return all declared parameters.
1250
   *
1251
   * If unable to locate a declared parameter then a
1252
   * parameter with type == PARAMETER_NOT_SET is returned in
1253
   * it's place.
1254
   *
1255
   * @param {string[]} [names] - The names of the declared parameters
1256
   *    to find or null indicating to return all declared parameters.
1257
   * @return {Parameter[]} - The parameters.
1258
   */
1259
  getParameters(names = []) {
24✔
1260
    let params = [];
3,498✔
1261

1262
    if (names.length == 0) {
3,498✔
1263
      // get all parameters
1264
      params = [...this._parameters.values()];
24✔
1265
      return params;
24✔
1266
    }
1267

1268
    for (const name of names) {
3,474✔
1269
      const param = this.hasParameter(name)
3,477!
1270
        ? this._parameters.get(name)
1271
        : new Parameter(name, ParameterType.PARAMETER_NOT_SET);
1272

1273
      params.push(param);
3,477✔
1274
    }
1275

1276
    return params;
3,474✔
1277
  }
1278

1279
  /**
1280
   * Get the types of given parameters.
1281
   *
1282
   * Return the types of given parameters.
1283
   *
1284
   * @param {string[]} [names] - The names of the declared parameters.
1285
   * @return {Uint8Array} - The types.
1286
   */
1287
  getParameterTypes(names = []) {
×
1288
    let types = [];
3✔
1289

1290
    for (const name of names) {
3✔
1291
      const descriptor = this._parameterDescriptors.get(name);
9✔
1292
      if (descriptor) {
9!
1293
        types.push(descriptor.type);
9✔
1294
      }
1295
    }
1296
    return types;
3✔
1297
  }
1298

1299
  /**
1300
   * Get the names of all declared parameters.
1301
   *
1302
   * @return {Array<string>} - The declared parameter names or empty array if
1303
   *    no parameters have been declared.
1304
   */
1305
  getParameterNames() {
1306
    return this.getParameters().map((param) => param.name);
45✔
1307
  }
1308

1309
  /**
1310
   * Determine if a parameter descriptor exists.
1311
   *
1312
   * @param {string} name - The name of a descriptor to for.
1313
   * @return {boolean} - True if a descriptor has been declared; otherwise false.
1314
   */
1315
  hasParameterDescriptor(name) {
1316
    return !!this.getParameterDescriptor(name);
1,788✔
1317
  }
1318

1319
  /**
1320
   * Get a declared parameter descriptor by name.
1321
   *
1322
   * If unable to locate a declared parameter descriptor then a
1323
   * descriptor with type == PARAMETER_NOT_SET is returned.
1324
   *
1325
   * @param {string} name - The name of the parameter descriptor to find.
1326
   * @return {ParameterDescriptor} - The parameter descriptor.
1327
   */
1328
  getParameterDescriptor(name) {
1329
    return this.getParameterDescriptors([name])[0];
3,579✔
1330
  }
1331

1332
  /**
1333
   * Find a list of declared ParameterDescriptors.
1334
   *
1335
   * If no names are provided return all declared descriptors.
1336
   *
1337
   * If unable to locate a declared descriptor then a
1338
   * descriptor with type == PARAMETER_NOT_SET is returned in
1339
   * it's place.
1340
   *
1341
   * @param {string[]} [names] - The names of the declared parameter
1342
   *    descriptors to find or null indicating to return all declared descriptors.
1343
   * @return {ParameterDescriptor[]} - The parameter descriptors.
1344
   */
1345
  getParameterDescriptors(names = []) {
×
1346
    let descriptors = [];
3,582✔
1347

1348
    if (names.length == 0) {
3,582!
1349
      // get all parameters
1350
      descriptors = [...this._parameterDescriptors.values()];
×
1351
      return descriptors;
×
1352
    }
1353

1354
    for (const name of names) {
3,582✔
1355
      let descriptor = this._parameterDescriptors.get(name);
3,585✔
1356
      if (!descriptor) {
3,585!
1357
        descriptor = new ParameterDescriptor(
×
1358
          name,
1359
          ParameterType.PARAMETER_NOT_SET
1360
        );
1361
      }
1362
      descriptors.push(descriptor);
3,585✔
1363
    }
1364

1365
    return descriptors;
3,582✔
1366
  }
1367

1368
  /**
1369
   * Replace a declared parameter.
1370
   *
1371
   * The parameter being replaced must be a declared parameter who's descriptor
1372
   * is not readOnly; otherwise an Error is thrown.
1373
   *
1374
   * @param {Parameter} parameter - The new parameter.
1375
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult} - The result of the operation.
1376
   */
1377
  setParameter(parameter) {
1378
    const results = this.setParameters([parameter]);
12✔
1379
    return results[0];
12✔
1380
  }
1381

1382
  /**
1383
   * Replace a list of declared parameters.
1384
   *
1385
   * Declared parameters are replaced in the order they are provided and
1386
   * a ParameterEvent is published for each individual parameter change.
1387
   *
1388
   * Prior to setting the parameters each SetParameterEventCallback registered
1389
   * using setOnParameterEventCallback() is called in succession with the parameters
1390
   * list. Any SetParameterEventCallback that retuns does not return a successful
1391
   * result will cause the entire operation to terminate with no changes to the
1392
   * parameters. When all SetParameterEventCallbacks return successful then the
1393
   * list of parameters is updated.
1394
   *
1395
   * If an error occurs, the process is stopped and returned. Parameters
1396
   * set before an error remain unchanged.
1397
   *
1398
   * @param {Parameter[]} parameters - The parameters to set.
1399
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult[]} - A list of SetParameterResult, one for each parameter that was set.
1400
   */
1401
  setParameters(parameters = []) {
×
1402
    return parameters.map((parameter) =>
15✔
1403
      this.setParametersAtomically([parameter])
15✔
1404
    );
1405
  }
1406

1407
  /**
1408
   * Repalce a list of declared parameters atomically.
1409
   *
1410
   * Declared parameters are replaced in the order they are provided.
1411
   * A single ParameterEvent is published collectively for all changed
1412
   * parameters.
1413
   *
1414
   * Prior to setting the parameters each SetParameterEventCallback registered
1415
   * using setOnParameterEventCallback() is called in succession with the parameters
1416
   * list. Any SetParameterEventCallback that retuns does not return a successful
1417
   * result will cause the entire operation to terminate with no changes to the
1418
   * parameters. When all SetParameterEventCallbacks return successful then the
1419
   * list of parameters is updated.d
1420
   *
1421
   * If an error occurs, the process stops immediately. All parameters updated to
1422
   * the point of the error are reverted to their previous state.
1423
   *
1424
   * @param {Parameter[]} parameters - The parameters to set.
1425
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult} - describes the result of setting 1 or more parameters.
1426
   */
1427
  setParametersAtomically(parameters = []) {
×
1428
    return this._setParametersAtomically(parameters);
18✔
1429
  }
1430

1431
  /**
1432
   * Internal method for updating parameters atomically.
1433
   *
1434
   * Prior to setting the parameters each SetParameterEventCallback registered
1435
   * using setOnParameterEventCallback() is called in succession with the parameters
1436
   * list. Any SetParameterEventCallback that retuns does not return a successful
1437
   * result will cause the entire operation to terminate with no changes to the
1438
   * parameters. When all SetParameterEventCallbacks return successful then the
1439
   * list of parameters is updated.
1440
   *
1441
   * @param {Paramerter[]} parameters - The parameters to update.
1442
   * @param {boolean} declareParameterMode - When true parameters are being declared;
1443
   *    otherwise they are being changed.
1444
   * @return {SetParameterResult} - A single collective result.
1445
   */
1446
  _setParametersAtomically(parameters = [], declareParameterMode = false) {
18!
1447
    let result = this._validateParameters(parameters, declareParameterMode);
1,788✔
1448
    if (!result.successful) {
1,788!
1449
      return result;
×
1450
    }
1451

1452
    // give all SetParametersCallbacks a chance to veto this change
1453
    for (const callback of this._setParametersCallbacks) {
1,788✔
1454
      result = callback(parameters);
141✔
1455
      if (!result.successful) {
141✔
1456
        // a callback has vetoed a parameter change
1457
        return result;
3✔
1458
      }
1459
    }
1460

1461
    // collectively track updates to parameters for use
1462
    // when publishing a ParameterEvent
1463
    const newParameters = [];
1,785✔
1464
    const changedParameters = [];
1,785✔
1465
    const deletedParameters = [];
1,785✔
1466

1467
    for (const parameter of parameters) {
1,785✔
1468
      if (parameter.type == ParameterType.PARAMETER_NOT_SET) {
1,785✔
1469
        this.undeclareParameter(parameter.name);
3✔
1470
        deletedParameters.push(parameter);
3✔
1471
      } else {
1472
        this._parameters.set(parameter.name, parameter);
1,782✔
1473
        if (declareParameterMode) {
1,782✔
1474
          newParameters.push(parameter);
1,770✔
1475
        } else {
1476
          changedParameters.push(parameter);
12✔
1477
        }
1478
      }
1479
    }
1480

1481
    // create ParameterEvent
1482
    const parameterEvent = new (loader.loadInterface(
1,785✔
1483
      PARAMETER_EVENT_MSG_TYPE
1484
    ))();
1485

1486
    const { seconds, nanoseconds } = this._clock.now().secondsAndNanoseconds;
1,785✔
1487
    parameterEvent.stamp = {
1,785✔
1488
      sec: Number(seconds),
1489
      nanosec: Number(nanoseconds),
1490
    };
1491

1492
    parameterEvent.node =
1,785✔
1493
      this.namespace() === '/'
1,785✔
1494
        ? this.namespace() + this.name()
1495
        : this.namespace() + '/' + this.name();
1496

1497
    if (newParameters.length > 0) {
1,785✔
1498
      parameterEvent['new_parameters'] = newParameters.map((parameter) =>
1,770✔
1499
        parameter.toParameterMessage()
1,770✔
1500
      );
1501
    }
1502
    if (changedParameters.length > 0) {
1,785✔
1503
      parameterEvent['changed_parameters'] = changedParameters.map(
12✔
1504
        (parameter) => parameter.toParameterMessage()
12✔
1505
      );
1506
    }
1507
    if (deletedParameters.length > 0) {
1,785✔
1508
      parameterEvent['deleted_parameters'] = deletedParameters.map(
3✔
1509
        (parameter) => parameter.toParameterMessage()
3✔
1510
      );
1511
    }
1512

1513
    // Publish ParameterEvent.
1514
    this._parameterEventPublisher.publish(parameterEvent);
1,785✔
1515

1516
    return {
1,785✔
1517
      successful: true,
1518
      reason: '',
1519
    };
1520
  }
1521

1522
  /**
1523
   * This callback is called when declaring a parameter or setting a parameter.
1524
   * The callback is provided a list of parameters and returns a SetParameterResult
1525
   * to indicate approval or veto of the operation.
1526
   *
1527
   * @callback SetParametersCallback
1528
   * @param {Parameter[]} parameters - The message published
1529
   * @returns {rcl_interfaces.msg.SetParameterResult} -
1530
   *
1531
   * @see [Node.addOnSetParametersCallback]{@link Node#addOnSetParametersCallback}
1532
   * @see [Node.removeOnSetParametersCallback]{@link Node#removeOnSetParametersCallback}
1533
   */
1534

1535
  /**
1536
   * Add a callback to the front of the list of callbacks invoked for parameter declaration
1537
   * and setting. No checks are made for duplicate callbacks.
1538
   *
1539
   * @param {SetParametersCallback} callback - The callback to add.
1540
   * @returns {undefined}
1541
   */
1542
  addOnSetParametersCallback(callback) {
1543
    this._setParametersCallbacks.unshift(callback);
1,689✔
1544
  }
1545

1546
  /**
1547
   * Remove a callback from the list of SetParametersCallbacks.
1548
   * If the callback is not found the process is a nop.
1549
   *
1550
   * @param {SetParametersCallback} callback - The callback to be removed
1551
   * @returns {undefined}
1552
   */
1553
  removeOnSetParametersCallback(callback) {
1554
    const idx = this._setParametersCallbacks.indexOf(callback);
6✔
1555
    if (idx > -1) {
6!
1556
      this._setParametersCallbacks.splice(idx, 1);
6✔
1557
    }
1558
  }
1559

1560
  // returns on 1st error or result {successful, reason}
1561
  _validateParameters(parameters = [], declareParameterMode = false) {
×
1562
    for (const parameter of parameters) {
1,788✔
1563
      // detect invalid parameter
1564
      try {
1,788✔
1565
        parameter.validate();
1,788✔
1566
      } catch {
1567
        return {
×
1568
          successful: false,
1569
          reason: `Invalid ${parameter.name}`,
1570
        };
1571
      }
1572

1573
      // detect undeclared parameter
1574
      if (!this.hasParameterDescriptor(parameter.name)) {
1,788!
1575
        return {
×
1576
          successful: false,
1577
          reason: `Parameter ${parameter.name} has not been declared`,
1578
        };
1579
      }
1580

1581
      // detect readonly parameter that can not be updated
1582
      const descriptor = this.getParameterDescriptor(parameter.name);
1,788✔
1583
      if (!declareParameterMode && descriptor.readOnly) {
1,788!
1584
        return {
×
1585
          successful: false,
1586
          reason: `Parameter ${parameter.name} is readonly`,
1587
        };
1588
      }
1589

1590
      // validate parameter against descriptor if not an undeclare action
1591
      if (parameter.type != ParameterType.PARAMETER_NOT_SET) {
1,788✔
1592
        try {
1,785✔
1593
          descriptor.validateParameter(parameter);
1,785✔
1594
        } catch {
1595
          return {
×
1596
            successful: false,
1597
            reason: `Parameter ${parameter.name} does not  readonly`,
1598
          };
1599
        }
1600
      }
1601
    }
1602

1603
    return {
1,788✔
1604
      successful: true,
1605
      reason: null,
1606
    };
1607
  }
1608

1609
  // Get a Map(nodeName->Parameter[]) of CLI parameter args that
1610
  // apply to 'this' node, .e.g., -p mynode:foo:=bar -p hello:=world
1611
  _getNativeParameterOverrides() {
1612
    const overrides = new Map();
1,665✔
1613

1614
    // Get native parameters from rcl context->global_arguments.
1615
    // rclnodejs returns an array of objects, 1 for each node e.g., -p my_node:foo:=bar,
1616
    // and a node named '/**' for global parameter rules,
1617
    // i.e., does not include a node identifier, e.g., -p color:=red
1618
    // {
1619
    //   name: string // node name
1620
    //   parameters[] = {
1621
    //     name: string
1622
    //     type: uint
1623
    //     value: object
1624
    // }
1625
    const cliParamOverrideData = rclnodejs.getParameterOverrides(
1,665✔
1626
      this.context.handle
1627
    );
1628

1629
    // convert native CLI parameterOverrides to Map<nodeName,Array<ParameterOverride>>
1630
    const cliParamOverrides = new Map();
1,665✔
1631
    if (cliParamOverrideData) {
1,665✔
1632
      for (let nodeParamData of cliParamOverrideData) {
24✔
1633
        const nodeName = nodeParamData.name;
36✔
1634
        const nodeParamOverrides = [];
36✔
1635
        for (let paramData of nodeParamData.parameters) {
36✔
1636
          const paramOverride = new Parameter(
51✔
1637
            paramData.name,
1638
            paramData.type,
1639
            paramData.value
1640
          );
1641
          nodeParamOverrides.push(paramOverride);
51✔
1642
        }
1643
        cliParamOverrides.set(nodeName, nodeParamOverrides);
36✔
1644
      }
1645
    }
1646

1647
    // collect global CLI global parameters, name == /**
1648
    let paramOverrides = cliParamOverrides.get('/**'); // array of ParameterOverrides
1,665✔
1649
    if (paramOverrides) {
1,665✔
1650
      for (const parameter of paramOverrides) {
15✔
1651
        overrides.set(parameter.name, parameter);
18✔
1652
      }
1653
    }
1654

1655
    // merge CLI node parameterOverrides with global parameterOverrides, replace existing
1656
    paramOverrides = cliParamOverrides.get(this.name()); // array of ParameterOverrides
1,665✔
1657
    if (paramOverrides) {
1,665✔
1658
      for (const parameter of paramOverrides) {
15✔
1659
        overrides.set(parameter.name, parameter);
21✔
1660
      }
1661
    }
1662

1663
    return overrides;
1,665✔
1664
  }
1665

1666
  /**
1667
   * Invokes the callback with a raw message of the given type. After the callback completes
1668
   * the message will be destroyed.
1669
   * @param {function} Type - Message type to create.
1670
   * @param {function} callback - Callback to invoke. First parameter will be the raw message,
1671
   * and the second is a function to retrieve the deserialized message.
1672
   * @returns {undefined}
1673
   */
1674
  _runWithMessageType(Type, callback) {
1675
    let message = new Type();
2,096✔
1676

1677
    callback(message.toRawROS(), () => {
2,096✔
1678
      let result = new Type();
1,657✔
1679
      result.deserialize(message.refObject);
1,657✔
1680

1681
      return result;
1,657✔
1682
    });
1683

1684
    Type.destoryRawROS(message);
2,096✔
1685
  }
1686

1687
  _addActionClient(actionClient) {
1688
    this._actionClients.push(actionClient);
114✔
1689
    this.syncHandles();
114✔
1690
  }
1691

1692
  _addActionServer(actionServer) {
1693
    this._actionServers.push(actionServer);
114✔
1694
    this.syncHandles();
114✔
1695
  }
1696
}
1697

1698
/**
1699
 * Create an Options instance initialized with default values.
1700
 * @returns {Options} - The new initialized instance.
1701
 * @static
1702
 * @example
1703
 * {
1704
 *   enableTypedArray: true,
1705
 *   isRaw: false,
1706
 *   qos: QoS.profileDefault,
1707
 *   contentFilter: undefined,
1708
 * }
1709
 */
1710
Node.getDefaultOptions = function () {
78✔
1711
  return {
14,223✔
1712
    enableTypedArray: true,
1713
    isRaw: false,
1714
    qos: QoS.profileDefault,
1715
    contentFilter: undefined,
1716
  };
1717
};
1718

1719
module.exports = Node;
78✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc