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

RobotWebTools / rclnodejs / 20308747520

17 Dec 2025 03:50PM UTC coverage: 80.367% (-0.04%) from 80.403%
20308747520

Pull #1357

github

web-flow
Merge e35eff136 into 4a1b0db25
Pull Request #1357: Add Observable subscriptions with RxJS support

1250 of 1738 branches covered (71.92%)

Branch coverage included in aggregate %.

31 of 34 new or added lines in 2 files covered. (91.18%)

45 existing lines in 1 file now uncovered.

2696 of 3172 relevant lines covered (84.99%)

503.25 hits per line

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

86.52
/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('./native_loader.js');
26✔
18

19
const ActionInterfaces = require('./action/interfaces.js');
26✔
20
const Client = require('./client.js');
26✔
21
const Clock = require('./clock.js');
26✔
22
const Context = require('./context.js');
26✔
23
const debug = require('debug')('rclnodejs:node');
26✔
24
const DistroUtils = require('./distro.js');
26✔
25
const GuardCondition = require('./guard_condition.js');
26✔
26
const loader = require('./interface_loader.js');
26✔
27
const Logging = require('./logging.js');
26✔
28
const NodeOptions = require('./node_options.js');
26✔
29
const {
30
  ParameterType,
31
  Parameter,
32
  ParameterDescriptor,
33
} = require('./parameter.js');
26✔
34
const { isValidSerializationMode } = require('./message_serialization.js');
26✔
35
const {
36
  TypeValidationError,
37
  RangeValidationError,
38
  ValidationError,
39
} = require('./errors.js');
26✔
40
const ParameterService = require('./parameter_service.js');
26✔
41
const ParameterClient = require('./parameter_client.js');
26✔
42
const ParameterWatcher = require('./parameter_watcher.js');
26✔
43
const Publisher = require('./publisher.js');
26✔
44
const QoS = require('./qos.js');
26✔
45
const Rates = require('./rate.js');
26✔
46
const Service = require('./service.js');
26✔
47
const Subscription = require('./subscription.js');
26✔
48
const ObservableSubscription = require('./observable_subscription.js');
26✔
49
const TimeSource = require('./time_source.js');
26✔
50
const Timer = require('./timer.js');
26✔
51
const TypeDescriptionService = require('./type_description_service.js');
26✔
52
const Entity = require('./entity.js');
26✔
53
const { SubscriptionEventCallbacks } = require('../lib/event_handler.js');
26✔
54
const { PublisherEventCallbacks } = require('../lib/event_handler.js');
26✔
55
const { validateFullTopicName } = require('./validator.js');
26✔
56

57
// Parameter event publisher constants
58
const PARAMETER_EVENT_MSG_TYPE = 'rcl_interfaces/msg/ParameterEvent';
26✔
59
const PARAMETER_EVENT_TOPIC = 'parameter_events';
26✔
60

61
/**
62
 * @class - Class representing a Node in ROS
63
 */
64

