Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions example/topics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,26 @@ The `subscriber/` directory contains examples of nodes that subscribe to topics:
- **Features**: ROS 2 service introspection capabilities
- **Run Command**: `node subscriber/subscription-service-event-example.js`

### 8. Serialization Modes Subscriber (`subscription-serialization-modes-example.js`)

**Purpose**: Demonstrates different serialization modes for message handling.

- **Message Type**: `sensor_msgs/msg/LaserScan`
- **Topic**: `scan`
- **Functionality**: Shows how 'typed', 'plain', and 'json' modes affect message serialization
- **Features**: Message serialization control for web applications and JSON compatibility
- **Run Command**: `node subscriber/subscription-serialization-modes-example.js`

### 9. JSON Utilities Subscriber (`subscription-json-utilities-example.js`)

**Purpose**: Demonstrates manual message conversion utilities.

- **Message Type**: `sensor_msgs/msg/LaserScan`
- **Topic**: `scan`
- **Functionality**: Shows how to use toJSONSafe and toJSONString utilities for manual conversion
- **Features**: Manual conversion of TypedArrays, BigInt, and special values for JSON serialization
- **Run Command**: `node subscriber/subscription-json-utilities-example.js`

## Validator Example

The `validator/` directory contains validation utilities:
Expand Down Expand Up @@ -193,6 +213,7 @@ Several examples work together to demonstrate complete communication:
- **Raw Messages**: Binary data transmission
- **Service Events**: Monitoring service interactions
- **Multi-dimensional Arrays**: Complex data structures with layout information
- **Message Serialization**: TypedArray handling and JSON-safe conversion for web applications
- **Validation**: Name and topic validation utilities

## Notes
Expand Down
41 changes: 41 additions & 0 deletions example/topics/subscriber/subscription-json-utilities-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) 2024 rclnodejs contributors. All rights reserved.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer unifying the wording here, you can either:

  1. Add your name, like https://github.com/RobotWebTools/rclnodejs/blob/develop/lib/parameter_service.js
  2. Use a general name, like https://github.com/RobotWebTools/rclnodejs/blob/develop/lib/utils.js

It's up to you. nit: it's year of 2025 already :)

//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const rclnodejs = require('../../../index.js');

/**
* This example demonstrates the JSON utility functions for manual message conversion.
* These utilities are useful when you need to convert messages on-demand
* rather than using the serializationMode subscription option.
*/
async function main() {
await rclnodejs.init();
const node = new rclnodejs.Node('json_utilities_example_node');

node.createSubscription('sensor_msgs/msg/LaserScan', '/laser_scan', (msg) => {
// Convert using utility functions
const jsonSafe = rclnodejs.toJSONSafe(msg);
const jsonString = rclnodejs.toJSONString(msg);

console.log(
`Original: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}, JSON-safe: ${jsonSafe.ranges ? jsonSafe.ranges.constructor.name : 'undefined'}, JSON length: ${jsonString.length}`
);
});

node.spin();
}

main().catch(console.error);
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (c) 2024 rclnodejs contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const rclnodejs = require('../../../index.js');

/**
* This example demonstrates the use of serialization modes for subscriptions.
* Serialization modes allow you to control how TypedArrays are handled in messages:
* - 'typed' (default): Keep TypedArrays for performance
* - 'plain': Convert TypedArrays to regular arrays
* - 'json': Fully JSON-safe (converts TypedArrays, BigInt, Infinity, etc.)
*/
async function main() {
await rclnodejs.init();
const node = new rclnodejs.Node('serialization_modes_example_node');

// Default mode: 'typed' - keeps TypedArrays
node.createSubscription(
'sensor_msgs/msg/LaserScan',
'/laser_scan',
{ serializationMode: 'typed' },
(msg) => {
console.log(
`[TYPED] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}`
);
}
);

// Plain mode: converts TypedArrays to regular arrays
node.createSubscription(
'sensor_msgs/msg/LaserScan',
'/laser_scan',
{ serializationMode: 'plain' },
(msg) => {
console.log(
`[PLAIN] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}`
);
}
);

// JSON mode: fully JSON-safe
node.createSubscription(
'sensor_msgs/msg/LaserScan',
'/laser_scan',
{ serializationMode: 'json' },
(msg) => {
console.log(
`[JSON] ranges: ${msg.ranges ? msg.ranges.constructor.name : 'undefined'}, JSON-safe: ${canStringifyJSON(msg)}`
);
}
);

node.spin();
}

function canStringifyJSON(obj) {
try {
JSON.stringify(obj);
return true;
} catch {
return false;
}
}

