Skip to content

Commit d8f4952

Browse files
committed
Add ClockEvent support
1 parent e6e95c1 commit d8f4952

10 files changed

Lines changed: 531 additions & 0 deletions

File tree

binding.gyp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
'./src/rcl_action_server_bindings.cpp',
2727
'./src/rcl_bindings.cpp',
2828
'./src/rcl_client_bindings.cpp',
29+
'./src/clock_event.cpp',
2930
'./src/rcl_context_bindings.cpp',
3031
'./src/rcl_graph_bindings.cpp',
3132
'./src/rcl_guard_condition_bindings.cpp',

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
const DistroUtils = require('./lib/distro.js');
1818
const RMWUtils = require('./lib/rmw.js');
1919
const { Clock, ROSClock } = require('./lib/clock.js');
20+
const ClockEvent = require('./lib/clock_event.js');
2021
const ClockType = require('./lib/clock_type.js');
2122
const { compareVersions } = require('./lib/utils.js');
2223
const Context = require('./lib/context.js');
@@ -188,6 +189,9 @@ let rcl = {
188189
/** {@link Clock} class */
189190
Clock: Clock,
190191

192+
/** {@link ClockEvent} class */
193+
ClockEvent: ClockEvent,
194+
191195
/** {@link ClockType} enum */
192196
ClockType: ClockType,
193197

lib/clock_event.js

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright (c) 2025, The Robot Web Tools Contributors
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');
18+
19+
/**
20+
* @class - Class representing a ClockEvent in ROS
21+
*/
22+
class ClockEvent {
23+
constructor() {
24+
this._handle = rclnodejs.createClockEvent();
25+
}
26+
27+
/**
28+
* Wait until a time specified by a steady clock.
29+
* @param {Clock} clock - The clock to use for time synchronization.
30+
* @param {bigint} until - The time to wait until.
31+
* @return {Promise<void>} - A promise that resolves when the time is reached.
32+
*/
33+
async waitUntilSteady(clock, until) {
34+
return rclnodejs.clockEventWaitUntilSteady(
35+
this._handle,
36+
clock.handle,
37+
until
38+
);
39+
}
40+
41+
/**
42+
* Wait until a time specified by a system clock.
43+
* @param {Clock} clock - The clock to use for time synchronization.
44+
* @param {bigint} until - The time to wait until.
45+
* @return {Promise<void>} - A promise that resolves when the time is reached.
46+
*/
47+
async waitUntilSystem(clock, until) {
48+
return rclnodejs.clockEventWaitUntilSystem(
49+
this._handle,
50+
clock.handle,
51+
until
52+
);
53+
}
54+
55+
/**
56+
* Wait until a time specified by a ROS clock.
57+
* @param {Clock} clock - The clock to use for time synchronization.
58+
* @param {bigint} until - The time to wait until.
59+
* @return {Promise<void>} - A promise that resolves when the time is reached.
60+
*/
61+
async waitUntilRos(clock, until) {
62+
return rclnodejs.clockEventWaitUntilRos(this._handle, clock.handle, until);
63+
}
64+
65+
/**
66+
* Indicate if the ClockEvent is set.
67+
* @return {boolean} - True if the ClockEvent is set.
68+
*/
69+
isSet() {
70+
return rclnodejs.clockEventIsSet(this._handle);
71+
}
72+
73+
/**
74+
* Set the event.
75+
*/
76+
set() {
77+
rclnodejs.clockEventSet(this._handle);
78+
}
79+
80+
/**
81+
* Clear the event.
82+
*/
83+
clear() {
84+
rclnodejs.clockEventClear(this._handle);
85+
}
86+
}
87+
88+
module.exports = ClockEvent;

src/addon.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <node_api.h>
1616
#include <rcutils/logging.h>
1717

18+
#include "clock_event.hpp"
1819
#include "macros.h"
1920
#include "rcl_action_client_bindings.h"
2021
#include "rcl_action_goal_bindings.h"
@@ -74,6 +75,7 @@ Napi::Object InitModule(Napi::Env env, Napi::Object exports) {
7475
rclnodejs::InitActionGoalBindings(env, exports);
7576
rclnodejs::InitActionServerBindings(env, exports);
7677
rclnodejs::InitClientBindings(env, exports);
78+
rclnodejs::InitClockEventBindings(env, exports);
7779
rclnodejs::InitContextBindings(env, exports);
7880
rclnodejs::InitGraphBindings(env, exports);
7981
rclnodejs::InitGuardConditionBindings(env, exports);

src/clock_event.cpp

Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
// Copyright (c) 2025, The Robot Web Tools Contributors
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+
#include "clock_event.hpp"
16+
17+
#include <rcl/error_handling.h>
18+
#include <rcl/rcl.h>
19+
#include <rcl/time.h>
20+
#include <rcl/types.h>
21+
22+
#include <chrono>
23+
#include <memory>
24+
#include <mutex>
25+
#include <stdexcept>
26+
27+
#include "macros.h"
28+
#include "rcl_handle.h"
29+
30+
namespace rclnodejs {
31+
32+
template <typename ClockType>
33+
void ClockEvent::wait_until(rcl_clock_t* clock, rcl_time_point_t until) {
34+
// Synchronize because clock epochs might differ
35+
rcl_time_point_value_t now_value;
36+
rcl_ret_t ret = rcl_clock_get_now(clock, &now_value);
37+
if (RCL_RET_OK != ret) {
38+
throw std::runtime_error("failed to get current time");
39+
}
40+
rcl_time_point_t rcl_entry;
41+
rcl_entry.nanoseconds = now_value;
42+
rcl_entry.clock_type = clock->type;
43+
44+
const typename ClockType::time_point chrono_entry = ClockType::now();
45+
46+
rcl_duration_t delta_t;
47+
ret = rcl_difference_times(&rcl_entry, &until, &delta_t);
48+
49+
if (RCL_RET_OK != ret) {
50+
throw std::runtime_error("failed to subtract times");
51+
}
52+
53+
// Cast because system clock resolution is too big for nanoseconds on Windows
54+
// & OSX
55+
const typename ClockType::time_point chrono_until =
56+
chrono_entry + std::chrono::duration_cast<typename ClockType::duration>(
57+
std::chrono::nanoseconds(delta_t.nanoseconds));
58+
59+
std::unique_lock<std::mutex> lock(mutex_);
60+
cv_.wait_until(lock, chrono_until, [this]() { return state_; });
61+
}
62+
63+
void ClockEvent::wait_until_ros(rcl_clock_t* clock, rcl_time_point_t until) {
64+
bool is_enabled;
65+
rcl_ret_t ret = rcl_is_enabled_ros_time_override(clock, &is_enabled);
66+
if (RCL_RET_OK != ret) {
67+
throw std::runtime_error("failed to check if ros time override is enabled");
68+
}
69+
70+
// Check if ROS time is enabled in C++ to avoid TOCTTOU with TimeSource
71+
if (is_enabled) {
72+
std::unique_lock<std::mutex> lock(mutex_);
73+
// Caller must have setup a time jump callback to wake this event
74+
cv_.wait(lock, [this]() { return state_; });
75+
} else {
76+
// ROS time not enabled is system time
77+
wait_until<std::chrono::system_clock>(clock, until);
78+
}
79+
}
80+
81+
bool ClockEvent::is_set() {
82+
std::unique_lock<std::mutex> lock(mutex_);
83+
return state_;
84+
}
85+
86+
void ClockEvent::set() {
87+
{
88+
std::unique_lock<std::mutex> lock(mutex_);
89+
state_ = true;
90+
}
91+
cv_.notify_all();
92+
}
93+
94+
void ClockEvent::clear() {
95+
{
96+
std::unique_lock<std::mutex> lock(mutex_);
97+
state_ = false;
98+
}
99+
cv_.notify_all();
100+
}
101+
102+
// Explicit instantiation
103+
template void ClockEvent::wait_until<std::chrono::steady_clock>(
104+
rcl_clock_t* clock, rcl_time_point_t until);
105+
template void ClockEvent::wait_until<std::chrono::system_clock>(
106+
rcl_clock_t* clock, rcl_time_point_t until);
107+
108+
enum class WaitType { Steady, System, Ros };
109+
110+
class ClockEventWaitWorker : public Napi::AsyncWorker {
111+
public:
112+
ClockEventWaitWorker(Napi::Env env, ClockEvent* event, rcl_clock_t* clock,
113+
int64_t until, WaitType type)
114+
: Napi::AsyncWorker(env),
115+
event_(event),
116+
clock_(clock),
117+
until_(until),
118+
type_(type),
119+
deferred_(Napi::Promise::Deferred::New(env)) {}
120+
121+
~ClockEventWaitWorker() {}
122+
123+
void Execute() override {
124+
try {
125+
rcl_time_point_t until_time_point;
126+
until_time_point.nanoseconds = until_;
127+
until_time_point.clock_type = clock_->type;
128+
129+
switch (type_) {
130+
case WaitType::Ros:
131+
event_->wait_until_ros(clock_, until_time_point);
132+
break;
133+
case WaitType::Steady:
134+
event_->wait_until<std::chrono::steady_clock>(clock_,
135+
until_time_point);
136+
break;
137+
case WaitType::System:
138+
event_->wait_until<std::chrono::system_clock>(clock_,
139+
until_time_point);
140+
break;
141+
}
142+
} catch (const std::exception& e) {
143+
SetError(e.what());
144+
}
145+
}
146+
147+
void OnOK() override { deferred_.Resolve(Env().Undefined()); }
148+
149+
void OnError(const Napi::Error& e) override { deferred_.Reject(e.Value()); }
150+
151+
Napi::Promise Promise() { return deferred_.Promise(); }
152+
153+
private:
154+
ClockEvent* event_;
155+
rcl_clock_t* clock_;
156+
int64_t until_;
157+
WaitType type_;
158+
Napi::Promise::Deferred deferred_;
159+
};
160+
161+
Napi::Value CreateClockEvent(const Napi::CallbackInfo& info) {
162+
Napi::Env env = info.Env();
163+
ClockEvent* event = new ClockEvent();
164+
return RclHandle::NewInstance(env, event, nullptr, [](void* ptr) {
165+
delete static_cast<ClockEvent*>(ptr);
166+
});
167+
}
168+
169+
Napi::Value ClockEventWaitUntilSteady(const Napi::CallbackInfo& info) {
170+
Napi::Env env = info.Env();
171+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
172+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
173+
174+
RclHandle* clock_handle = RclHandle::Unwrap(info[1].As<Napi::Object>());
175+
rcl_clock_t* clock = static_cast<rcl_clock_t*>(clock_handle->ptr());
176+
177+
bool lossless;
178+
int64_t until = info[2].As<Napi::BigInt>().Int64Value(&lossless);
179+
180+
auto worker =
181+
new ClockEventWaitWorker(env, event, clock, until, WaitType::Steady);
182+
worker->Queue();
183+
return worker->Promise();
184+
}
185+
186+
Napi::Value ClockEventWaitUntilSystem(const Napi::CallbackInfo& info) {
187+
Napi::Env env = info.Env();
188+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
189+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
190+
191+
RclHandle* clock_handle = RclHandle::Unwrap(info[1].As<Napi::Object>());
192+
rcl_clock_t* clock = static_cast<rcl_clock_t*>(clock_handle->ptr());
193+
194+
bool lossless;
195+
int64_t until = info[2].As<Napi::BigInt>().Int64Value(&lossless);
196+
197+
auto worker =
198+
new ClockEventWaitWorker(env, event, clock, until, WaitType::System);
199+
worker->Queue();
200+
return worker->Promise();
201+
}
202+
203+
Napi::Value ClockEventWaitUntilRos(const Napi::CallbackInfo& info) {
204+
Napi::Env env = info.Env();
205+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
206+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
207+
208+
RclHandle* clock_handle = RclHandle::Unwrap(info[1].As<Napi::Object>());
209+
rcl_clock_t* clock = static_cast<rcl_clock_t*>(clock_handle->ptr());
210+
211+
bool lossless;
212+
int64_t until = info[2].As<Napi::BigInt>().Int64Value(&lossless);
213+
214+
auto worker =
215+
new ClockEventWaitWorker(env, event, clock, until, WaitType::Ros);
216+
worker->Queue();
217+
return worker->Promise();
218+
}
219+
220+
Napi::Value ClockEventIsSet(const Napi::CallbackInfo& info) {
221+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
222+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
223+
return Napi::Boolean::New(info.Env(), event->is_set());
224+
}
225+
226+
Napi::Value ClockEventSet(const Napi::CallbackInfo& info) {
227+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
228+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
229+
event->set();
230+
return info.Env().Undefined();
231+
}
232+
233+
Napi::Value ClockEventClear(const Napi::CallbackInfo& info) {
234+
RclHandle* event_handle = RclHandle::Unwrap(info[0].As<Napi::Object>());
235+
ClockEvent* event = static_cast<ClockEvent*>(event_handle->ptr());
236+
event->clear();
237+
return info.Env().Undefined();
238+
}
239+
240+
void InitClockEventBindings(Napi::Env env, Napi::Object exports) {
241+
exports.Set("createClockEvent", Napi::Function::New(env, CreateClockEvent));
242+
exports.Set("clockEventWaitUntilSteady",
243+
Napi::Function::New(env, ClockEventWaitUntilSteady));
244+
exports.Set("clockEventWaitUntilSystem",
245+
Napi::Function::New(env, ClockEventWaitUntilSystem));
246+
exports.Set("clockEventWaitUntilRos",
247+
Napi::Function::New(env, ClockEventWaitUntilRos));
248+
exports.Set("clockEventIsSet", Napi::Function::New(env, ClockEventIsSet));
249+
exports.Set("clockEventSet", Napi::Function::New(env, ClockEventSet));
250+
exports.Set("clockEventClear", Napi::Function::New(env, ClockEventClear));
251+
}
252+
253+
} // namespace rclnodejs

0 commit comments

Comments
 (0)