65
class Node extends rclnodejs.ShadowNode {
66
  /**
67
   * Create a ROS2Node.
68
   * model using the {@link https://github.com/ros2/rcl/tree/master/rcl_lifecycle|ros2 client library (rcl) lifecyle api}.
69
   * @param {string} nodeName - The name used to register in ROS.
70
   * @param {string} [namespace=''] - The namespace used in ROS.
71
   * @param {Context} [context=Context.defaultContext()] - The context to create the node in.
72
   * @param {NodeOptions} [options=NodeOptions.defaultOptions] - The options to configure the new node behavior.
73
   * @throws {Error} If the given context is not registered.
74
   */
75
  constructor(
76
    nodeName,
77
    namespace = '',
44✔
78
    context = Context.defaultContext(),
79✔
79
    options = NodeOptions.defaultOptions,
81✔
80
    args = [],
100✔
81
    useGlobalArguments = true
100✔
82
  ) {
83
    super();
828✔
84

85
    if (typeof nodeName !== 'string') {
828✔
86
      throw new TypeValidationError('nodeName', nodeName, 'string');
12✔
87
    }
88
    if (typeof namespace !== 'string') {
816✔
89
      throw new TypeValidationError('namespace', namespace, 'string');
10✔
90
    }
91

92
    this._init(nodeName, namespace, options, context, args, useGlobalArguments);
806✔
93
    debug(
796✔
94
      'Finish initializing node, name = %s and namespace = %s.',
95
      nodeName,
96
      namespace
97
    );
98
  }
99

100
  _init(name, namespace, options, context, args, useGlobalArguments) {
101
    this.handle = rclnodejs.createNode(
806✔
102
      name,
103
      namespace,
104
      context.handle,
105
      args,
106
      useGlobalArguments,
107
      options.rosoutQos
108
    );
109
    Object.defineProperty(this, 'handle', {
796✔
110
      configurable: false,
111
      writable: false,
112
    }); // make read-only
113

114
    this._context = context;
796✔
115
    this.context.onNodeCreated(this);
796✔
116

117
    this._publishers = [];
796✔
118
    this._subscriptions = [];
796✔
119
    this._clients = [];
796✔
120
    this._services = [];
796✔
121
    this._timers = [];
796✔
122
    this._guards = [];
796✔
123
    this._events = [];
796✔
124
    this._actionClients = [];
796✔
125
    this._actionServers = [];
796✔
126
    this._parameterClients = [];
796✔
127
    this._parameterWatchers = [];
796✔
128
    this._rateTimerServer = null;
796✔
129
    this._parameterDescriptors = new Map();
796✔
130
    this._parameters = new Map();
796✔
131
    this._parameterService = null;
796✔
132
    this._typeDescriptionService = null;
796✔
133
    this._parameterEventPublisher = null;
796✔
134
    this._setParametersCallbacks = [];
796✔
135
    this._logger = new Logging(rclnodejs.getNodeLoggerName(this.handle));
796✔
136
    this._spinning = false;
796✔
137
    this._enableRosout = options.enableRosout;
796✔
138

139
    if (this._enableRosout) {
796✔
140
      rclnodejs.initRosoutPublisherForNode(this.handle);
795✔
141
    }
142

143
    this._parameterEventPublisher = this.createPublisher(
796✔
144
      PARAMETER_EVENT_MSG_TYPE,
145
      PARAMETER_EVENT_TOPIC
146
    );
147

148
    // initialize _parameterOverrides from parameters defined on the commandline
149
    this._parameterOverrides = this._getNativeParameterOverrides();
796✔
150

151
    // override cli parameterOverrides with those specified in options
152
    if (options.parameterOverrides.length > 0) {
796✔
153
      for (const parameter of options.parameterOverrides) {
8✔
154
        if ((!parameter) instanceof Parameter) {
13!
155
          throw new TypeValidationError(
×
156
            'parameterOverride',
157
            parameter,
158
            'Parameter instance',
159
            {
160
              nodeName: name,
161
            }
162
          );
163
        }
164
        this._parameterOverrides.set(parameter.name, parameter);
13✔
165
      }
166
    }
167

168
    // initialize _parameters from parameterOverrides
169
    if (options.automaticallyDeclareParametersFromOverrides) {
796✔
170
      for (const parameter of this._parameterOverrides.values()) {
5✔
171
        parameter.validate();
10✔
172
        const descriptor = ParameterDescriptor.fromParameter(parameter);
10✔
173
        this._parameters.set(parameter.name, parameter);
10✔
174
        this._parameterDescriptors.set(parameter.name, descriptor);
10✔
175
      }
176
    }
177

178
    // Clock that has support for ROS time.
179
    // Note: parameter overrides and parameter event publisher need to be ready at this point
180
    // to be able to declare 'use_sim_time' if it was not declared yet.
181
    this._clock = new Clock.ROSClock();
796✔
182
    this._timeSource = new TimeSource(this);
796✔
183
    this._timeSource.attachClock(this._clock);
796✔
184

185
    if (options.startParameterServices) {
796✔
186
      this._parameterService = new ParameterService(this);
790✔
187
      this._parameterService.start();
790✔
188
    }
189

190
    if (
796!
191
      DistroUtils.getDistroId() >= DistroUtils.getDistroId('jazzy') &&
1,592✔
192
      options.startTypeDescriptionService
193
    ) {
194
      this._typeDescriptionService = new TypeDescriptionService(this);
796✔
195
      this._typeDescriptionService.start();
796✔
196
    }
197
  }
198

199
  execute(handles) {
200
    let timersReady = this._timers.filter((timer) =>
9,002✔
201
      handles.includes(timer.handle)
8,068✔
202
    );
203
    let guardsReady = this._guards.filter((guard) =>
9,002✔
204
      handles.includes(guard.handle)
3✔
205
    );
206
    let subscriptionsReady = this._subscriptions.filter((subscription) =>
9,002✔
207
      handles.includes(subscription.handle)
506✔
208
    );
209
    let clientsReady = this._clients.filter((client) =>
9,002✔
210
      handles.includes(client.handle)
313✔
211
    );
212
    let servicesReady = this._services.filter((service) =>
9,002✔
213
      handles.includes(service.handle)
45,199✔
214
    );
215
    let actionClientsReady = this._actionClients.filter((actionClient) =>
9,002✔
216
      handles.includes(actionClient.handle)
156✔
217
    );
218
    let actionServersReady = this._actionServers.filter((actionServer) =>
9,002✔
219
      handles.includes(actionServer.handle)
156✔
220
    );
221
    let eventsReady = this._events.filter((event) =>
9,002✔
222
      handles.includes(event.handle)
4✔
223
    );
224

225
    timersReady.forEach((timer) => {
9,002✔
226
      if (timer.isReady()) {
8,058✔
227
        rclnodejs.callTimer(timer.handle);
8,001✔
228
        timer.callback();
8,001✔
229
      }
230
    });
231

232
    eventsReady.forEach((event) => {
9,002✔
233
      event.takeData();
4✔
234
    });
235

236
    for (const subscription of subscriptionsReady) {
9,002✔
237
      if (subscription.isDestroyed()) continue;
461✔
238
      if (subscription.isRaw) {
451✔
239
        let rawMessage = rclnodejs.rclTakeRaw(subscription.handle);
1✔
240
        if (rawMessage) {
1!
241
          subscription.processResponse(rawMessage);
1✔
242
        }
243
        continue;
1✔
244
      }
245

246
      this._runWithMessageType(
450✔
247
        subscription.typeClass,
248
        (message, deserialize) => {
249
          let success = rclnodejs.rclTake(subscription.handle, message);
450✔
250
          if (success) {
450✔
251
            subscription.processResponse(deserialize());
381✔
252
          }
253
        }
254
      );
255
    }
256

257
    for (const guard of guardsReady) {
9,002✔
258
      if (guard.isDestroyed()) continue;
3!
259

260
      guard.callback();
3✔
261
    }
262

263
    for (const client of clientsReady) {
9,002✔
264
      if (client.isDestroyed()) continue;
159!
265
      this._runWithMessageType(
159✔
266
        client.typeClass.Response,
267
        (message, deserialize) => {
268
          let sequenceNumber = rclnodejs.rclTakeResponse(
159✔
269
            client.handle,
270
            message
271
          );
272
          if (sequenceNumber !== undefined) {
159✔
273
            client.processResponse(sequenceNumber, deserialize());
86✔
274
          }
275
        }
276
      );
277
    }
278

279
    for (const service of servicesReady) {
9,002✔
280
      if (service.isDestroyed()) continue;
177!
281
      this._runWithMessageType(
177✔
282
        service.typeClass.Request,
283
        (message, deserialize) => {
284
          let header = rclnodejs.rclTakeRequest(
177✔
285
            service.handle,
286
            this.handle,
287
            message
288
          );
289
          if (header) {
177✔
290
            service.processRequest(header, deserialize());
91✔
291
          }
292
        }
293
      );
294
    }
295

296
    for (const actionClient of actionClientsReady) {
9,002✔
297
      if (actionClient.isDestroyed()) continue;
74!
298

299
      const properties = actionClient.handle.properties;
74✔
300

301
      if (properties.isGoalResponseReady) {
74✔
302
        this._runWithMessageType(
34✔
303
          actionClient.typeClass.impl.SendGoalService.Response,
304
          (message, deserialize) => {
305
            let sequence = rclnodejs.actionTakeGoalResponse(
34✔
306
              actionClient.handle,
307
              message
308
            );
309
            if (sequence != undefined) {
34✔
310
              actionClient.processGoalResponse(sequence, deserialize());
30✔
311
            }
312
          }
313
        );
314
      }
315

316
      if (properties.isCancelResponseReady) {
74✔
317
        this._runWithMessageType(
5✔
318
          actionClient.typeClass.impl.CancelGoal.Response,
319
          (message, deserialize) => {
320
            let sequence = rclnodejs.actionTakeCancelResponse(
5✔
321
              actionClient.handle,
322
              message
323
            );
324
            if (sequence != undefined) {
5✔
325
              actionClient.processCancelResponse(sequence, deserialize());
4✔
326
            }
327
          }
328
        );
329
      }
330

331
      if (properties.isResultResponseReady) {
74✔
332
        this._runWithMessageType(
15✔
333
          actionClient.typeClass.impl.GetResultService.Response,
334
          (message, deserialize) => {
335
            let sequence = rclnodejs.actionTakeResultResponse(
15✔
336
              actionClient.handle,
337
              message
338
            );
339
            if (sequence != undefined) {
15!
340
              actionClient.processResultResponse(sequence, deserialize());
15✔
341
            }
342
          }
343
        );
344
      }
345

346
      if (properties.isFeedbackReady) {
74✔
347
        this._runWithMessageType(
7✔
348
          actionClient.typeClass.impl.FeedbackMessage,
349
          (message, deserialize) => {
350
            let success = rclnodejs.actionTakeFeedback(
7✔
351
              actionClient.handle,
352
              message
353
            );
354
            if (success) {
7✔
355
              actionClient.processFeedbackMessage(deserialize());
5✔
356
            }
357
          }
358
        );
359
      }
360

361
      if (properties.isStatusReady) {
74✔
362
        this._runWithMessageType(
38✔
363
          actionClient.typeClass.impl.GoalStatusArray,
364
          (message, deserialize) => {
365
            let success = rclnodejs.actionTakeStatus(
38✔
366
              actionClient.handle,
367
              message
368
            );
369
            if (success) {
38✔
370
              actionClient.processStatusMessage(deserialize());
35✔
371
            }
372
          }
373
        );
374
      }
375
    }
376

377
    for (const actionServer of actionServersReady) {
9,002✔
378
      if (actionServer.isDestroyed()) continue;
92!
379

380
      const properties = actionServer.handle.properties;
92✔
381

382
      if (properties.isGoalRequestReady) {
92✔
383
        this._runWithMessageType(
31✔
384
          actionServer.typeClass.impl.SendGoalService.Request,
385
          (message, deserialize) => {
386
            const result = rclnodejs.actionTakeGoalRequest(
31✔
387
              actionServer.handle,
388
              message
389
            );
390
            if (result) {
31✔
391
              actionServer.processGoalRequest(result, deserialize());
30✔
392
            }
393
          }
394
        );
395
      }
396

397
      if (properties.isCancelRequestReady) {
92✔
398
        this._runWithMessageType(
7✔
399
          actionServer.typeClass.impl.CancelGoal.Request,
400
          (message, deserialize) => {
401
            const result = rclnodejs.actionTakeCancelRequest(
7✔
402
              actionServer.handle,
403
              message
404
            );
405
            if (result) {
7✔
406
              actionServer.processCancelRequest(result, deserialize());
4✔
407
            }
408
          }
409
        );
410
      }
411

412
      if (properties.isResultRequestReady) {
92✔
413
        this._runWithMessageType(
22✔
414
          actionServer.typeClass.impl.GetResultService.Request,
415
          (message, deserialize) => {
416
            const result = rclnodejs.actionTakeResultRequest(
22✔
417
              actionServer.handle,
418
              message
419
            );
420
            if (result) {
22✔
421
              actionServer.processResultRequest(result, deserialize());
15✔
422
            }
423
          }
424
        );
425
      }
426

427
      if (properties.isGoalExpired) {
92✔
428
        let GoalInfoArray = ActionInterfaces.GoalInfo.ArrayType;
4✔
429
        let message = new GoalInfoArray(actionServer._goalHandles.size);
4✔
430
        let count = rclnodejs.actionExpireGoals(
4✔
431
          actionServer.handle,
432
          actionServer._goalHandles.size,
433
          message._refArray.buffer
434
        );
435
        if (count > 0) {
4✔
436
          actionServer.processGoalExpired(message, count);
3✔
437
        }
438
        GoalInfoArray.freeArray(message);
4✔
439
      }
440
    }
441

442
    // At this point it is safe to clear the cache of any
443
    // destroyed entity references
444
    Entity._gcHandles();
9,002✔
445
  }
446

447
  /**
448
   * Determine if this node is spinning.
449
   * @returns {boolean} - true when spinning; otherwise returns false.
450
   */
451
  get spinning() {
452
    return this._spinning;
4,446✔
453
  }
454

455
  /**
456
   * Trigger the event loop to continuously check for and route.
457
   * incoming events.
458
   * @param {Node} node - The node to be spun up.
459
   * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0.
460
   * @throws {Error} If the node is already spinning.
461
   * @return {undefined}
462
   */
463
  spin(timeout = 10) {
17✔
464
    if (this.spinning) {
617!
465
      throw new Error('The node is already spinning.');
×
466
    }
467
    this.start(this.context.handle, timeout);
617✔
468
    this._spinning = true;
617✔
469
  }
470

471
  /**
472
   * Use spin().
473
   * @deprecated, since 0.18.0
474
   */
475
  startSpinning(timeout) {
476
    this.spin(timeout);
×
477
  }
478

479
  /**
480
   * Terminate spinning - no further events will be received.
481
   * @returns {undefined}
482
   */
483
  stop() {
484
    super.stop();
617✔
485
    this._spinning = false;
617✔
486
  }
487

488
  /**
489
   * Terminate spinning - no further events will be received.
490
   * @returns {undefined}
491
   * @deprecated since 0.18.0, Use stop().
492
   */
493
  stopSpinning() {
494
    super.stop();
×
495
    this._spinning = false;
×
496
  }
497

498
  /**
499
   * Spin the node and trigger the event loop to check for one incoming event. Thereafter the node
500
   * will not received additional events until running additional calls to spin() or spinOnce().
501
   * @param {Node} node - The node to be spun.
502
   * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0.
503
   * @throws {Error} If the node is already spinning.
504
   * @return {undefined}
505
   */
506
  spinOnce(timeout = 10) {
2✔
507
    if (this.spinning) {
3,009✔
508
      throw new Error('The node is already spinning.');
2✔
509
    }
510
    super.spinOnce(this.context.handle, timeout);
3,007✔
511
  }
512

513
  _removeEntityFromArray(entity, array) {
514
    let index = array.indexOf(entity);
341✔
515
    if (index > -1) {
341✔
516
      array.splice(index, 1);
339✔
517
    }
518
  }
519

520
  _destroyEntity(entity, array, syncHandles = true) {
287✔
521
    if (entity['isDestroyed'] && entity.isDestroyed()) return;
294✔
522

523
    this._removeEntityFromArray(entity, array);
286✔
524
    if (syncHandles) {
286✔
525
      this.syncHandles();
281✔
526
    }
527

528
    if (entity['_destroy']) {
286✔
529
      entity._destroy();
280✔
530
    } else {
531
      // guards and timers
532
      entity.handle.release();
6✔
533
    }
534
  }
535

536
  _validateOptions(options) {
537
    if (
7,454✔
538
      options !== undefined &&
7,528✔
539
      (options === null || typeof options !== 'object')
540
    ) {
541
      throw new TypeValidationError('options', options, 'object', {
20✔
542
        nodeName: this.name(),
543
      });
544
    }
545

546
    if (options === undefined) {
7,434✔
547
      return Node.getDefaultOptions();
7,407✔
548
    }
549

550
    if (options.enableTypedArray === undefined) {
27✔
551
      options = Object.assign(options, { enableTypedArray: true });
13✔
552
    }
553

554
    if (options.qos === undefined) {
27✔
555
      options = Object.assign(options, { qos: QoS.profileDefault });
13✔
556
    }
557

558
    if (options.isRaw === undefined) {
27✔
559
      options = Object.assign(options, { isRaw: false });
16✔
560
    }
561

562
    if (options.serializationMode === undefined) {
27✔
563
      options = Object.assign(options, { serializationMode: 'default' });
10✔
564
    } else if (!isValidSerializationMode(options.serializationMode)) {
17✔
565
      throw new ValidationError(
1✔
566
        `Invalid serializationMode: ${options.serializationMode}. Valid modes are: 'default', 'plain', 'json'`,
567
        {
568
          code: 'INVALID_SERIALIZATION_MODE',
569
          argumentName: 'serializationMode',
570
          providedValue: options.serializationMode,
571
          expectedType: "'default' | 'plain' | 'json'",
572
          nodeName: this.name(),
573
        }
574
      );
575
    }
576

577
    return options;
26✔
578
  }
579

580
  /**
581
   * Create a Timer.
582
   * @param {bigint} period - The number representing period in nanoseconds.
583
   * @param {function} callback - The callback to be called when timeout.
584
   * @param {Clock} [clock] - The clock which the timer gets time from.
585
   * @return {Timer} - An instance of Timer.
586
   */
587
  createTimer(period, callback, clock = null) {
62✔
588
    if (arguments.length === 3 && !(arguments[2] instanceof Clock)) {
62!
589
      clock = null;
×
590
    } else if (arguments.length === 4) {
62!
591
      clock = arguments[3];
×
592
    }
593

594
    if (typeof period !== 'bigint') {
62✔
595
      throw new TypeValidationError('period', period, 'bigint', {
1✔
596
        nodeName: this.name(),
597
      });
598
    }
599
    if (typeof callback !== 'function') {
61✔
600
      throw new TypeValidationError('callback', callback, 'function', {
1✔
601
        nodeName: this.name(),
602
      });
603
    }
604

605
    const timerClock = clock || this._clock;
60✔
606
    let timerHandle = rclnodejs.createTimer(
60✔
607
      timerClock.handle,
608
      this.context.handle,
609
      period
610
    );
611
    let timer = new Timer(timerHandle, period, callback);
60✔
612
    debug('Finish creating timer, period = %d.', period);
60✔
613
    this._timers.push(timer);
60✔
614
    this.syncHandles();
60✔
615

616
    return timer;
60✔
617
  }
618

619
  /**
620
   * Create a Rate.
621
   *
622
   * @param {number} hz - The frequency of the rate timer; default is 1 hz.
623
   * @returns {Promise<Rate>} - Promise resolving to new instance of Rate.
624
   */
625
  async createRate(hz = 1) {
4✔
626
    if (typeof hz !== 'number') {
9!
627
      throw new TypeValidationError('hz', hz, 'number', {
×
628
        nodeName: this.name(),
629
      });
630
    }
631

632
    const MAX_RATE_HZ_IN_MILLISECOND = 1000.0;
9✔
633
    if (hz <= 0.0 || hz > MAX_RATE_HZ_IN_MILLISECOND) {
9✔
634
      throw new RangeValidationError(
2✔
635
        'hz',
636
        hz,
637
        `0.0 < hz <= ${MAX_RATE_HZ_IN_MILLISECOND}`,
638
        {
639
          nodeName: this.name(),
640
        }
641
      );
642
    }
643

644
    // lazy initialize rateTimerServer
645
    if (!this._rateTimerServer) {
7✔
646
      this._rateTimerServer = new Rates.RateTimerServer(this);
5✔
647
      await this._rateTimerServer.init();
5✔
648
    }
649

650
    const period = Math.round(1000 / hz);
7✔
651
    const timer = this._rateTimerServer.createTimer(BigInt(period) * 1000000n);
7✔
652
    const rate = new Rates.Rate(hz, timer);
7✔
653

654
    return rate;
7✔
655
  }
656

657
  /**
658
   * Create a Publisher.
659
   * @param {function|string|object} typeClass - The ROS message class,
660
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
661
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
662
   * @param {string} topic - The name of the topic.
663
   * @param {object} options - The options argument used to parameterize the publisher.
664
   * @param {boolean} options.enableTypedArray - The topic will use TypedArray if necessary, default: true.
665
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the publisher, default: QoS.profileDefault.
666
   * @param {PublisherEventCallbacks} eventCallbacks - The event callbacks for the publisher.
667
   * @return {Publisher} - An instance of Publisher.
668
   */
669
  createPublisher(typeClass, topic, options, eventCallbacks) {
670
    return this._createPublisher(
1,164✔
671
      typeClass,
672
      topic,
673
      options,
674
      Publisher,
675
      eventCallbacks
676
    );
677
  }
678

679
  _createPublisher(typeClass, topic, options, publisherClass, eventCallbacks) {
680
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
1,167✔
681
      typeClass = loader.loadInterface(typeClass);
1,143✔
682
    }
683
    options = this._validateOptions(options);
1,160✔
684

685
    if (typeof typeClass !== 'function') {
1,160✔
686
      throw new TypeValidationError('typeClass', typeClass, 'function', {
8✔
687
        nodeName: this.name(),
688
        entityType: 'publisher',
689
      });
690
    }
691
    if (typeof topic !== 'string') {
1,152✔
692
      throw new TypeValidationError('topic', topic, 'string', {
12✔
693
        nodeName: this.name(),
694
        entityType: 'publisher',
695
      });
696
    }
697
    if (
1,140!
698
      eventCallbacks &&
1,142✔
699
      !(eventCallbacks instanceof PublisherEventCallbacks)
700
    ) {
701
      throw new TypeValidationError(
×
702
        'eventCallbacks',
703
        eventCallbacks,
704
        'PublisherEventCallbacks',
705
        {
706
          nodeName: this.name(),
707
          entityType: 'publisher',
708
          entityName: topic,
709
        }
710
      );
711
    }
712

713
    let publisher = publisherClass.createPublisher(
1,140✔
714
      this,
715
      typeClass,
716
      topic,
717
      options,
718
      eventCallbacks
719
    );
720
    debug('Finish creating publisher, topic = %s.', topic);
1,130✔
721
    this._publishers.push(publisher);
1,130✔
722
    return publisher;
1,130✔
723
  }