main().catch(console.error);
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const ActionUuid = require('./lib/action/uuid.js');
const ClientGoalHandle = require('./lib/action/client_goal_handle.js');
const { CancelResponse, GoalResponse } = require('./lib/action/response.js');
const ServerGoalHandle = require('./lib/action/server_goal_handle.js');
const { toJSONSafe, toJSONString } = require('./lib/message_serialization.js');
const {
getActionClientNamesAndTypesByNode,
getActionServerNamesAndTypesByNode,
Expand Down Expand Up @@ -538,6 +539,23 @@ let rcl = {
* @return {Promise<{process: ChildProcess}>} A Promise that resolves with the process.
*/
ros2Launch: ros2Launch,

/**
* Convert a message object to be JSON-safe by converting TypedArrays to regular arrays
* and handling BigInt, Infinity, NaN, etc. for JSON serialization.
* @param {*} obj - The message object to convert
* @returns {*} A JSON-safe version of the object
*/
toJSONSafe: toJSONSafe,

/**
* Convert a message object to a JSON string with proper handling of TypedArrays,
* BigInt, and other non-JSON-serializable values.
* @param {*} obj - The message object to convert
* @param {number} [space] - Space parameter for JSON.stringify formatting
* @returns {string} The JSON string representation
*/
toJSONString: toJSONString,
};

const _sigHandler = () => {
Expand Down
171 changes: 171 additions & 0 deletions lib/message_serialization.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Copyright (c) 2024 rclnodejs contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

/**
* Check if a value is a TypedArray
* @param {*} value - The value to check
* @returns {boolean} True if the value is a TypedArray
*/
function isTypedArray(value) {
return ArrayBuffer.isView(value) && !(value instanceof DataView);
}

/**
* Check if a value needs JSON conversion (BigInt, functions, etc.)
* @param {*} value - The value to check
* @returns {boolean} True if the value needs special JSON handling
*/
function needsJSONConversion(value) {
return (
typeof value === 'bigint' ||
typeof value === 'function' ||
typeof value === 'undefined' ||
value === Infinity ||
value === -Infinity ||
(typeof value === 'number' && isNaN(value))
);
}

/**
* Convert a message to plain arrays (TypedArray -> regular Array)
* @param {*} obj - The object to convert
* @returns {*} The converted object with plain arrays
*/
function toPlainArrays(obj) {
if (obj === null || obj === undefined) {
return obj;
}

if (isTypedArray(obj)) {
return Array.from(obj);
}

if (Array.isArray(obj)) {
return obj.map((item) => toPlainArrays(item));
}

if (typeof obj === 'object' && obj !== null) {
const result = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
result[key] = toPlainArrays(obj[key]);
}
}
return result;
}

return obj;
}

/**
* Convert a message to be fully JSON-safe
* @param {*} obj - The object to convert
* @returns {*} The JSON-safe converted object
*/
function toJSONSafe(obj) {
if (obj === null || obj === undefined) {
return obj;
}

if (isTypedArray(obj)) {
return Array.from(obj).map((item) => toJSONSafe(item));
}

if (needsJSONConversion(obj)) {
if (typeof obj === 'bigint') {
// Convert BigInt to string with 'n' suffix to indicate it was a BigInt
return obj.toString() + 'n';
}
if (obj === Infinity) return 'Infinity';
if (obj === -Infinity) return '-Infinity';
if (typeof obj === 'number' && isNaN(obj)) return 'NaN';
if (typeof obj === 'undefined') return null;
if (typeof obj === 'function') return '[Function]';
}

if (Array.isArray(obj)) {
return obj.map((item) => toJSONSafe(item));
}

if (typeof obj === 'object' && obj !== null) {
const result = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
result[key] = toJSONSafe(obj[key]);
}
}
return result;
}

return obj;
}

/**
* Convert a message to a JSON string
* @param {*} obj - The object to convert
* @param {number} [space] - Space parameter for JSON.stringify formatting
* @returns {string} The JSON string representation
*/
function toJSONString(obj, space) {
const jsonSafeObj = toJSONSafe(obj);
return JSON.stringify(jsonSafeObj, null, space);
}

/**
* Apply serialization mode conversion to a message object
* @param {*} message - The message object to convert
* @param {string} serializationMode - The serialization mode ('typed', 'plain', 'json')
* @returns {*} The converted message
*/
function applySerializationMode(message, serializationMode) {
switch (serializationMode) {
case 'typed':
// No conversion needed - keep TypedArrays
return message;

case 'plain':
// Convert TypedArrays to regular arrays
return toPlainArrays(message);

case 'json':
// Convert to fully JSON-safe format
return toJSONSafe(message);

default:
throw new TypeError(
`Invalid serializationMode: ${serializationMode}. Valid modes are: 'typed', 'plain', 'json'`
);
}
}

/**
* Validate serialization mode
* @param {string} mode - The serialization mode to validate
* @returns {boolean} True if valid
*/
function isValidSerializationMode(mode) {
return ['typed', 'plain', 'json'].includes(mode);
}

module.exports = {
isTypedArray,
needsJSONConversion,
toPlainArrays,
toJSONSafe,
toJSONString,
applySerializationMode,
isValidSerializationMode,
};
Loading
Loading