724

725
  /**
726
   * This callback is called when a message is published
727
   * @callback SubscriptionCallback
728
   * @param {Object} message - The message published
729
   * @see [Node.createSubscription]{@link Node#createSubscription}
730
   * @see [Node.createPublisher]{@link Node#createPublisher}
731
   * @see {@link Publisher}
732
   * @see {@link Subscription}
733
   */
734

735
  /**
736
   * Create a Subscription with optional content-filtering.
737
   * @param {function|string|object} typeClass - The ROS message class,
738
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
739
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
740
   * @param {string} topic - The name of the topic.
741
   * @param {object} options - The options argument used to parameterize the subscription.
742
   * @param {boolean} options.enableTypedArray - The topic will use TypedArray if necessary, default: true.
743
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the subscription, default: QoS.profileDefault.
744
   * @param {boolean} options.isRaw - The topic is serialized when true, default: false.
745
   * @param {string} [options.serializationMode='default'] - Controls message serialization format:
746
   *  'default': Use native rclnodejs behavior (respects enableTypedArray setting),
747
   *  'plain': Convert TypedArrays to regular arrays,
748
   *  'json': Fully JSON-safe (handles TypedArrays, BigInt, etc.).
749
   * @param {object} [options.contentFilter=undefined] - The content-filter, default: undefined.
750
   *  Confirm that your RMW supports content-filtered topics before use. 
751
   * @param {string} options.contentFilter.expression - Specifies the criteria to select the data samples of
752
   *  interest. It is similar to the WHERE part of an SQL clause.
753
   * @param {string[]} [options.contentFilter.parameters=undefined] - Array of strings that give values to
754
   *  the ‘parameters’ (i.e., "%n" tokens) in the filter_expression. The number of supplied parameters must
755
   *  fit with the requested values in the filter_expression (i.e., the number of %n tokens). default: undefined.
756
   * @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.
757
   * @param {SubscriptionEventCallbacks} eventCallbacks - The event callbacks for the subscription.
758
   * @return {Subscription} - An instance of Subscription.
759
   * @throws {ERROR} - May throw an RMW error if content-filter is malformed. 
760
   * @see {@link SubscriptionCallback}
761
   * @see {@link https://www.omg.org/spec/DDS/1.4/PDF|Content-filter details at DDS 1.4 specification, Annex B}
762
   */
763
  createSubscription(typeClass, topic, options, callback, eventCallbacks) {
764
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
427✔
765
      typeClass = loader.loadInterface(typeClass);
418✔
766
    }
767

768
    if (typeof options === 'function') {
420✔
769
      callback = options;
379✔
770
      options = undefined;
379✔
771
    }
772
    options = this._validateOptions(options);
420✔
773

774
    if (typeof typeClass !== 'function') {
410✔
775
      throw new TypeValidationError('typeClass', typeClass, 'function', {
4✔
776
        nodeName: this.name(),
777
        entityType: 'subscription',
778
      });
779
    }
780
    if (typeof topic !== 'string') {
406✔
781
      throw new TypeValidationError('topic', topic, 'string', {
6✔
782
        nodeName: this.name(),
783
        entityType: 'subscription',
784
      });
785
    }
786
    if (typeof callback !== 'function') {
400!
787
      throw new TypeValidationError('callback', callback, 'function', {
×
788
        nodeName: this.name(),
789
        entityType: 'subscription',
790
        entityName: topic,
791
      });
792
    }
793
    if (
400!
794
      eventCallbacks &&
404✔
795
      !(eventCallbacks instanceof SubscriptionEventCallbacks)
796
    ) {
797
      throw new TypeValidationError(
×
798
        'eventCallbacks',
799
        eventCallbacks,
800
        'SubscriptionEventCallbacks',
801
        {
802
          nodeName: this.name(),
803
          entityType: 'subscription',
804
          entityName: topic,
805
        }
806
      );
807
    }
808

809
    let subscription = Subscription.createSubscription(
400✔
810
      this,
811
      typeClass,
812
      topic,
813
      options,
814
      callback,
815
      eventCallbacks
816
    );
817
    debug('Finish creating subscription, topic = %s.', topic);
389✔
818
    this._subscriptions.push(subscription);
389✔
819
    this.syncHandles();
389✔
820

821
    return subscription;
389✔
822
  }
823

824
  /**
825
   * Create a Subscription that returns an RxJS Observable.
826
   * This allows using reactive programming patterns with ROS 2 messages.
827
   *
828
   * @param {function|string|object} typeClass - The ROS message class,
829
   *      OR a string representing the message class, e.g. 'std_msgs/msg/String',
830
   *      OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
831
   * @param {string} topic - The name of the topic.
832
   * @param {object} [options] - The options argument used to parameterize the subscription.
833
   * @param {boolean} [options.enableTypedArray=true] - The topic will use TypedArray if necessary.
834
   * @param {QoS} [options.qos=QoS.profileDefault] - ROS Middleware "quality of service" settings.
835
   * @param {boolean} [options.isRaw=false] - The topic is serialized when true.
836
   * @param {string} [options.serializationMode='default'] - Controls message serialization format.
837
   * @param {object} [options.contentFilter] - The content-filter (if supported by RMW).
838
   * @param {SubscriptionEventCallbacks} [eventCallbacks] - The event callbacks for the subscription.
839
   * @return {ObservableSubscription} - An ObservableSubscription with an RxJS Observable.
840
   */
841
  createObservableSubscription(typeClass, topic, options, eventCallbacks) {
842
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
7!
843
      typeClass = loader.loadInterface(typeClass);
7✔
844
    }
845

846
    options = this._validateOptions(options);
7✔
847

848
    if (typeof typeClass !== 'function') {
7!
NEW
849
      throw new TypeValidationError('typeClass', typeClass, 'function', {
×
850
        nodeName: this.name(),
851
        entityType: 'subscription',
852
      });
853
    }
854
    if (typeof topic !== 'string') {
7!
NEW
855
      throw new TypeValidationError('topic', topic, 'string', {
×
856
        nodeName: this.name(),
857
        entityType: 'subscription',
858
      });
859
    }
860
    if (
7!
861
      eventCallbacks &&
7!
862
      !(eventCallbacks instanceof SubscriptionEventCallbacks)
863
    ) {
NEW
UNCOV
864
      throw new TypeValidationError(
×
865
        'eventCallbacks',
866
        eventCallbacks,
867
        'SubscriptionEventCallbacks',
868
        {
869
          nodeName: this.name(),
870
          entityType: 'subscription',
871
          entityName: topic,
872
        }
873
      );
874
    }
875

876
    let observableSubscription = null;
7✔
877

878
    const subscription = Subscription.createSubscription(
7✔
879
      this,
880
      typeClass,
881
      topic,
882
      options,
883
      (message) => {
884
        if (observableSubscription) {
8!
885
          observableSubscription._emit(message);
8✔
886
        }
887
      },
888
      eventCallbacks
889
    );
890

891
    observableSubscription = new ObservableSubscription(subscription);
7✔
892

893
    debug('Finish creating observable subscription, topic = %s.', topic);
7✔
894
    this._subscriptions.push(subscription);
7✔
895
    this.syncHandles();
7✔
896

897
    return observableSubscription;
7✔
898
  }
899

900
  /**
901
   * Create a Client.
902
   * @param {function|string|object} typeClass - The ROS message class,
903
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
904
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
905
   * @param {string} serviceName - The service name to request.
906
   * @param {object} options - The options argument used to parameterize the client.
907
   * @param {boolean} options.enableTypedArray - The response will use TypedArray if necessary, default: true.
908
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the client, default: QoS.profileDefault.
909
   * @return {Client} - An instance of Client.
910
   */
911
  createClient(typeClass, serviceName, options) {
912
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
196✔
913
      typeClass = loader.loadInterface(typeClass);
186✔
914
    }
915
    options = this._validateOptions(options);
189✔
916

917
    if (typeof typeClass !== 'function') {
189✔
918
      throw new TypeValidationError('typeClass', typeClass, 'function', {
8✔
919
        nodeName: this.name(),
920
        entityType: 'client',
921
      });
922
    }
923
    if (typeof serviceName !== 'string') {
181✔
924
      throw new TypeValidationError('serviceName', serviceName, 'string', {
12✔
925
        nodeName: this.name(),
926
        entityType: 'client',
927
      });
928
    }
929

930
    let client = Client.createClient(
169✔
931
      this.handle,
932
      serviceName,
933
      typeClass,
934
      options
935
    );
936
    debug('Finish creating client, service = %s.', serviceName);
159✔
937
    this._clients.push(client);
159✔
938
    this.syncHandles();
159✔
939

940
    return client;
159✔
941
  }
942

943
  /**
944
   * This callback is called when a request is sent to service
945
   * @callback RequestCallback
946
   * @param {Object} request - The request sent to the service
947
   * @param {Response} response - The response to client.
948
        Use [response.send()]{@link Response#send} to send response object to client
949
   * @return {undefined}
950
   * @see [Node.createService]{@link Node#createService}
951
   * @see [Client.sendRequest]{@link Client#sendRequest}
952
   * @see {@link Client}
953
   * @see {@link Service}
954
   * @see {@link Response#send}
955
   */
956

957
  /**
958
   * Create a Service.
959
   * @param {function|string|object} typeClass - The ROS message class,
960
        OR a string representing the message class, e.g. 'std_msgs/msg/String',
961
        OR an object representing the message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'}
962
   * @param {string} serviceName - The service name to offer.
963
   * @param {object} options - The options argument used to parameterize the service.
964
   * @param {boolean} options.enableTypedArray - The request will use TypedArray if necessary, default: true.
965
   * @param {QoS} options.qos - ROS Middleware "quality of service" settings for the service, default: QoS.profileDefault.
966
   * @param {RequestCallback} callback - The callback to be called when receiving request.
967
   * @return {Service} - An instance of Service.
968
   * @see {@link RequestCallback}
969
   */
970
  createService(typeClass, serviceName, options, callback) {
971
    if (typeof typeClass === 'string' || typeof typeClass === 'object') {
4,813✔
972
      typeClass = loader.loadInterface(typeClass);
4,803✔
973
    }
974

975
    if (typeof options === 'function') {
4,806✔
976
      callback = options;
4,783✔
977
      options = undefined;
4,783✔
978
    }
979
    options = this._validateOptions(options);
4,806✔
980

981
    if (typeof typeClass !== 'function') {
4,796✔
982
      throw new TypeValidationError('typeClass', typeClass, 'function', {
4✔
983
        nodeName: this.name(),
984
        entityType: 'service',
985
      });
986
    }
987
    if (typeof serviceName !== 'string') {
4,792✔
988
      throw new TypeValidationError('serviceName', serviceName, 'string', {
6✔
989
        nodeName: this.name(),
990
        entityType: 'service',
991
      });
992
    }
993
    if (typeof callback !== 'function') {
4,786!
UNCOV
994
      throw new TypeValidationError('callback', callback, 'function', {
×
995
        nodeName: this.name(),
996
        entityType: 'service',
997
        entityName: serviceName,
998
      });
999
    }
1000

1001
    let service = Service.createService(
4,786✔
1002
      this.handle,
1003
      serviceName,
1004
      typeClass,
1005
      options,
1006
      callback
1007
    );
1008
    debug('Finish creating service, service = %s.', serviceName);
4,776✔
1009
    this._services.push(service);
4,776✔
1010
    this.syncHandles();
4,776✔
1011

1012
    return service;
4,776✔
1013
  }
1014

1015
  /**
1016
   * Create a ParameterClient for accessing parameters on a remote node.
1017
   * @param {string} remoteNodeName - The name of the remote node whose parameters to access.
1018
   * @param {object} [options] - Options for parameter client.
1019
   * @param {number} [options.timeout=5000] - Default timeout in milliseconds for service calls.
1020
   * @return {ParameterClient} - An instance of ParameterClient.
1021
   */
1022
  createParameterClient(remoteNodeName, options = {}) {
50✔
1023
    if (typeof remoteNodeName !== 'string' || remoteNodeName.trim() === '') {
103!
UNCOV
1024
      throw new TypeError('Remote node name must be a non-empty string');
×
1025
    }
1026

1027
    const parameterClient = new ParameterClient(this, remoteNodeName, options);
103✔
1028
    debug(
103✔
1029
      'Finish creating parameter client for remote node = %s.',
1030
      remoteNodeName
1031
    );
1032
    this._parameterClients.push(parameterClient);
103✔
1033

1034
    return parameterClient;
103✔
1035
  }
1036

1037
  /**
1038
   * Create a ParameterWatcher for watching parameter changes on a remote node.
1039
   * @param {string} remoteNodeName - The name of the remote node whose parameters to watch.
1040
   * @param {string[]} parameterNames - Array of parameter names to watch.
1041
   * @param {object} [options] - Options for parameter watcher.
1042
   * @param {number} [options.timeout=5000] - Default timeout in milliseconds for service calls.
1043
   * @return {ParameterWatcher} - An instance of ParameterWatcher.
1044
   */
1045
  createParameterWatcher(remoteNodeName, parameterNames, options = {}) {
56✔
1046
    const watcher = new ParameterWatcher(
57✔
1047
      this,
1048
      remoteNodeName,
1049
      parameterNames,
1050
      options
1051
    );
1052
    debug(
53✔
1053
      'Finish creating parameter watcher for remote node = %s.',
1054
      remoteNodeName
1055
    );
1056
    this._parameterWatchers.push(watcher);
53✔
1057

1058
    return watcher;
53✔
1059
  }
1060

1061
  /**
1062
   * Create a guard condition.
1063
   * @param {Function} callback - The callback to be called when the guard condition is triggered.
1064
   * @return {GuardCondition} - An instance of GuardCondition.
1065
   */
1066
  createGuardCondition(callback) {
1067
    if (typeof callback !== 'function') {
3!
UNCOV
1068
      throw new TypeValidationError('callback', callback, 'function', {
×
1069
        nodeName: this.name(),
1070
        entityType: 'guard_condition',
1071
      });
1072
    }
1073

1074
    let guard = GuardCondition.createGuardCondition(callback, this.context);
3✔
1075
    debug('Finish creating guard condition');
3✔
1076
    this._guards.push(guard);
3✔
1077
    this.syncHandles();
3✔
1078

1079
    return guard;
3✔
1080
  }
1081

1082
  /**
1083
   * Destroy all resource allocated by this node, including
1084
   * <code>Timer</code>s/<code>Publisher</code>s/<code>Subscription</code>s
1085
   * /<code>Client</code>s/<code>Service</code>s
1086
   * @return {undefined}
1087
   */
1088
  destroy() {
1089
    if (this.spinning) {
818✔
1090
      this.stop();
534✔
1091
    }
1092

1093
    // Action servers/clients require manual destruction due to circular reference with goal handles.
1094
    this._actionClients.forEach((actionClient) => actionClient.destroy());
818✔
1095
    this._actionServers.forEach((actionServer) => actionServer.destroy());
818✔
1096

1097
    this._parameterClients.forEach((paramClient) => paramClient.destroy());
818✔
1098
    this._parameterWatchers.forEach((watcher) => watcher.destroy());
818✔
1099

1100
    this.context.onNodeDestroyed(this);
818✔
1101

1102
    if (this._enableRosout) {
818✔
1103
      rclnodejs.finiRosoutPublisherForNode(this.handle);
795✔
1104
      this._enableRosout = false;
795✔
1105
    }
1106

1107
    this.handle.release();
818✔
1108
    this._clock = null;
818✔
1109
    this._timers = [];
818✔
1110
    this._publishers = [];
818✔
1111
    this._subscriptions = [];
818✔
1112
    this._clients = [];
818✔
1113
    this._services = [];
818✔
1114
    this._guards = [];
818✔
1115
    this._actionClients = [];
818✔
1116
    this._actionServers = [];
818✔
1117
    this._parameterClients = [];
818✔
1118
    this._parameterWatchers = [];
818✔
1119

1120
    if (this._rateTimerServer) {
818✔
1121
      this._rateTimerServer.shutdown();
5✔
1122
      this._rateTimerServer = null;
5✔
1123
    }
1124
  }
1125

1126
  /**
1127
   * Destroy a Publisher.
1128
   * @param {Publisher} publisher - The Publisher to be destroyed.
1129
   * @return {undefined}
1130
   */
1131
  destroyPublisher(publisher) {
1132
    if (!(publisher instanceof Publisher)) {
9✔
1133
      throw new TypeValidationError(
2✔
1134
        'publisher',
1135
        publisher,
1136
        'Publisher instance',
1137
        {
1138
          nodeName: this.name(),
1139
        }
1140
      );
1141
    }
1142
    if (publisher.events) {
7!
UNCOV
1143
      publisher.events.forEach((event) => {
×
UNCOV
1144
        this._destroyEntity(event, this._events);
×
1145
      });
UNCOV
1146
      publisher.events = [];
×
1147
    }
1148
    this._destroyEntity(publisher, this._publishers, false);
7✔
1149
  }
1150

1151
  /**
1152
   * Destroy a Subscription.
1153
   * @param {Subscription} subscription - The Subscription to be destroyed.
1154
   * @return {undefined}
1155
   */
1156
  destroySubscription(subscription) {
1157
    if (!(subscription instanceof Subscription)) {
82✔
1158
      throw new TypeValidationError(
2✔
1159
        'subscription',
1160
        subscription,
1161
        'Subscription instance',
1162
        {
1163
          nodeName: this.name(),
1164
        }
1165
      );
1166
    }
1167
    if (subscription.events) {
80✔
1168
      subscription.events.forEach((event) => {
1✔
1169
        this._destroyEntity(event, this._events);
1✔
1170
      });
1171
      subscription.events = [];
1✔
1172
    }
1173

1174
    this._destroyEntity(subscription, this._subscriptions);
80✔
1175
  }
1176

1177
  /**
1178
   * Destroy a Client.
1179
   * @param {Client} client - The Client to be destroyed.
1180
   * @return {undefined}
1181
   */
1182
  destroyClient(client) {
1183
    if (!(client instanceof Client)) {
117✔
1184
      throw new TypeValidationError('client', client, 'Client instance', {
2✔
1185
        nodeName: this.name(),
1186
      });
1187
    }
1188
    this._destroyEntity(client, this._clients);
115✔
1189
  }
1190

1191
  /**
1192
   * Destroy a Service.
1193
   * @param {Service} service - The Service to be destroyed.
1194
   * @return {undefined}
1195
   */
1196
  destroyService(service) {
1197
    if (!(service instanceof Service)) {
8✔
1198
      throw new TypeValidationError('service', service, 'Service instance', {
2✔
1199
        nodeName: this.name(),
1200
      });
1201
    }
1202
    this._destroyEntity(service, this._services);
6✔
1203
  }
1204

1205
  /**
1206
   * Destroy a ParameterClient.
1207
   * @param {ParameterClient} parameterClient - The ParameterClient to be destroyed.
1208
   * @return {undefined}
1209
   */
1210
  destroyParameterClient(parameterClient) {
1211
    if (!(parameterClient instanceof ParameterClient)) {
54!
1212
      throw new TypeError('Invalid argument');
×
1213
    }
1214
    this._removeEntityFromArray(parameterClient, this._parameterClients);
54✔
1215
    parameterClient.destroy();
54✔
1216
  }
1217

1218
  /**
1219
   * Destroy a ParameterWatcher.
1220
   * @param {ParameterWatcher} watcher - The ParameterWatcher to be destroyed.
1221
   * @return {undefined}
1222
   */
1223
  destroyParameterWatcher(watcher) {
1224
    if (!(watcher instanceof ParameterWatcher)) {
1!
UNCOV
1225
      throw new TypeError('Invalid argument');
×
1226
    }
1227
    this._removeEntityFromArray(watcher, this._parameterWatchers);
1✔
1228
    watcher.destroy();
1✔
1229
  }
1230

1231
  /**
1232
   * Destroy a Timer.
1233
   * @param {Timer} timer - The Timer to be destroyed.
1234
   * @return {undefined}
1235
   */
1236
  destroyTimer(timer) {
1237
    if (!(timer instanceof Timer)) {
8✔
1238
      throw new TypeValidationError('timer', timer, 'Timer instance', {
2✔
1239
        nodeName: this.name(),
1240
      });
1241
    }
1242
    this._destroyEntity(timer, this._timers);
6✔
1243
  }
1244

1245
  /**
1246
   * Destroy a guard condition.
1247
   * @param {GuardCondition} guard - The guard condition to be destroyed.
1248
   * @return {undefined}
1249
   */
1250
  destroyGuardCondition(guard) {
1251
    if (!(guard instanceof GuardCondition)) {
3!
UNCOV
1252
      throw new TypeValidationError('guard', guard, 'GuardCondition instance', {
×
1253
        nodeName: this.name(),
1254
      });
1255
    }
1256
    this._destroyEntity(guard, this._guards);
3✔
1257
  }
1258

1259
  /**
1260
   * Get the name of the node.
1261
   * @return {string}
1262
   */
1263
  name() {
1264
    return rclnodejs.getNodeName(this.handle);
4,709✔
1265
  }
1266

1267
  /**
1268
   * Get the namespace of the node.
1269
   * @return {string}
1270
   */
1271
  namespace() {
1272
    return rclnodejs.getNamespace(this.handle);
4,434✔
1273
  }
1274

1275
  /**
1276
   * Get the context in which this node was created.
1277
   * @return {Context}
1278
   */
1279
  get context() {
1280
    return this._context;
6,097✔
1281
  }
1282

1283
  /**
1284
   * Get the nodes logger.
1285
   * @returns {Logger} - The logger for the node.
1286
   */
1287
  getLogger() {
1288
    return this._logger;
141✔
1289
  }
1290

1291
  /**
1292
   * Get the clock used by the node.
1293
   * @returns {Clock} - The nodes clock.
1294
   */
1295
  getClock() {
1296
    return this._clock;
86✔
1297
  }
1298

1299
  /**
1300
   * Get the current time using the node's clock.
1301
   * @returns {Timer} - The current time.
1302
   */
1303
  now() {
1304
    return this.getClock().now();
2✔
1305
  }
1306

1307
  /**
1308
   * Get the list of published topics discovered by the provided node for the remote node name.
1309
   * @param {string} nodeName - The name of the node.
1310
   * @param {string} namespace - The name of the namespace.
1311
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
1312
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1313
   */
1314
  getPublisherNamesAndTypesByNode(nodeName, namespace, noDemangle = false) {
2✔
1315
    return rclnodejs.getPublisherNamesAndTypesByNode(
2✔
1316
      this.handle,
1317
      nodeName,
1318
      namespace,
1319
      noDemangle
1320
    );
1321
  }
1322

1323
  /**
1324
   * Get the list of published topics discovered by the provided node for the remote node name.
1325
   * @param {string} nodeName - The name of the node.
1326
   * @param {string} namespace - The name of the namespace.
1327
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
1328
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1329
   */
1330
  getSubscriptionNamesAndTypesByNode(nodeName, namespace, noDemangle = false) {
×
UNCOV
1331
    return rclnodejs.getSubscriptionNamesAndTypesByNode(
×
1332
      this.handle,
1333
      nodeName,
1334
      namespace,
1335
      noDemangle
1336
    );
1337
  }
1338

1339
  /**
1340
   * Get service names and types for which a remote node has servers.
1341
   * @param {string} nodeName - The name of the node.
1342
   * @param {string} namespace - The name of the namespace.
1343
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1344
   */
1345
  getServiceNamesAndTypesByNode(nodeName, namespace) {
UNCOV
1346
    return rclnodejs.getServiceNamesAndTypesByNode(
×
1347
      this.handle,
1348
      nodeName,
1349
      namespace
1350
    );
1351
  }
1352

1353
  /**
1354
   * Get service names and types for which a remote node has clients.
1355
   * @param {string} nodeName - The name of the node.
1356
   * @param {string} namespace - The name of the namespace.
1357
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1358
   */
1359
  getClientNamesAndTypesByNode(nodeName, namespace) {
UNCOV
1360
    return rclnodejs.getClientNamesAndTypesByNode(
×
1361
      this.handle,
1362
      nodeName,
1363
      namespace
1364
    );
1365
  }
1366

1367
  /**
1368
   * Get the list of topics discovered by the provided node.
1369
   * @param {boolean} noDemangle - If true topic names and types returned will not be demangled, default: false.
1370
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1371
   */
1372
  getTopicNamesAndTypes(noDemangle = false) {
×
UNCOV
1373
    return rclnodejs.getTopicNamesAndTypes(this.handle, noDemangle);
×
1374
  }
1375

1376
  /**
1377
   * Get the list of services discovered by the provided node.
1378
   * @return {Array<{name: string, types: Array<string>}>} - An array of the names and types.
1379
   */
1380
  getServiceNamesAndTypes() {
1381
    return rclnodejs.getServiceNamesAndTypes(this.handle);
2✔
1382
  }
1383

1384
  /**
1385
   * Return a list of publishers on a given topic.
1386
   *
1387
   * The returned parameter is a list of TopicEndpointInfo objects, where each will contain
1388
   * the node name, node namespace, topic type, topic endpoint's GID, and its QoS profile.
1389
   *
1390
   * When the `no_mangle` parameter is `true`, the provided `topic` should be a valid
1391
   * topic name for the middleware (useful when combining ROS with native middleware (e.g. DDS)
1392
   * apps).  When the `no_mangle` parameter is `false`, the provided `topic` should
1393
   * follow ROS topic name conventions.
1394
   *
1395
   * `topic` may be a relative, private, or fully qualified topic name.
1396
   *  A relative or private topic will be expanded using this node's namespace and name.
1397
   *  The queried `topic` is not remapped.
1398
   *
1399
   * @param {string} topic - The topic on which to find the publishers.
1400
   * @param {boolean} [noDemangle=false] - If `true`, `topic` needs to be a valid middleware topic
1401
   *                               name, otherwise it should be a valid ROS topic name. Defaults to `false`.
1402
   * @returns {Array} - list of publishers
1403
   */
1404
  getPublishersInfoByTopic(topic, noDemangle = false) {
1✔
1405
    return rclnodejs.getPublishersInfoByTopic(
4✔
1406
      this.handle,
1407
      this._getValidatedTopic(topic, noDemangle),
1408
      noDemangle
1409
    );
1410
  }
1411

1412
  /**
1413
   * Return a list of subscriptions on a given topic.
1414
   *
1415
   * The returned parameter is a list of TopicEndpointInfo objects, where each will contain
1416
   * the node name, node namespace, topic type, topic endpoint's GID, and its QoS profile.
1417
   *
1418
   * When the `no_mangle` parameter is `true`, the provided `topic` should be a valid
1419
   * topic name for the middleware (useful when combining ROS with native middleware (e.g. DDS)
1420
   * apps).  When the `no_mangle` parameter is `false`, the provided `topic` should
1421
   * follow ROS topic name conventions.
1422
   *
1423
   * `topic` may be a relative, private, or fully qualified topic name.
1424
   *  A relative or private topic will be expanded using this node's namespace and name.
1425
   *  The queried `topic` is not remapped.
1426
   *
1427
   * @param {string} topic - The topic on which to find the subscriptions.
1428
   * @param {boolean} [noDemangle=false] -  If `true`, `topic` needs to be a valid middleware topic
1429
                                    name, otherwise it should be a valid ROS topic name. Defaults to `false`.
1430
   * @returns {Array} - list of subscriptions
1431
   */
1432
  getSubscriptionsInfoByTopic(topic, noDemangle = false) {
×
1433
    return rclnodejs.getSubscriptionsInfoByTopic(
2✔
1434
      this.handle,
1435
      this._getValidatedTopic(topic, noDemangle),
1436
      noDemangle
1437
    );
1438
  }
1439

1440
  /**
1441
   * Return a list of clients on a given service.
1442
   *
1443
   * The returned parameter is a list of ServiceEndpointInfo objects, where each will contain
1444
   * the node name, node namespace, service type, service endpoint's GID, and its QoS profile.
1445
   *
1446
   * When the `no_mangle` parameter is `true`, the provided `service` should be a valid
1447
   * service name for the middleware (useful when combining ROS with native middleware (e.g. DDS)
1448
   * apps).  When the `no_mangle` parameter is `false`, the provided `service` should
1449
   * follow ROS service name conventions.
1450
   *
1451
   * `service` may be a relative, private, or fully qualified service name.
1452
   *  A relative or private service will be expanded using this node's namespace and name.
1453
   *  The queried `service` is not remapped.
1454
   *
1455
   * @param {string} service - The service on which to find the clients.
1456
   * @param {boolean} [noDemangle=false] - If `true`, `service` needs to be a valid middleware service
1457
   *                               name, otherwise it should be a valid ROS service name. Defaults to `false`.
1458
   * @returns {Array} - list of clients
1459
   */
1460
  getClientsInfoByService(service, noDemangle = false) {
×
1461
    if (DistroUtils.getDistroId() < DistroUtils.DistroId.ROLLING) {
2!
UNCOV
1462
      console.warn(
×
1463
        'getClientsInfoByService is not supported by this version of ROS 2'
1464
      );
UNCOV
1465
      return null;
×
1466
    }
1467
    return rclnodejs.getClientsInfoByService(
2✔
1468
      this.handle,
1469
      this._getValidatedServiceName(service, noDemangle),
1470
      noDemangle
1471
    );
1472
  }
1473

1474
  /**
1475
   * Return a list of servers on a given service.
1476
   *
1477
   * The returned parameter is a list of ServiceEndpointInfo objects, where each will contain
1478
   * the node name, node namespace, service type, service endpoint's GID, and its QoS profile.
1479
   *
1480
   * When the `no_mangle` parameter is `true`, the provided `service` should be a valid
1481
   * service name for the middleware (useful when combining ROS with native middleware (e.g. DDS)
1482
   * apps).  When the `no_mangle` parameter is `false`, the provided `service` should
1483
   * follow ROS service name conventions.
1484
   *
1485
   * `service` may be a relative, private, or fully qualified service name.
1486
   *  A relative or private service will be expanded using this node's namespace and name.
1487
   *  The queried `service` is not remapped.
1488
   *
1489
   * @param {string} service - The service on which to find the servers.
1490
   * @param {boolean} [noDemangle=false] - If `true`, `service` needs to be a valid middleware service
1491
   *                               name, otherwise it should be a valid ROS service name. Defaults to `false`.
1492
   * @returns {Array} - list of servers
1493
   */
1494
  getServersInfoByService(service, noDemangle = false) {
×
1495
    if (DistroUtils.getDistroId() < DistroUtils.DistroId.ROLLING) {
2!
UNCOV
1496
      console.warn(
×
1497
        'getServersInfoByService is not supported by this version of ROS 2'
1498
      );
UNCOV
1499
      return null;
×
1500
    }
1501
    return rclnodejs.getServersInfoByService(
2✔
1502
      this.handle,
1503
      this._getValidatedServiceName(service, noDemangle),
1504
      noDemangle
1505
    );
1506
  }
1507

1508
  /**
1509
   * Get the list of nodes discovered by the provided node.
1510
   * @return {Array<string>} - An array of the names.
1511
   */
1512
  getNodeNames() {
1513
    return this.getNodeNamesAndNamespaces().map((item) => item.name);
41✔
1514
  }
1515

1516
  /**
1517
   * Get the list of nodes and their namespaces discovered by the provided node.
1518
   * @return {Array<{name: string, namespace: string}>} An array of the names and namespaces.
1519
   */
1520
  getNodeNamesAndNamespaces() {
1521
    return rclnodejs.getNodeNames(this.handle, /*getEnclaves=*/ false);
17✔
1522
  }
1523

1524
  /**
1525
   * Get the list of nodes and their namespaces with enclaves discovered by the provided node.
1526
   * @return {Array<{name: string, namespace: string, enclave: string}>} An array of the names, namespaces and enclaves.
1527
   */
1528
  getNodeNamesAndNamespacesWithEnclaves() {
1529
    return rclnodejs.getNodeNames(this.handle, /*getEnclaves=*/ true);
1✔
1530
  }
1531

1532
  /**
1533
   * Return the number of publishers on a given topic.
1534
   * @param {string} topic - The name of the topic.
1535
   * @returns {number} - Number of publishers on the given topic.
1536
   */
1537
  countPublishers(topic) {
1538
    let expandedTopic = rclnodejs.expandTopicName(
6✔
1539
      topic,
1540
      this.name(),
1541
      this.namespace()
1542
    );
1543
    rclnodejs.validateTopicName(expandedTopic);
6✔
1544

1545
    return rclnodejs.countPublishers(this.handle, expandedTopic);
6✔
1546
  }
1547

1548
  /**
1549
   * Return the number of subscribers on a given topic.
1550
   * @param {string} topic - The name of the topic.
1551
   * @returns {number} - Number of subscribers on the given topic.
1552
   */
1553
  countSubscribers(topic) {
1554
    let expandedTopic = rclnodejs.expandTopicName(
6✔
1555
      topic,
1556
      this.name(),
1557
      this.namespace()
1558
    );
1559
    rclnodejs.validateTopicName(expandedTopic);
6✔
1560

1561
    return rclnodejs.countSubscribers(this.handle, expandedTopic);
6✔
1562
  }
1563

1564
  /**
1565
   * Get the number of clients on a given service name.
1566
   * @param {string} serviceName - the service name
1567
   * @returns {Number}
1568
   */
1569
  countClients(serviceName) {
1570
    if (DistroUtils.getDistroId() <= DistroUtils.getDistroId('humble')) {
2!
UNCOV
1571
      console.warn('countClients is not supported by this version of ROS 2');
×
UNCOV
1572
      return null;
×
1573
    }
1574
    return rclnodejs.countClients(this.handle, serviceName);
2✔
1575
  }
1576

1577
  /**
1578
   * Get the number of services on a given service name.
1579
   * @param {string} serviceName - the service name
1580
   * @returns {Number}
1581
   */
1582
  countServices(serviceName) {
1583
    if (DistroUtils.getDistroId() <= DistroUtils.getDistroId('humble')) {
1!
UNCOV
1584
      console.warn('countServices is not supported by this version of ROS 2');
×
UNCOV
1585
      return null;
×
1586
    }
1587
    return rclnodejs.countServices(this.handle, serviceName);
1✔
1588
  }
1589

1590
  /**
1591
   * Get the list of parameter-overrides found on the commandline and
1592
   * in the NodeOptions.parameter_overrides property.
1593
   *
1594
   * @return {Array<Parameter>} - An array of Parameters.
1595
   */
1596
  getParameterOverrides() {
1597
    return Array.from(this._parameterOverrides.values());
8✔
1598
  }
1599

1600
  /**
1601
   * Declare a parameter.
1602
   *
1603
   * Internally, register a parameter and it's descriptor.
1604
   * If a parameter-override exists, it's value will replace that of the parameter
1605
   * unless ignoreOverride is true.
1606
   * If the descriptor is undefined, then a ParameterDescriptor will be inferred
1607
   * from the parameter's state.
1608
   *
1609
   * If a parameter by the same name has already been declared then an Error is thrown.
1610
   * A parameter must be undeclared before attempting to redeclare it.
1611
   *
1612
   * @param {Parameter} parameter - Parameter to declare.
1613
   * @param {ParameterDescriptor} [descriptor] - Optional descriptor for parameter.
1614
   * @param {boolean} [ignoreOverride] - When true disregard any parameter-override that may be present.
1615
   * @return {Parameter} - The newly declared parameter.
1616
   */
1617
  declareParameter(parameter, descriptor, ignoreOverride = false) {
2,174✔
1618
    const parameters = this.declareParameters(
2,175✔
1619
      [parameter],
1620
      descriptor ? [descriptor] : [],
2,175✔
1621
      ignoreOverride
1622
    );
1623
    return parameters.length == 1 ? parameters[0] : null;
2,175!
1624
  }
1625

1626
  /**
1627
   * Declare a list of parameters.
1628
   *
1629
   * Internally register parameters with their corresponding descriptor one by one
1630
   * in the order they are provided. This is an atomic operation. If an error
1631
   * occurs the process halts and no further parameters are declared.
1632
   * Parameters that have already been processed are undeclared.
1633
   *
1634
   * While descriptors is an optional parameter, when provided there must be
1635
   * a descriptor for each parameter; otherwise an Error is thrown.
1636
   * If descriptors is not provided then a descriptor will be inferred
1637
   * from each parameter's state.
1638
   *
1639
   * When a parameter-override is available, the parameter's value
1640
   * will be replaced with that of the parameter-override unless ignoreOverrides
1641
   * is true.
1642
   *
1643
   * If a parameter by the same name has already been declared then an Error is thrown.
1644
   * A parameter must be undeclared before attempting to redeclare it.
1645
   *
1646
   * Prior to declaring the parameters each SetParameterEventCallback registered
1647
   * using setOnParameterEventCallback() is called in succession with the parameters
1648
   * list. Any SetParameterEventCallback that retuns does not return a successful
1649
   * result will cause the entire operation to terminate with no changes to the
1650
   * parameters. When all SetParameterEventCallbacks return successful then the
1651
   * list of parameters is updated.
1652
   *
1653
   * @param {Parameter[]} parameters - The parameters to declare.
1654
   * @param {ParameterDescriptor[]} [descriptors] - Optional descriptors,
1655
   *    a 1-1 correspondence with parameters.
1656
   * @param {boolean} ignoreOverrides - When true, parameter-overrides are
1657
   *    not considered, i.e.,ignored.
1658
   * @return {Parameter[]} - The declared parameters.
1659
   */
1660
  declareParameters(parameters, descriptors = [], ignoreOverrides = false) {
×
1661
    if (!Array.isArray(parameters)) {
2,175!
UNCOV
1662
      throw new TypeValidationError('parameters', parameters, 'Array', {
×
1663
        nodeName: this.name(),
1664
      });
1665
    }
1666
    if (!Array.isArray(descriptors)) {
2,175!
UNCOV
1667
      throw new TypeValidationError('descriptors', descriptors, 'Array', {
×
1668
        nodeName: this.name(),
1669
      });
1670
    }
1671
    if (descriptors.length > 0 && parameters.length !== descriptors.length) {
2,175!
UNCOV
1672
      throw new ValidationError(
×
1673
        'Each parameter must have a corresponding ParameterDescriptor',
1674
        {
1675
          code: 'PARAMETER_DESCRIPTOR_MISMATCH',
1676
          argumentName: 'descriptors',
1677
          providedValue: descriptors.length,
1678
          expectedType: `Array with length ${parameters.length}`,
1679
          nodeName: this.name(),
1680
        }
1681
      );
1682
    }
1683

1684
    const declaredDescriptors = [];
2,175✔
1685
    const declaredParameters = [];
2,175✔
1686
    const declaredParameterCollisions = [];
2,175✔
1687
    for (let i = 0; i < parameters.length; i++) {
2,175✔
1688
      let parameter =
1689
        !ignoreOverrides && this._parameterOverrides.has(parameters[i].name)
2,175✔
1690
          ? this._parameterOverrides.get(parameters[i].name)
1691
          : parameters[i];
1692

1693
      // stop processing parameters that have already been declared
1694
      if (this._parameters.has(parameter.name)) {
2,175!
UNCOV
1695
        declaredParameterCollisions.push(parameter);
×
UNCOV
1696
        continue;
×
1697
      }
1698

1699
      // create descriptor for parameter if not provided
1700
      let descriptor =
1701
        descriptors.length > 0
2,175✔
1702
          ? descriptors[i]
1703
          : ParameterDescriptor.fromParameter(parameter);
1704

1705
      descriptor.validate();
2,175✔
1706

1707
      declaredDescriptors.push(descriptor);
2,175✔
1708
      declaredParameters.push(parameter);
2,175✔
1709
    }
1710

1711
    if (declaredParameterCollisions.length > 0) {
2,175!
1712
      const errorMsg =
UNCOV
1713
        declaredParameterCollisions.length == 1
×
1714
          ? `Parameter(${declaredParameterCollisions[0]}) already declared.`
1715
          : `Multiple parameters already declared, e.g., Parameter(${declaredParameterCollisions[0]}).`;
UNCOV
1716
      throw new Error(errorMsg);
×
1717
    }
1718

1719
    // register descriptor
1720
    for (const descriptor of declaredDescriptors) {
2,175✔
1721
      this._parameterDescriptors.set(descriptor.name, descriptor);
2,175✔
1722
    }
1723

1724
    const result = this._setParametersAtomically(declaredParameters, true);
2,175✔
1725
    if (!result.successful) {
2,175!
1726
      // unregister descriptors
UNCOV
1727
      for (const descriptor of declaredDescriptors) {
×
UNCOV
1728
        this._parameterDescriptors.delete(descriptor.name);
×
1729
      }
1730

UNCOV
1731
      throw new Error(result.reason);
×
1732
    }
1733

1734
    return this.getParameters(declaredParameters.map((param) => param.name));
2,175✔
1735
  }
1736

1737
  /**
1738
   * Undeclare a parameter.
1739
   *
1740
   * Readonly parameters can not be undeclared or updated.
1741
   * @param {string} name - Name of parameter to undeclare.
1742
   * @return {undefined} -
1743
   */
1744
  undeclareParameter(name) {
1745
    if (!this.hasParameter(name)) return;
1!
1746

1747
    const descriptor = this.getParameterDescriptor(name);
1✔
1748
    if (descriptor.readOnly) {
1!
UNCOV
1749
      throw new Error(
×
1750
        `${name} parameter is read-only and can not be undeclared`
1751
      );
1752
    }
1753

1754
    this._parameters.delete(name);
1✔
1755
    this._parameterDescriptors.delete(name);
1✔
1756
  }
1757

1758
  /**
1759
   * Determine if a parameter has been declared.
1760
   * @param {string} name - name of parameter
1761
   * @returns {boolean} - Return true if parameter is declared; false otherwise.
1762
   */
1763
  hasParameter(name) {
1764
    return this._parameters.has(name);
5,413✔
1765
  }
1766

1767
  /**
1768
   * Get a declared parameter by name.
1769
   *
1770
   * If unable to locate a declared parameter then a
1771
   * parameter with type == PARAMETER_NOT_SET is returned.
1772
   *
1773
   * @param {string} name - The name of the parameter.
1774
   * @return {Parameter} - The parameter.
1775
   */
1776
  getParameter(name) {
1777
    return this.getParameters([name])[0];
1,604✔
1778
  }
1779

1780
  /**
1781
   * Get a list of parameters.
1782
   *
1783
   * Find and return the declared parameters.
1784
   * If no names are provided return all declared parameters.
1785
   *
1786
   * If unable to locate a declared parameter then a
1787
   * parameter with type == PARAMETER_NOT_SET is returned in
1788
   * it's place.
1789
   *
1790
   * @param {string[]} [names] - The names of the declared parameters
1791
   *    to find or null indicating to return all declared parameters.
1792
   * @return {Parameter[]} - The parameters.
1793
   */
1794
  getParameters(names = []) {
12✔
1795
    let params = [];
3,817✔
1796

1797
    if (names.length == 0) {
3,817✔
1798
      // get all parameters
1799
      params = [...this._parameters.values()];
12✔
1800
      return params;
12✔
1801
    }
1802

1803
    for (const name of names) {
3,805✔
1804
      const param = this.hasParameter(name)
3,812✔
1805
        ? this._parameters.get(name)
1806
        : new Parameter(name, ParameterType.PARAMETER_NOT_SET);
1807

1808
      params.push(param);
3,812✔
1809
    }
1810

1811
    return params;
3,805✔
1812
  }
1813

1814
  /**
1815
   * Get the types of given parameters.
1816
   *
1817
   * Return the types of given parameters.
1818
   *
1819
   * @param {string[]} [names] - The names of the declared parameters.
1820
   * @return {Uint8Array} - The types.
1821
   */
1822
  getParameterTypes(names = []) {
×
1823
    let types = [];
3✔
1824

1825
    for (const name of names) {
3✔
1826
      const descriptor = this._parameterDescriptors.get(name);
7✔
1827
      if (descriptor) {
7!
1828
        types.push(descriptor.type);
7✔
1829
      }
1830
    }
1831
    return types;
3✔
1832
  }
1833

1834
  /**
1835
   * Get the names of all declared parameters.
1836
   *
1837
   * @return {Array<string>} - The declared parameter names or empty array if
1838
   *    no parameters have been declared.
1839
   */
1840
  getParameterNames() {
1841
    return this.getParameters().map((param) => param.name);
53✔
1842
  }
1843

1844
  /**
1845
   * Determine if a parameter descriptor exists.
1846
   *
1847
   * @param {string} name - The name of a descriptor to for.
1848
   * @return {boolean} - true if a descriptor has been declared; otherwise false.
1849
   */
1850
  hasParameterDescriptor(name) {
1851
    return !!this.getParameterDescriptor(name);
2,200✔
1852
  }
1853

1854
  /**
1855
   * Get a declared parameter descriptor by name.
1856
   *
1857
   * If unable to locate a declared parameter descriptor then a
1858
   * descriptor with type == PARAMETER_NOT_SET is returned.
1859
   *
1860
   * @param {string} name - The name of the parameter descriptor to find.
1861
   * @return {ParameterDescriptor} - The parameter descriptor.
1862
   */
1863
  getParameterDescriptor(name) {
1864
    return this.getParameterDescriptors([name])[0];
4,401✔
1865
  }
1866

1867
  /**
1868
   * Find a list of declared ParameterDescriptors.
1869
   *
1870
   * If no names are provided return all declared descriptors.
1871
   *
1872
   * If unable to locate a declared descriptor then a
1873
   * descriptor with type == PARAMETER_NOT_SET is returned in
1874
   * it's place.
1875
   *
1876
   * @param {string[]} [names] - The names of the declared parameter
1877
   *    descriptors to find or null indicating to return all declared descriptors.
1878
   * @return {ParameterDescriptor[]} - The parameter descriptors.
1879
   */
1880
  getParameterDescriptors(names = []) {
×
1881
    let descriptors = [];
4,404✔
1882

1883
    if (names.length == 0) {
4,404!
1884
      // get all parameters
UNCOV
1885
      descriptors = [...this._parameterDescriptors.values()];
×
UNCOV
1886
      return descriptors;
×
1887
    }
1888

1889
    for (const name of names) {
4,404✔
1890
      let descriptor = this._parameterDescriptors.get(name);
4,406✔
1891
      if (!descriptor) {
4,406!
UNCOV
1892
        descriptor = new ParameterDescriptor(
×
1893
          name,
1894
          ParameterType.PARAMETER_NOT_SET
1895
        );
1896
      }
1897
      descriptors.push(descriptor);
4,406✔
1898
    }
1899

1900
    return descriptors;
4,404✔
1901
  }
1902

1903
  /**
1904
   * Replace a declared parameter.
1905
   *
1906
   * The parameter being replaced must be a declared parameter who's descriptor
1907
   * is not readOnly; otherwise an Error is thrown.
1908
   *
1909
   * @param {Parameter} parameter - The new parameter.
1910
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult} - The result of the operation.
1911
   */
1912
  setParameter(parameter) {
1913
    const results = this.setParameters([parameter]);
10✔
1914
    return results[0];
10✔
1915
  }
1916

1917
  /**
1918
   * Replace a list of declared parameters.
1919
   *
1920
   * Declared parameters are replaced in the order they are provided and
1921
   * a ParameterEvent is published for each individual parameter change.
1922
   *
1923
   * Prior to setting the parameters each SetParameterEventCallback registered
1924
   * using setOnParameterEventCallback() is called in succession with the parameters
1925
   * list. Any SetParameterEventCallback that retuns does not return a successful
1926
   * result will cause the entire operation to terminate with no changes to the
1927
   * parameters. When all SetParameterEventCallbacks return successful then the
1928
   * list of parameters is updated.
1929
   *
1930
   * If an error occurs, the process is stopped and returned. Parameters
1931
   * set before an error remain unchanged.
1932
   *
1933
   * @param {Parameter[]} parameters - The parameters to set.
1934
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult[]} - A list of SetParameterResult, one for each parameter that was set.
1935
   */
1936
  setParameters(parameters = []) {
×
1937
    return parameters.map((parameter) =>
21✔
1938
      this.setParametersAtomically([parameter])
24✔
1939
    );
1940
  }
1941

1942
  /**
1943
   * Repalce a list of declared parameters atomically.
1944
   *
1945
   * Declared parameters are replaced in the order they are provided.
1946
   * A single ParameterEvent is published collectively for all changed
1947
   * parameters.
1948
   *
1949
   * Prior to setting the parameters each SetParameterEventCallback registered
1950
   * using setOnParameterEventCallback() is called in succession with the parameters
1951
   * list. Any SetParameterEventCallback that retuns does not return a successful
1952
   * result will cause the entire operation to terminate with no changes to the
1953
   * parameters. When all SetParameterEventCallbacks return successful then the
1954
   * list of parameters is updated.d
1955
   *
1956
   * If an error occurs, the process stops immediately. All parameters updated to
1957
   * the point of the error are reverted to their previous state.
1958
   *
1959
   * @param {Parameter[]} parameters - The parameters to set.
1960
   * @return {rclnodejs.rcl_interfaces.msg.SetParameterResult} - describes the result of setting 1 or more parameters.
1961
   */
1962
  setParametersAtomically(parameters = []) {
×
1963
    return this._setParametersAtomically(parameters);
25✔
1964
  }
1965

1966
  /**
1967
   * Internal method for updating parameters atomically.
1968
   *
1969
   * Prior to setting the parameters each SetParameterEventCallback registered
1970
   * using setOnParameterEventCallback() is called in succession with the parameters
1971
   * list. Any SetParameterEventCallback that retuns does not return a successful
1972
   * result will cause the entire operation to terminate with no changes to the
1973
   * parameters. When all SetParameterEventCallbacks return successful then the
1974
   * list of parameters is updated.
1975
   *
1976
   * @param {Paramerter[]} parameters - The parameters to update.
1977
   * @param {boolean} declareParameterMode - When true parameters are being declared;
1978
   *    otherwise they are being changed.
1979
   * @return {SetParameterResult} - A single collective result.
1980
   */
1981
  _setParametersAtomically(parameters = [], declareParameterMode = false) {
25!
1982
    let result = this._validateParameters(parameters, declareParameterMode);
2,200✔
1983
    if (!result.successful) {
2,200!
UNCOV
1984
      return result;
×
1985
    }
1986

1987
    // give all SetParametersCallbacks a chance to veto this change
1988
    for (const callback of this._setParametersCallbacks) {
2,200✔
1989
      result = callback(parameters);
1,410✔
1990
      if (!result.successful) {
1,410✔
1991
        // a callback has vetoed a parameter change
1992
        return result;
1✔
1993
      }
1994
    }
1995

1996
    // collectively track updates to parameters for use
1997
    // when publishing a ParameterEvent
1998
    const newParameters = [];
2,199✔
1999
    const changedParameters = [];
2,199✔
2000
    const deletedParameters = [];
2,199✔
2001

2002
    for (const parameter of parameters) {
2,199✔
2003
      if (parameter.type == ParameterType.PARAMETER_NOT_SET) {
2,199✔
2004
        this.undeclareParameter(parameter.name);
1✔
2005
        deletedParameters.push(parameter);
1✔
2006
      } else {
2007
        this._parameters.set(parameter.name, parameter);
2,198✔
2008
        if (declareParameterMode) {
2,198✔
2009
          newParameters.push(parameter);
2,175✔
2010
        } else {
2011
          changedParameters.push(parameter);
23✔
2012
        }
2013
      }
2014
    }
2015

2016
    // create ParameterEvent
2017
    const parameterEvent = new (loader.loadInterface(
2,199✔
2018
      PARAMETER_EVENT_MSG_TYPE
2019
    ))();
2020

2021
    const { seconds, nanoseconds } = this._clock.now().secondsAndNanoseconds;
2,199✔
2022
    parameterEvent.stamp = {
2,199✔
2023
      sec: Number(seconds),
2024
      nanosec: Number(nanoseconds),
2025
    };
2026

2027
    parameterEvent.node =
2,199✔
2028
      this.namespace() === '/'
2,199✔
2029
        ? this.namespace() + this.name()
2030
        : this.namespace() + '/' + this.name();
2031

2032
    if (newParameters.length > 0) {
2,199✔
2033
      parameterEvent['new_parameters'] = newParameters.map((parameter) =>
2,175✔
2034
        parameter.toParameterMessage()
2,175✔
2035
      );
2036
    }
2037
    if (changedParameters.length > 0) {
2,199✔
2038
      parameterEvent['changed_parameters'] = changedParameters.map(
23✔
2039
        (parameter) => parameter.toParameterMessage()
23✔
2040
      );
2041
    }
2042
    if (deletedParameters.length > 0) {
2,199✔
2043
      parameterEvent['deleted_parameters'] = deletedParameters.map(
1✔
2044
        (parameter) => parameter.toParameterMessage()
1✔
2045
      );
2046
    }
2047

2048
    // Publish ParameterEvent.
2049
    this._parameterEventPublisher.publish(parameterEvent);
2,199✔
2050

2051
    return {
2,199✔
2052
      successful: true,
2053
      reason: '',
2054
    };
2055
  }
2056

2057
  /**
2058
   * This callback is called when declaring a parameter or setting a parameter.
2059
   * The callback is provided a list of parameters and returns a SetParameterResult
2060
   * to indicate approval or veto of the operation.
2061
   *
2062
   * @callback SetParametersCallback
2063
   * @param {Parameter[]} parameters - The message published
2064
   * @returns {rcl_interfaces.msg.SetParameterResult} -
2065
   *
2066
   * @see [Node.addOnSetParametersCallback]{@link Node#addOnSetParametersCallback}
2067
   * @see [Node.removeOnSetParametersCallback]{@link Node#removeOnSetParametersCallback}
2068
   */
2069

2070
  /**
2071
   * Add a callback to the front of the list of callbacks invoked for parameter declaration
2072
   * and setting. No checks are made for duplicate callbacks.
2073
   *
2074
   * @param {SetParametersCallback} callback - The callback to add.
2075
   * @returns {undefined}
2076
   */
2077
  addOnSetParametersCallback(callback) {
2078
    this._setParametersCallbacks.unshift(callback);
804✔
2079
  }
2080

2081
  /**
2082
   * Remove a callback from the list of SetParametersCallbacks.
2083
   * If the callback is not found the process is a nop.
2084
   *
2085
   * @param {SetParametersCallback} callback - The callback to be removed
2086
   * @returns {undefined}
2087
   */
2088
  removeOnSetParametersCallback(callback) {
2089
    const idx = this._setParametersCallbacks.indexOf(callback);
2✔
2090
    if (idx > -1) {
2!
2091
      this._setParametersCallbacks.splice(idx, 1);
2✔
2092
    }
2093
  }
2094

2095
  /**
2096
   * Get the fully qualified name of the node.
2097
   *
2098
   * @returns {string} - String containing the fully qualified name of the node.
2099
   */
2100
  getFullyQualifiedName() {
2101
    return rclnodejs.getFullyQualifiedName(this.handle);
1✔
2102
  }
2103

2104
  /**
2105
   * Get the RMW implementation identifier
2106
   * @returns {string} - The RMW implementation identifier.
2107
   */
2108
  getRMWImplementationIdentifier() {
2109
    return rclnodejs.getRMWImplementationIdentifier();
1✔
2110
  }
2111

2112
  /**
2113
   * Return a topic name expanded and remapped.
2114
   * @param {string} topicName - Topic name to be expanded and remapped.
2115
   * @param {boolean} [onlyExpand=false] - If `true`, remapping rules won't be applied.
2116
   * @returns {string} - A fully qualified topic name.
2117
   */
2118
  resolveTopicName(topicName, onlyExpand = false) {
2✔
2119
    if (typeof topicName !== 'string') {
3!
UNCOV
2120
      throw new TypeValidationError('topicName', topicName, 'string', {
×
2121
        nodeName: this.name(),
2122
      });
2123
    }
2124
    return rclnodejs.resolveName(
3✔
2125
      this.handle,
2126
      topicName,
2127
      onlyExpand,
2128
      /*isService=*/ false
2129
    );
2130
  }
2131

2132
  /**
2133
   * Return a service name expanded and remapped.
2134
   * @param {string} service - Service name to be expanded and remapped.
2135
   * @param {boolean} [onlyExpand=false] - If `true`, remapping rules won't be applied.
2136
   * @returns {string} - A fully qualified service name.
2137
   */
2138
  resolveServiceName(service, onlyExpand = false) {
6✔
2139
    if (typeof service !== 'string') {
7!
UNCOV
2140
      throw new TypeValidationError('service', service, 'string', {
×
2141
        nodeName: this.name(),
2142
      });
2143
    }
2144
    return rclnodejs.resolveName(
7✔
2145
      this.handle,
2146
      service,
2147
      onlyExpand,
2148
      /*isService=*/ true
2149
    );
2150
  }
2151

2152
  // returns on 1st error or result {successful, reason}
2153
  _validateParameters(parameters = [], declareParameterMode = false) {
×
2154
    for (const parameter of parameters) {
2,200✔
2155
      // detect invalid parameter
2156
      try {
2,200✔
2157
        parameter.validate();
2,200✔
2158
      } catch {
UNCOV
2159
        return {
×
2160
          successful: false,
2161
          reason: `Invalid ${parameter.name}`,
2162
        };
2163
      }
2164

2165
      // detect undeclared parameter
2166
      if (!this.hasParameterDescriptor(parameter.name)) {
2,200!
UNCOV
2167
        return {
×
2168
          successful: false,
2169
          reason: `Parameter ${parameter.name} has not been declared`,
2170
        };
2171
      }
2172

2173
      // detect readonly parameter that can not be updated
2174
      const descriptor = this.getParameterDescriptor(parameter.name);
2,200✔
2175
      if (!declareParameterMode && descriptor.readOnly) {
2,200!
UNCOV
2176
        return {
×
2177
          successful: false,
2178
          reason: `Parameter ${parameter.name} is readonly`,
2179
        };
2180
      }
2181

2182
      // validate parameter against descriptor if not an undeclare action
2183
      if (parameter.type != ParameterType.PARAMETER_NOT_SET) {
2,200✔
2184
        try {
2,199✔
2185
          descriptor.validateParameter(parameter);
2,199✔
2186
        } catch {
UNCOV
2187
          return {
×
2188
            successful: false,
2189
            reason: `Parameter ${parameter.name} does not  readonly`,
2190
          };
2191
        }
2192
      }
2193
    }
2194

2195
    return {
2,200✔
2196
      successful: true,
2197
      reason: null,
2198
    };
2199
  }
2200

2201
  // Get a Map(nodeName->Parameter[]) of CLI parameter args that
2202
  // apply to 'this' node, .e.g., -p mynode:foo:=bar -p hello:=world
2203
  _getNativeParameterOverrides() {
2204
    const overrides = new Map();
796✔
2205

2206
    // Get native parameters from rcl context->global_arguments.
2207
    // rclnodejs returns an array of objects, 1 for each node e.g., -p my_node:foo:=bar,
2208
    // and a node named '/**' for global parameter rules,
2209
    // i.e., does not include a node identifier, e.g., -p color:=red
2210
    // {
2211
    //   name: string // node name
2212
    //   parameters[] = {
2213
    //     name: string
2214
    //     type: uint
2215
    //     value: object
2216
    // }
2217
    const cliParamOverrideData = rclnodejs.getParameterOverrides(
796✔
2218
      this.context.handle
2219
    );
2220

2221
    // convert native CLI parameterOverrides to Map<nodeName,Array<ParameterOverride>>
2222
    const cliParamOverrides = new Map();
796✔
2223
    if (cliParamOverrideData) {
796✔
2224
      for (let nodeParamData of cliParamOverrideData) {
8✔
2225
        const nodeName = nodeParamData.name;
12✔
2226
        const nodeParamOverrides = [];
12✔
2227
        for (let paramData of nodeParamData.parameters) {
12✔
2228
          const paramOverride = new Parameter(
17✔
2229
            paramData.name,
2230
            paramData.type,
2231
            paramData.value
2232
          );
2233
          nodeParamOverrides.push(paramOverride);
17✔
2234
        }
2235
        cliParamOverrides.set(nodeName, nodeParamOverrides);
12✔
2236
      }
2237
    }
2238

2239
    // collect global CLI global parameters, name == /**
2240
    let paramOverrides = cliParamOverrides.get('/**'); // array of ParameterOverrides
796✔
2241
    if (paramOverrides) {
796✔
2242
      for (const parameter of paramOverrides) {
5✔
2243
        overrides.set(parameter.name, parameter);
6✔
2244
      }
2245
    }
2246

2247
    // merge CLI node parameterOverrides with global parameterOverrides, replace existing
2248
    paramOverrides = cliParamOverrides.get(this.name()); // array of ParameterOverrides
796✔
2249
    if (paramOverrides) {
796✔
2250
      for (const parameter of paramOverrides) {
5✔
2251
        overrides.set(parameter.name, parameter);
7✔
2252
      }
2253
    }
2254

2255
    return overrides;
796✔
2256
  }
2257

2258
  /**
2259
   * Invokes the callback with a raw message of the given type. After the callback completes
2260
   * the message will be destroyed.
2261
   * @param {function} Type - Message type to create.
2262
   * @param {function} callback - Callback to invoke. First parameter will be the raw message,
2263
   * and the second is a function to retrieve the deserialized message.
2264
   * @returns {undefined}
2265
   */
2266
  _runWithMessageType(Type, callback) {
2267
    let message = new Type();
945✔
2268

2269
    callback(message.toRawROS(), () => {
945✔
2270
      let result = new Type();
696✔
2271
      result.deserialize(message.refObject);
696✔
2272

2273
      return result;
696✔
2274
    });
2275

2276
    Type.destroyRawROS(message);
945✔
2277
  }
2278

2279
  _addActionClient(actionClient) {
2280
    this._actionClients.push(actionClient);
41✔
2281
    this.syncHandles();
41✔
2282
  }
2283

2284
  _addActionServer(actionServer) {
2285
    this._actionServers.push(actionServer);
41✔
2286
    this.syncHandles();
41✔
2287
  }
2288

2289
  _getValidatedTopic(topicName, noDemangle) {
2290
    if (noDemangle) {
6!
UNCOV
2291
      return topicName;
×
2292
    }
2293
    const fqTopicName = rclnodejs.expandTopicName(
6✔
2294
      topicName,
2295
      this.name(),
2296
      this.namespace()
2297
    );
2298
    validateFullTopicName(fqTopicName);
6✔
2299
    return rclnodejs.remapTopicName(this.handle, fqTopicName);
6✔
2300
  }
2301

2302
  _getValidatedServiceName(serviceName, noDemangle) {
2303
    if (typeof serviceName !== 'string') {
4!
UNCOV
2304
      throw new TypeValidationError('serviceName', serviceName, 'string', {
×
2305
        nodeName: this.name(),
2306
      });
2307
    }
2308

2309
    if (noDemangle) {
4!
UNCOV
2310
      return serviceName;
×
2311
    }
2312

2313
    const resolvedServiceName = this.resolveServiceName(serviceName);
4✔
2314
    rclnodejs.validateTopicName(resolvedServiceName);
4✔
2315
    return resolvedServiceName;
4✔
2316
  }
2317
}
2318

2319
/**
2320
 * Create an Options instance initialized with default values.
2321
 * @returns {Options} - The new initialized instance.
2322
 * @static
2323
 * @example
2324
 * {
2325
 *   enableTypedArray: true,
2326
 *   isRaw: false,
2327
 *   qos: QoS.profileDefault,
2328
 *   contentFilter: undefined,
2329
 *   serializationMode: 'default',
2330
 * }
2331
 */
2332
Node.getDefaultOptions = function () {
26✔
2333
  return {
7,418✔
2334
    enableTypedArray: true,
2335
    isRaw: false,
2336
    qos: QoS.profileDefault,
2337
    contentFilter: undefined,
2338
    serializationMode: 'default',
2339
  };
2340
};
2341

2342
module.exports = Node;
26✔
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

© 2026 Coveralls, Inc