1use core::marker::PhantomData;
4
5use nros_core::RosAction;
6use nros_rmw::{ActionEndpointHashes, ActionInfo, QoSProfile, ServiceInfo, Session, TopicInfo};
7
8#[allow(unused_imports)]
9use crate::rmw_type_registry::{MessageForRmw, register_type};
10
11use super::{
12 action_core::{ActionClientCore, ActionServerCore, RawActiveGoal},
13 arena::{
14 ActionClientCallbackEntry, ActionClientRawArenaEntry, ActionServerArenaEntry,
15 ActionServerRawArenaEntry, BufferStrategy, CallbackMeta, EntryKind, TraceName,
16 action_client_callback_try_process, action_client_raw_try_process,
17 action_server_raw_try_process, action_server_try_process, always_ready,
18 as_active_goal_count, as_complete_goal, as_expire_goals, as_for_each_active_goal,
19 as_goal_exists, as_publish_feedback, as_raw_active_goal_count, as_raw_complete_goal,
20 as_raw_expire_goals, as_raw_for_each_active_goal, as_raw_goal_exists,
21 as_raw_publish_feedback, as_raw_set_goal_status, as_set_goal_status, buffered_region_size,
22 drop_entry, no_pre_sample,
23 },
24 handles::{ActionServer, ActiveGoal},
25 spin::Executor,
26 spsc_ring::SpscRing,
27 triple_buffer::TripleBuffer,
28 types::{
29 HandleId, InvocationMode, NodeError, RawAcceptedCallback, RawCancelCallback,
30 RawCancelResponseCallback, RawFeedbackCallback, RawGoalCallback, RawGoalResponseCallback,
31 RawResultCallback,
32 },
33};
34
35pub const ACTION_SERVER_QUERYABLES: usize = 3;
49
50pub const ACTION_SERVER_PUBLISHERS: usize = 2;
60
61pub const ACTION_CLIENT_SUBSCRIPTIONS: usize = 1;
70
71pub const ACTION_CLIENT_SERVICE_CLIENTS: usize = 3;
81
82pub struct RawActionServerSpec<'a> {
92 pub node_id: Option<super::node_record::NodeId>,
97 pub action_name: &'a str,
98 pub type_name: &'a str,
99 pub type_hash: &'a str,
102 pub hashes: ActionEndpointHashes<'a>,
104 pub qos: QoSProfile,
109 pub goal_callback: RawGoalCallback,
110 pub cancel_callback: RawCancelCallback,
111 pub accepted_callback: Option<RawAcceptedCallback>,
112 pub context: *mut core::ffi::c_void,
113}
114
115pub struct RawActionClientSpec<'a> {
121 pub node_id: Option<super::node_record::NodeId>,
126 pub action_name: &'a str,
127 pub type_name: &'a str,
128 pub type_hash: &'a str,
131 pub hashes: ActionEndpointHashes<'a>,
133 pub goal_response_callback: Option<RawGoalResponseCallback>,
134 pub feedback_callback: Option<RawFeedbackCallback>,
135 pub result_callback: Option<RawResultCallback>,
136 pub cancel_response_callback: Option<RawCancelResponseCallback>,
140 pub context: *mut core::ffi::c_void,
141}
142
143impl<'s> Executor<'s> {
148 pub fn register_action_server<A, GoalF, CancelF>(
159 &mut self,
160 action_name: &str,
161 goal_callback: GoalF,
162 cancel_callback: CancelF,
163 ) -> Result<ActionServerHandle<A>, NodeError>
164 where
165 A: RosAction + 'static,
166 A::Goal: Clone + MessageForRmw,
167 A::Result: Clone + Default + MessageForRmw,
168 A::Feedback: MessageForRmw,
169 A::SendGoalRequest: MessageForRmw,
170 A::SendGoalResponse: MessageForRmw,
171 A::GetResultRequest: MessageForRmw,
172 A::GetResultResponse: MessageForRmw,
173 A::FeedbackMessage: MessageForRmw,
174 GoalF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse + 'static,
175 CancelF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse
176 + 'static,
177 {
178 self.register_action_server_sized::<A, GoalF, CancelF, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, 4>(
179 action_name,
180 goal_callback,
181 cancel_callback,
182 )
183 }
184
185 pub fn register_action_server_sized<
187 A,
188 GoalF,
189 CancelF,
190 const GOAL_BUF: usize,
191 const RESULT_BUF: usize,
192 const FEEDBACK_BUF: usize,
193 const MAX_GOALS: usize,
194 >(
195 &mut self,
196 action_name: &str,
197 goal_callback: GoalF,
198 cancel_callback: CancelF,
199 ) -> Result<ActionServerHandle<A>, NodeError>
200 where
201 A: RosAction + 'static,
202 A::Goal: Clone + MessageForRmw,
203 A::Result: Clone + Default + MessageForRmw,
204 A::Feedback: MessageForRmw,
205 A::SendGoalRequest: MessageForRmw,
206 A::SendGoalResponse: MessageForRmw,
207 A::GetResultRequest: MessageForRmw,
208 A::GetResultResponse: MessageForRmw,
209 A::FeedbackMessage: MessageForRmw,
210 GoalF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse + 'static,
211 CancelF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse
212 + 'static,
213 {
214 register_type::<A::Goal>()?;
221 register_type::<A::Result>()?;
222 register_type::<A::Feedback>()?;
223 register_type::<A::SendGoalRequest>()?;
224 register_type::<A::SendGoalResponse>()?;
225 register_type::<A::GetResultRequest>()?;
226 register_type::<A::GetResultResponse>()?;
227 register_type::<A::FeedbackMessage>()?;
228 A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
234 type Entry<
235 A,
236 GoalF,
237 CancelF,
238 const GB: usize,
239 const RB: usize,
240 const FB: usize,
241 const MG: usize,
242 > = ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>;
243
244 let slot = self.next_entry_slot()?;
245
246 let action_info = ActionInfo::new(action_name, A::ACTION_NAME, A::ACTION_HASH);
248
249 let send_goal_type = super::action_core::action_service_base_type(
254 <A::SendGoalRequest as nros_core::RosMessage>::TYPE_NAME,
255 A::ACTION_NAME,
256 );
257 let get_result_type = super::action_core::action_service_base_type(
258 <A::GetResultRequest as nros_core::RosMessage>::TYPE_NAME,
259 A::ACTION_NAME,
260 );
261 let feedback_type = <A::FeedbackMessage as nros_core::RosMessage>::TYPE_NAME;
262
263 let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
264 let send_goal_info = ServiceInfo::new(
265 &send_goal_keyexpr,
266 send_goal_type,
267 A::SEND_GOAL_SERVICE_HASH,
268 )
269 .with_domain(self.domain_id);
270 let send_goal_server = self
271 .session
272 .create_service(&send_goal_info, QoSProfile::services_default())
273 .map_err(NodeError::Transport)?;
274
275 let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
276 let cancel_goal_info = ServiceInfo::new(
277 &cancel_goal_keyexpr,
278 "action_msgs::srv::dds_::CancelGoal_",
279 A::CANCEL_GOAL_SERVICE_HASH,
280 )
281 .with_domain(self.domain_id);
282 let cancel_goal_server = self
283 .session
284 .create_service(&cancel_goal_info, QoSProfile::services_default())
285 .map_err(NodeError::Transport)?;
286
287 let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
288 let get_result_info = ServiceInfo::new(
289 &get_result_keyexpr,
290 get_result_type,
291 A::GET_RESULT_SERVICE_HASH,
292 )
293 .with_domain(self.domain_id);
294 let get_result_server = self
295 .session
296 .create_service(&get_result_info, QoSProfile::services_default())
297 .map_err(NodeError::Transport)?;
298
299 let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
300 let feedback_topic = TopicInfo::new(
301 &feedback_keyexpr,
302 feedback_type,
303 <A::FeedbackMessage as nros_core::RosMessage>::TYPE_HASH,
304 )
305 .with_domain(self.domain_id);
306 let feedback_publisher = self
307 .session
308 .create_publisher(&feedback_topic, QoSProfile::QOS_PROFILE_DEFAULT)
309 .map_err(NodeError::Transport)?;
310
311 let status_keyexpr: heapless::String<256> = action_info.status_key();
312 let status_topic = TopicInfo::new(
313 &status_keyexpr,
314 "action_msgs::msg::dds_::GoalStatusArray_",
315 A::STATUS_MESSAGE_HASH,
316 )
317 .with_domain(self.domain_id);
318 let status_publisher = self
319 .session
320 .create_publisher(&status_topic, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
321 .map_err(NodeError::Transport)?;
322
323 let server = ActionServer {
324 core: super::action_core::ActionServerCore {
325 send_goal_server,
326 cancel_goal_server,
327 get_result_server,
328 feedback_publisher,
329 status_publisher,
330 active_goals: heapless::Vec::new(),
331 completed_results: heapless::Vec::new(),
332 pending_get_results: heapless::Vec::new(),
333 result_slab: [0u8; RESULT_BUF],
334 result_slab_used: 0,
335 goal_buffer: [0u8; GOAL_BUF],
336 feedback_buffer: [0u8; FEEDBACK_BUF],
337 cancel_buffer: [0u8; 256],
338 },
339 typed_goals: heapless::Vec::new(),
340 completed_goals: heapless::Vec::new(),
341 };
342
343 let offset = self
344 .arena_alloc::<Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>(
345 )?;
346
347 unsafe {
348 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
349 let entry_ptr = arena_ptr.add(offset)
350 as *mut Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>;
351 core::ptr::write(
352 entry_ptr,
353 Entry {
354 server,
355 goal_callback,
356 cancel_callback,
357 },
358 );
359 }
360
361 let meta = CallbackMeta {
362 offset,
363 kind: EntryKind::ActionServer,
364 arena_len: super::arena::ArenaLen::UNRECORDED,
365 has_data: always_ready,
366 pre_sample: no_pre_sample,
367 invocation: InvocationMode::Always,
368 try_process: action_server_try_process::<
369 A,
370 GoalF,
371 CancelF,
372 GOAL_BUF,
373 RESULT_BUF,
374 FEEDBACK_BUF,
375 MAX_GOALS,
376 >,
377 drop_fn: drop_entry::<
378 Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
379 >,
380 };
381 self.emplace_entry(slot, meta, TraceName::Text(action_name));
382
383 Ok(ActionServerHandle {
384 entry_index: slot,
385 publish_feedback_fn: as_publish_feedback::<
386 A,
387 GoalF,
388 CancelF,
389 GOAL_BUF,
390 RESULT_BUF,
391 FEEDBACK_BUF,
392 MAX_GOALS,
393 >,
394 complete_goal_fn: as_complete_goal::<
395 A,
396 GoalF,
397 CancelF,
398 GOAL_BUF,
399 RESULT_BUF,
400 FEEDBACK_BUF,
401 MAX_GOALS,
402 >,
403 set_goal_status_fn: as_set_goal_status::<
404 A,
405 GoalF,
406 CancelF,
407 GOAL_BUF,
408 RESULT_BUF,
409 FEEDBACK_BUF,
410 MAX_GOALS,
411 >,
412 active_goal_count_fn: as_active_goal_count::<
413 A,
414 GoalF,
415 CancelF,
416 GOAL_BUF,
417 RESULT_BUF,
418 FEEDBACK_BUF,
419 MAX_GOALS,
420 >,
421 goal_exists_fn: as_goal_exists::<
422 A,
423 GoalF,
424 CancelF,
425 GOAL_BUF,
426 RESULT_BUF,
427 FEEDBACK_BUF,
428 MAX_GOALS,
429 >,
430 expire_goals_fn: as_expire_goals::<
431 A,
432 GoalF,
433 CancelF,
434 GOAL_BUF,
435 RESULT_BUF,
436 FEEDBACK_BUF,
437 MAX_GOALS,
438 >,
439 for_each_active_goal_fn: as_for_each_active_goal::<
440 A,
441 GoalF,
442 CancelF,
443 GOAL_BUF,
444 RESULT_BUF,
445 FEEDBACK_BUF,
446 MAX_GOALS,
447 >,
448 _phantom: PhantomData,
449 })
450 }
451}
452
453#[allow(clippy::type_complexity)]
464pub struct ActionServerHandle<A: RosAction> {
465 pub(crate) entry_index: usize,
466 publish_feedback_fn:
467 unsafe fn(*mut u8, &nros_core::GoalUuid, &A::Feedback) -> Result<(), NodeError>,
468 complete_goal_fn: unsafe fn(
469 *mut u8,
470 &nros_core::GoalUuid,
471 nros_core::GoalStatusCode,
472 A::Result,
473 ) -> Result<(), NodeError>,
474 set_goal_status_fn: unsafe fn(*mut u8, &nros_core::GoalUuid, nros_core::GoalStatusCode),
475 active_goal_count_fn: unsafe fn(*const u8) -> usize,
476 goal_exists_fn: unsafe fn(*const u8, &nros_core::GoalUuid) -> bool,
477 expire_goals_fn: unsafe fn(*mut u8) -> usize,
478 for_each_active_goal_fn: unsafe fn(*const u8, &mut dyn FnMut(&ActiveGoal<A>)),
479 _phantom: PhantomData<A>,
480}
481
482impl<A: RosAction> Clone for ActionServerHandle<A> {
483 fn clone(&self) -> Self {
484 *self
485 }
486}
487
488impl<A: RosAction> Copy for ActionServerHandle<A> {}
489
490impl<A: RosAction> ActionServerHandle<A> {
491 pub fn handle_id(&self) -> HandleId {
495 HandleId::for_owned_slot(self.entry_index)
496 }
497
498 pub fn publish_feedback(
504 &self,
505 executor: &mut Executor,
506 goal_id: &nros_core::GoalUuid,
507 feedback: &A::Feedback,
508 ) -> Result<(), NodeError> {
509 let meta = executor.entries[self.entry_index]
510 .as_ref()
511 .ok_or(NodeError::BufferTooSmall)?;
512 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
513 unsafe {
514 let data_ptr = arena_ptr.add(meta.offset);
515 (self.publish_feedback_fn)(data_ptr, goal_id, feedback)
516 }
517 }
518
519 pub fn succeed(
546 &self,
547 executor: &mut Executor,
548 goal_id: &nros_core::GoalUuid,
549 result: A::Result,
550 ) -> Result<(), NodeError> {
551 self.complete_goal(
552 executor,
553 goal_id,
554 nros_core::GoalStatusCode::Succeeded,
555 result,
556 )
557 }
558
559 pub fn abort(
561 &self,
562 executor: &mut Executor,
563 goal_id: &nros_core::GoalUuid,
564 result: A::Result,
565 ) -> Result<(), NodeError> {
566 self.complete_goal(
567 executor,
568 goal_id,
569 nros_core::GoalStatusCode::Aborted,
570 result,
571 )
572 }
573
574 pub fn canceled(
585 &self,
586 executor: &mut Executor,
587 goal_id: &nros_core::GoalUuid,
588 result: A::Result,
589 ) -> Result<(), NodeError> {
590 self.complete_goal(
591 executor,
592 goal_id,
593 nros_core::GoalStatusCode::Canceled,
594 result,
595 )
596 }
597
598 pub fn complete_goal(
599 &self,
600 executor: &mut Executor,
601 goal_id: &nros_core::GoalUuid,
602 status: nros_core::GoalStatusCode,
603 result: A::Result,
604 ) -> Result<(), NodeError> {
605 let meta = executor.entries[self.entry_index]
606 .as_ref()
607 .ok_or(NodeError::BufferTooSmall)?;
608 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
609 unsafe {
610 let data_ptr = arena_ptr.add(meta.offset);
611 (self.complete_goal_fn)(data_ptr, goal_id, status, result)
612 }
613 }
614
615 pub fn set_goal_status(
620 &self,
621 executor: &mut Executor,
622 goal_id: &nros_core::GoalUuid,
623 status: nros_core::GoalStatusCode,
624 ) {
625 if let Some(meta) = executor.entries[self.entry_index].as_ref() {
626 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
627 unsafe {
628 let data_ptr = arena_ptr.add(meta.offset);
629 (self.set_goal_status_fn)(data_ptr, goal_id, status);
630 }
631 }
632 }
633
634 pub fn active_goal_count(&self, executor: &Executor) -> usize {
638 match executor.entries[self.entry_index].as_ref() {
639 Some(meta) => {
640 let arena_ptr = executor.arena.as_ptr() as *const u8;
641 unsafe {
642 let data_ptr = arena_ptr.add(meta.offset);
643 (self.active_goal_count_fn)(data_ptr)
644 }
645 }
646 None => 0,
647 }
648 }
649
650 pub fn goal_exists(&self, executor: &Executor, goal_id: &nros_core::GoalUuid) -> bool {
662 match executor.entries[self.entry_index].as_ref() {
663 Some(meta) => {
664 let arena_ptr = executor.arena.as_ptr() as *const u8;
665 unsafe {
666 let data_ptr = arena_ptr.add(meta.offset);
667 (self.goal_exists_fn)(data_ptr, goal_id)
668 }
669 }
670 None => false,
671 }
672 }
673
674 pub fn expire_goals(&self, executor: &mut Executor) -> usize {
684 match executor.entries[self.entry_index].as_ref() {
685 Some(meta) => {
686 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
687 unsafe {
688 let data_ptr = arena_ptr.add(meta.offset);
689 (self.expire_goals_fn)(data_ptr)
690 }
691 }
692 None => 0,
693 }
694 }
695
696 pub fn for_each_active_goal(&self, executor: &Executor, mut f: impl FnMut(&ActiveGoal<A>)) {
701 if let Some(meta) = executor.entries[self.entry_index].as_ref() {
702 let arena_ptr = executor.arena.as_ptr() as *const u8;
703 unsafe {
704 let data_ptr = arena_ptr.add(meta.offset);
705 (self.for_each_active_goal_fn)(data_ptr, &mut f);
706 }
707 }
708 }
709}
710
711impl<'s> Executor<'s> {
716 #[doc(hidden)]
725 #[allow(clippy::too_many_arguments)]
726 pub(crate) fn register_action_server_raw(
727 &mut self,
728 spec: RawActionServerSpec<'_>,
729 ) -> Result<ActionServerRawHandle, NodeError> {
730 self.register_action_server_raw_sized::<{ crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, 4>(
731 spec,
732 )
733 }
734
735 #[doc(hidden)]
744 pub fn register_action_server_raw_sized<
745 const GOAL_BUF: usize,
746 const RESULT_BUF: usize,
747 const FEEDBACK_BUF: usize,
748 const MAX_GOALS: usize,
749 >(
750 &mut self,
751 spec: RawActionServerSpec<'_>,
752 ) -> Result<ActionServerRawHandle, NodeError> {
753 let RawActionServerSpec {
754 node_id,
755 action_name,
756 type_name,
757 type_hash,
758 hashes,
759 qos,
760 goal_callback,
761 cancel_callback,
762 accepted_callback,
763 context,
764 } = spec;
765
766 type Entry<const GB: usize, const RB: usize, const FB: usize, const MG: usize> =
767 ActionServerRawArenaEntry<GB, RB, FB, MG>;
768
769 let slot = self.next_entry_slot()?;
770
771 let action_info = ActionInfo::new(action_name, type_name, type_hash);
772 let domain_id = self.domain_id;
776 let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
777
778 let (
787 send_goal_server,
788 cancel_goal_server,
789 get_result_server,
790 feedback_publisher,
791 status_publisher,
792 ) = {
793 let send_goal_server = {
803 let send_goal_type: heapless::String<256> =
804 super::action_core::action_channel_type(type_name, "SendGoal");
805 let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
806 let mut info =
807 ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
808 .with_namespace(&ns)
809 .with_domain(domain_id);
810 if !node_name.is_empty() {
811 info = info.with_node_name(&node_name);
812 }
813 self.session_at_mut(session_idx)
814 .ok_or(NodeError::BackendMismatch)?
815 .create_service(&info, qos)
816 .map_err(NodeError::Transport)?
817 };
818 let cancel_goal_server = {
819 let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
820 let mut info = ServiceInfo::new(
821 &cancel_goal_keyexpr,
822 "action_msgs::srv::dds_::CancelGoal_",
823 hashes.cancel_goal,
824 )
825 .with_namespace(&ns)
826 .with_domain(domain_id);
827 if !node_name.is_empty() {
828 info = info.with_node_name(&node_name);
829 }
830 self.session_at_mut(session_idx)
831 .ok_or(NodeError::BackendMismatch)?
832 .create_service(&info, qos)
833 .map_err(NodeError::Transport)?
834 };
835 let get_result_server = {
836 let get_result_type: heapless::String<256> =
837 super::action_core::action_channel_type(type_name, "GetResult");
838 let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
839 let mut info =
840 ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
841 .with_namespace(&ns)
842 .with_domain(domain_id);
843 if !node_name.is_empty() {
844 info = info.with_node_name(&node_name);
845 }
846 self.session_at_mut(session_idx)
847 .ok_or(NodeError::BackendMismatch)?
848 .create_service(&info, qos)
849 .map_err(NodeError::Transport)?
850 };
851 let feedback_publisher = {
852 let feedback_type: heapless::String<256> =
853 super::action_core::action_channel_type(type_name, "FeedbackMessage");
854 let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
855 let mut info = TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
856 .with_namespace(&ns)
857 .with_domain(domain_id);
858 if !node_name.is_empty() {
859 info = info.with_node_name(&node_name);
860 }
861 self.session_at_mut(session_idx)
862 .ok_or(NodeError::BackendMismatch)?
863 .create_publisher(&info, QoSProfile::QOS_PROFILE_DEFAULT)
864 .map_err(NodeError::Transport)?
865 };
866 let status_publisher = {
867 let status_keyexpr: heapless::String<256> = action_info.status_key();
868 let mut info = TopicInfo::new(
869 &status_keyexpr,
870 "action_msgs::msg::dds_::GoalStatusArray_",
871 hashes.status,
872 )
873 .with_namespace(&ns)
874 .with_domain(domain_id);
875 if !node_name.is_empty() {
876 info = info.with_node_name(&node_name);
877 }
878 self.session_at_mut(session_idx)
879 .ok_or(NodeError::BackendMismatch)?
880 .create_publisher(&info, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
881 .map_err(NodeError::Transport)?
882 };
883 (
884 send_goal_server,
885 cancel_goal_server,
886 get_result_server,
887 feedback_publisher,
888 status_publisher,
889 )
890 };
891
892 let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>()?;
893
894 unsafe {
897 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
898 let entry_ptr =
899 arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>;
900 ActionServerCore::init_in_place(
901 core::ptr::addr_of_mut!((*entry_ptr).core),
902 send_goal_server,
903 cancel_goal_server,
904 get_result_server,
905 feedback_publisher,
906 status_publisher,
907 );
908 core::ptr::addr_of_mut!((*entry_ptr).goal_callback).write(goal_callback);
909 core::ptr::addr_of_mut!((*entry_ptr).cancel_callback).write(cancel_callback);
910 core::ptr::addr_of_mut!((*entry_ptr).accepted_callback).write(accepted_callback);
911 core::ptr::addr_of_mut!((*entry_ptr).context).write(context);
912 let Entry {
915 core: _,
916 goal_callback: _,
917 cancel_callback: _,
918 accepted_callback: _,
919 context: _,
920 } = &*entry_ptr;
921 }
922
923 let meta = CallbackMeta {
924 offset,
925 kind: EntryKind::ActionServer,
926 arena_len: super::arena::ArenaLen::UNRECORDED,
927 has_data: always_ready,
928 pre_sample: no_pre_sample,
929 invocation: InvocationMode::Always,
930 try_process: action_server_raw_try_process::<
931 GOAL_BUF,
932 RESULT_BUF,
933 FEEDBACK_BUF,
934 MAX_GOALS,
935 >,
936 drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>,
937 };
938 self.emplace_entry(slot, meta, TraceName::Text(spec.action_name));
939 self.apply_node_default_sched(slot, node_id, None);
940
941 Ok(ActionServerRawHandle {
942 entry_index: slot,
943 publish_feedback_fn: as_raw_publish_feedback::<
944 GOAL_BUF,
945 RESULT_BUF,
946 FEEDBACK_BUF,
947 MAX_GOALS,
948 >,
949 complete_goal_fn: as_raw_complete_goal::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
950 set_goal_status_fn: as_raw_set_goal_status::<
951 GOAL_BUF,
952 RESULT_BUF,
953 FEEDBACK_BUF,
954 MAX_GOALS,
955 >,
956 active_goal_count_fn: as_raw_active_goal_count::<
957 GOAL_BUF,
958 RESULT_BUF,
959 FEEDBACK_BUF,
960 MAX_GOALS,
961 >,
962 goal_exists_fn: as_raw_goal_exists::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
963 expire_goals_fn: as_raw_expire_goals::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
964 for_each_active_goal_fn: as_raw_for_each_active_goal::<
965 GOAL_BUF,
966 RESULT_BUF,
967 FEEDBACK_BUF,
968 MAX_GOALS,
969 >,
970 })
971 }
972}
973
974unsafe extern "C" fn detached_goal_callback(
993 _goal_id: *const nros_core::GoalUuid,
994 _goal_data: *const u8,
995 _goal_len: usize,
996 _context: *mut core::ffi::c_void,
997) -> nros_core::GoalResponse {
998 nros_core::GoalResponse::Reject
999}
1000
1001unsafe extern "C" fn detached_cancel_callback(
1012 _goal_id: *const nros_core::GoalUuid,
1013 _status: nros_core::GoalStatusCode,
1014 _context: *mut core::ffi::c_void,
1015) -> nros_core::CancelResponse {
1016 nros_core::CancelResponse::Accept
1017}
1018
1019impl<'s> Executor<'s> {
1020 pub(crate) unsafe fn detach_action_server_raw_sized<
1052 const GOAL_BUF: usize,
1053 const RESULT_BUF: usize,
1054 const FEEDBACK_BUF: usize,
1055 const MAX_GOALS: usize,
1056 >(
1057 &mut self,
1058 entry_index: usize,
1059 ) -> bool {
1060 let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1061 return false;
1062 };
1063 if !matches!(meta.kind, EntryKind::ActionServer) {
1064 return false;
1065 }
1066 let offset = meta.offset;
1067 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1068 unsafe {
1069 let entry = &mut *(arena_ptr.add(offset)
1070 as *mut ActionServerRawArenaEntry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>);
1071 entry.goal_callback = detached_goal_callback;
1072 entry.cancel_callback = detached_cancel_callback;
1073 entry.accepted_callback = None;
1074 entry.context = core::ptr::null_mut();
1075 }
1076 true
1077 }
1078
1079 pub(crate) unsafe fn detach_action_server_raw(
1093 &mut self,
1094 handle: &ActionServerRawHandle,
1095 ) -> bool {
1096 unsafe {
1097 self.detach_action_server_raw_sized::<
1098 { crate::config::DEFAULT_RX_BUF_SIZE },
1099 { crate::config::DEFAULT_RX_BUF_SIZE },
1100 { crate::config::DEFAULT_RX_BUF_SIZE },
1101 4,
1102 >(handle.entry_index)
1103 }
1104 }
1105
1106 pub(crate) unsafe fn retarget_action_server_raw(
1121 &mut self,
1122 handle: &ActionServerRawHandle,
1123 context: *mut core::ffi::c_void,
1124 ) -> bool {
1125 let Some(meta) = self
1126 .entries
1127 .get(handle.entry_index)
1128 .and_then(|e| e.as_ref())
1129 else {
1130 return false;
1131 };
1132 if !matches!(meta.kind, EntryKind::ActionServer) {
1133 return false;
1134 }
1135 let offset = meta.offset;
1136 unsafe {
1137 let entry = &mut *((self.arena.as_mut_ptr() as *mut u8).add(offset)
1138 as *mut ActionServerRawArenaEntry<
1139 { crate::config::DEFAULT_RX_BUF_SIZE },
1140 { crate::config::DEFAULT_RX_BUF_SIZE },
1141 { crate::config::DEFAULT_RX_BUF_SIZE },
1142 4,
1143 >);
1144 entry.context = context;
1145 }
1146 true
1147 }
1148
1149 pub(crate) unsafe fn detach_action_client_raw(&mut self, entry_index: usize) -> bool {
1168 let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1169 return false;
1170 };
1171 if !matches!(meta.kind, EntryKind::ActionClient) {
1172 return false;
1173 }
1174 let offset = meta.offset;
1175 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1176 unsafe {
1177 let entry = &mut *(arena_ptr.add(offset)
1178 as *mut ActionClientRawArenaEntry<
1179 { crate::config::DEFAULT_RX_BUF_SIZE },
1180 { crate::config::DEFAULT_RX_BUF_SIZE },
1181 { crate::config::DEFAULT_RX_BUF_SIZE },
1182 >);
1183 entry.goal_response_callback = None;
1184 entry.feedback_callback = None;
1185 entry.result_callback = None;
1186 entry.context = core::ptr::null_mut();
1187 }
1188 true
1189 }
1190
1191 pub(crate) unsafe fn retarget_action_client_raw(
1203 &mut self,
1204 entry_index: usize,
1205 context: *mut core::ffi::c_void,
1206 ) -> bool {
1207 let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1208 return false;
1209 };
1210 if !matches!(meta.kind, EntryKind::ActionClient) {
1211 return false;
1212 }
1213 let offset = meta.offset;
1214 unsafe {
1215 let entry = &mut *((self.arena.as_mut_ptr() as *mut u8).add(offset)
1216 as *mut ActionClientRawArenaEntry<
1217 { crate::config::DEFAULT_RX_BUF_SIZE },
1218 { crate::config::DEFAULT_RX_BUF_SIZE },
1219 { crate::config::DEFAULT_RX_BUF_SIZE },
1220 >);
1221 entry.context = context;
1222 }
1223 true
1224 }
1225
1226 pub(crate) unsafe fn release_action_server_raw_sized<
1249 const GOAL_BUF: usize,
1250 const RESULT_BUF: usize,
1251 const FEEDBACK_BUF: usize,
1252 const MAX_GOALS: usize,
1253 >(
1254 &mut self,
1255 entry_index: usize,
1256 ) -> bool {
1257 unsafe { self.release_entry(entry_index, EntryKind::ActionServer) }
1258 }
1259
1260 pub(crate) unsafe fn release_action_server_raw(
1267 &mut self,
1268 handle: &ActionServerRawHandle,
1269 ) -> bool {
1270 unsafe {
1271 self.release_action_server_raw_sized::<
1272 { crate::config::DEFAULT_RX_BUF_SIZE },
1273 { crate::config::DEFAULT_RX_BUF_SIZE },
1274 { crate::config::DEFAULT_RX_BUF_SIZE },
1275 4,
1276 >(handle.entry_index)
1277 }
1278 }
1279
1280 pub(crate) unsafe fn release_action_client_raw(&mut self, entry_index: usize) -> bool {
1290 unsafe {
1291 self.release_action_client_raw_sized::<
1292 { crate::config::DEFAULT_RX_BUF_SIZE },
1293 { crate::config::DEFAULT_RX_BUF_SIZE },
1294 { crate::config::DEFAULT_RX_BUF_SIZE },
1295 >(entry_index)
1296 }
1297 }
1298
1299 pub(crate) unsafe fn release_action_client_raw_sized<
1307 const GOAL_BUF: usize,
1308 const RESULT_BUF: usize,
1309 const FEEDBACK_BUF: usize,
1310 >(
1311 &mut self,
1312 entry_index: usize,
1313 ) -> bool {
1314 unsafe { self.release_entry(entry_index, EntryKind::ActionClient) }
1315 }
1316}
1317
1318#[repr(C)]
1327#[allow(clippy::type_complexity)]
1328pub struct ActionServerRawHandle {
1329 pub(crate) entry_index: usize,
1330 publish_feedback_fn:
1331 unsafe fn(*mut u8, &nros_core::GoalUuid, *const u8, usize) -> Result<(), NodeError>,
1332 complete_goal_fn: unsafe fn(
1333 *mut u8,
1334 &nros_core::GoalUuid,
1335 nros_core::GoalStatusCode,
1336 *const u8,
1337 usize,
1338 ) -> Result<(), NodeError>,
1339 set_goal_status_fn: unsafe fn(*mut u8, &nros_core::GoalUuid, nros_core::GoalStatusCode),
1340 active_goal_count_fn: unsafe fn(*const u8) -> usize,
1341 goal_exists_fn: unsafe fn(*const u8, &nros_core::GoalUuid) -> bool,
1342 expire_goals_fn: unsafe fn(*mut u8) -> usize,
1343 for_each_active_goal_fn: unsafe fn(*const u8, &mut dyn FnMut(&RawActiveGoal)),
1344}
1345
1346impl Clone for ActionServerRawHandle {
1347 fn clone(&self) -> Self {
1348 *self
1349 }
1350}
1351
1352impl Copy for ActionServerRawHandle {}
1353
1354pub const INVALID_ENTRY_INDEX: usize = usize::MAX;
1362
1363impl ActionServerRawHandle {
1364 pub(crate) const fn invalid() -> Self {
1370 unsafe fn unreachable_publish_feedback(
1371 _: *mut u8,
1372 _: &nros_core::GoalUuid,
1373 _: *const u8,
1374 _: usize,
1375 ) -> Result<(), NodeError> {
1376 unreachable!("ActionServerRawHandle::publish_feedback called on invalid handle")
1377 }
1378 unsafe fn unreachable_complete_goal(
1379 _: *mut u8,
1380 _: &nros_core::GoalUuid,
1381 _: nros_core::GoalStatusCode,
1382 _: *const u8,
1383 _: usize,
1384 ) -> Result<(), NodeError> {
1385 unreachable!("ActionServerRawHandle::complete_goal called on invalid handle")
1386 }
1387 unsafe fn unreachable_set_goal_status(
1388 _: *mut u8,
1389 _: &nros_core::GoalUuid,
1390 _: nros_core::GoalStatusCode,
1391 ) {
1392 unreachable!("ActionServerRawHandle::set_goal_status called on invalid handle")
1393 }
1394 unsafe fn unreachable_active_goal_count(_: *const u8) -> usize {
1395 unreachable!("ActionServerRawHandle::active_goal_count called on invalid handle")
1396 }
1397 unsafe fn unreachable_goal_exists(_: *const u8, _: &nros_core::GoalUuid) -> bool {
1398 unreachable!("ActionServerRawHandle::goal_exists called on invalid handle")
1399 }
1400 unsafe fn unreachable_expire_goals(_: *mut u8) -> usize {
1401 unreachable!("ActionServerRawHandle::expire_goals called on invalid handle")
1402 }
1403 unsafe fn unreachable_for_each_active_goal(
1404 _: *const u8,
1405 _: &mut dyn FnMut(&RawActiveGoal),
1406 ) {
1407 unreachable!("ActionServerRawHandle::for_each_active_goal called on invalid handle")
1408 }
1409 Self {
1410 entry_index: INVALID_ENTRY_INDEX,
1411 publish_feedback_fn: unreachable_publish_feedback,
1412 complete_goal_fn: unreachable_complete_goal,
1413 set_goal_status_fn: unreachable_set_goal_status,
1414 active_goal_count_fn: unreachable_active_goal_count,
1415 goal_exists_fn: unreachable_goal_exists,
1416 expire_goals_fn: unreachable_expire_goals,
1417 for_each_active_goal_fn: unreachable_for_each_active_goal,
1418 }
1419 }
1420
1421 pub(crate) const fn is_invalid(&self) -> bool {
1423 self.entry_index == INVALID_ENTRY_INDEX
1424 }
1425}
1426
1427impl Default for ActionServerRawHandle {
1428 fn default() -> Self {
1429 Self::invalid()
1430 }
1431}
1432
1433impl ActionServerRawHandle {
1434 pub(crate) fn handle_id(&self) -> HandleId {
1436 HandleId::for_owned_slot(self.entry_index)
1437 }
1438
1439 pub(crate) fn publish_feedback_raw(
1443 &self,
1444 executor: &mut Executor,
1445 goal_id: &nros_core::GoalUuid,
1446 feedback_data: &[u8],
1447 ) -> Result<(), NodeError> {
1448 let meta = executor.entries[self.entry_index]
1449 .as_ref()
1450 .ok_or(NodeError::BufferTooSmall)?;
1451 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1452 unsafe {
1453 let data_ptr = arena_ptr.add(meta.offset);
1454 (self.publish_feedback_fn)(
1455 data_ptr,
1456 goal_id,
1457 feedback_data.as_ptr(),
1458 feedback_data.len(),
1459 )
1460 }
1461 }
1462
1463 pub(crate) fn complete_goal_raw(
1474 &self,
1475 executor: &mut Executor,
1476 goal_id: &nros_core::GoalUuid,
1477 status: nros_core::GoalStatusCode,
1478 result_data: &[u8],
1479 ) -> Result<(), NodeError> {
1480 let meta = executor.entries[self.entry_index]
1481 .as_ref()
1482 .ok_or(NodeError::BufferTooSmall)?;
1483 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1484 unsafe {
1485 let data_ptr = arena_ptr.add(meta.offset);
1486 (self.complete_goal_fn)(
1487 data_ptr,
1488 goal_id,
1489 status,
1490 result_data.as_ptr(),
1491 result_data.len(),
1492 )
1493 }
1494 }
1495
1496 pub(crate) fn set_goal_status(
1501 &self,
1502 executor: &mut Executor,
1503 goal_id: &nros_core::GoalUuid,
1504 status: nros_core::GoalStatusCode,
1505 ) {
1506 if let Some(meta) = executor.entries[self.entry_index].as_ref() {
1507 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1508 unsafe {
1509 let data_ptr = arena_ptr.add(meta.offset);
1510 (self.set_goal_status_fn)(data_ptr, goal_id, status);
1511 }
1512 }
1513 }
1514
1515 pub(crate) fn active_goal_count(&self, executor: &Executor) -> usize {
1519 match executor.entries[self.entry_index].as_ref() {
1520 Some(meta) => {
1521 let arena_ptr = executor.arena.as_ptr() as *const u8;
1522 unsafe {
1523 let data_ptr = arena_ptr.add(meta.offset);
1524 (self.active_goal_count_fn)(data_ptr)
1525 }
1526 }
1527 None => 0,
1528 }
1529 }
1530
1531 pub(crate) fn goal_exists(&self, executor: &Executor, goal_id: &nros_core::GoalUuid) -> bool {
1538 match executor.entries[self.entry_index].as_ref() {
1539 Some(meta) => {
1540 let arena_ptr = executor.arena.as_ptr() as *const u8;
1541 unsafe {
1542 let data_ptr = arena_ptr.add(meta.offset);
1543 (self.goal_exists_fn)(data_ptr, goal_id)
1544 }
1545 }
1546 None => false,
1547 }
1548 }
1549
1550 pub(crate) fn expire_goals(&self, executor: &mut Executor) -> usize {
1554 match executor.entries[self.entry_index].as_ref() {
1555 Some(meta) => {
1556 let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1557 unsafe {
1558 let data_ptr = arena_ptr.add(meta.offset);
1559 (self.expire_goals_fn)(data_ptr)
1560 }
1561 }
1562 None => 0,
1563 }
1564 }
1565
1566 pub(crate) fn for_each_active_goal(
1570 &self,
1571 executor: &Executor,
1572 mut f: impl FnMut(&RawActiveGoal),
1573 ) {
1574 if let Some(meta) = executor.entries[self.entry_index].as_ref() {
1575 let arena_ptr = executor.arena.as_ptr() as *const u8;
1576 unsafe {
1577 let data_ptr = arena_ptr.add(meta.offset);
1578 (self.for_each_active_goal_fn)(data_ptr, &mut f);
1579 }
1580 }
1581 }
1582
1583 pub(crate) fn goal_status(
1593 &self,
1594 executor: &Executor,
1595 goal_id: &nros_core::GoalUuid,
1596 ) -> Option<nros_core::GoalStatusCode> {
1597 let mut found = None;
1598 self.for_each_active_goal(executor, |g| {
1599 if g.goal_id.uuid == goal_id.uuid && found.is_none() {
1600 found = Some(g.status);
1601 }
1602 });
1603 found
1604 }
1605}
1606
1607impl<'s> Executor<'s> {
1612 #[doc(hidden)]
1627 #[allow(clippy::too_many_arguments)]
1628 pub(crate) fn register_action_client_raw(
1629 &mut self,
1630 spec: RawActionClientSpec<'_>,
1631 ) -> Result<ActionClientRawHandle, NodeError> {
1632 self.register_action_client_raw_sized::<
1633 { crate::config::DEFAULT_RX_BUF_SIZE },
1634 { crate::config::DEFAULT_RX_BUF_SIZE },
1635 { crate::config::DEFAULT_RX_BUF_SIZE },
1636 >(spec)
1637 }
1638
1639 #[doc(hidden)]
1645 pub fn register_action_client_raw_sized<
1646 const GOAL_BUF: usize,
1647 const RESULT_BUF: usize,
1648 const FEEDBACK_BUF: usize,
1649 >(
1650 &mut self,
1651 spec: RawActionClientSpec<'_>,
1652 ) -> Result<ActionClientRawHandle, NodeError> {
1653 let RawActionClientSpec {
1654 node_id,
1655 action_name,
1656 type_name,
1657 type_hash,
1658 hashes,
1659 goal_response_callback,
1660 feedback_callback,
1661 result_callback,
1662 cancel_response_callback,
1663 context,
1664 } = spec;
1665
1666 type Entry<const GB: usize, const RB: usize, const FB: usize> =
1667 ActionClientRawArenaEntry<GB, RB, FB>;
1668
1669 let slot = self.next_entry_slot()?;
1670
1671 let action_info = ActionInfo::new(action_name, type_name, type_hash);
1672 let domain_id = self.domain_id;
1676 let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
1677
1678 let (send_goal_client, cancel_goal_client, get_result_client, feedback_sub) = {
1679 let send_goal_type: heapless::String<256> =
1684 super::action_core::action_channel_type(type_name, "SendGoal");
1685 let get_result_type: heapless::String<256> =
1686 super::action_core::action_channel_type(type_name, "GetResult");
1687 let feedback_type: heapless::String<256> =
1688 super::action_core::action_channel_type(type_name, "FeedbackMessage");
1689
1690 let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1691 let mut send_goal_info =
1692 ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
1693 .with_namespace(&ns)
1694 .with_domain(domain_id);
1695 if !node_name.is_empty() {
1696 send_goal_info = send_goal_info.with_node_name(&node_name);
1697 }
1698
1699 let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1700 let mut cancel_goal_info = ServiceInfo::new(
1701 &cancel_goal_keyexpr,
1702 "action_msgs::srv::dds_::CancelGoal_",
1703 hashes.cancel_goal,
1704 )
1705 .with_namespace(&ns)
1706 .with_domain(domain_id);
1707 if !node_name.is_empty() {
1708 cancel_goal_info = cancel_goal_info.with_node_name(&node_name);
1709 }
1710
1711 let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1712 let mut get_result_info =
1713 ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
1714 .with_namespace(&ns)
1715 .with_domain(domain_id);
1716 if !node_name.is_empty() {
1717 get_result_info = get_result_info.with_node_name(&node_name);
1718 }
1719
1720 let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1721 let mut feedback_topic =
1722 TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
1723 .with_namespace(&ns)
1724 .with_domain(domain_id);
1725 if !node_name.is_empty() {
1726 feedback_topic = feedback_topic.with_node_name(&node_name);
1727 }
1728
1729 let session = self
1730 .session_at_mut(session_idx)
1731 .ok_or(NodeError::BackendMismatch)?;
1732 (
1742 session
1743 .create_client(&send_goal_info, QoSProfile::services_default())
1744 .map_err(|e| {
1745 nros_log::log_error!(
1746 nros_log::get_logger("nros_node"),
1747 "action client: send_goal client failed: {:?}",
1748 e
1749 );
1750 NodeError::Transport(e)
1751 })?,
1752 session
1753 .create_client(&cancel_goal_info, QoSProfile::services_default())
1754 .map_err(|e| {
1755 nros_log::log_error!(
1756 nros_log::get_logger("nros_node"),
1757 "action client: cancel_goal client failed: {:?}",
1758 e
1759 );
1760 NodeError::Transport(e)
1761 })?,
1762 session
1763 .create_client(&get_result_info, QoSProfile::services_default())
1764 .map_err(|e| {
1765 nros_log::log_error!(
1766 nros_log::get_logger("nros_node"),
1767 "action client: get_result client failed: {:?}",
1768 e
1769 );
1770 NodeError::Transport(e)
1771 })?,
1772 session
1773 .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1774 .map_err(|e| {
1775 nros_log::log_error!(
1776 nros_log::get_logger("nros_node"),
1777 "action client: feedback subscription failed: {:?}",
1778 e
1779 );
1780 NodeError::Transport(e)
1781 })?,
1782 )
1783 };
1784
1785 let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>()?;
1786
1787 unsafe {
1790 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1791 let entry_ptr = arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
1792 ActionClientCore::init_in_place(
1793 core::ptr::addr_of_mut!((*entry_ptr).core),
1794 send_goal_client,
1795 cancel_goal_client,
1796 get_result_client,
1797 feedback_sub,
1798 );
1799 core::ptr::addr_of_mut!((*entry_ptr).goal_response_callback)
1800 .write(goal_response_callback);
1801 core::ptr::addr_of_mut!((*entry_ptr).feedback_callback).write(feedback_callback);
1802 core::ptr::addr_of_mut!((*entry_ptr).result_callback).write(result_callback);
1803 core::ptr::addr_of_mut!((*entry_ptr).cancel_response_callback)
1804 .write(cancel_response_callback);
1805 core::ptr::addr_of_mut!((*entry_ptr).context).write(context);
1806 let Entry {
1809 core: _,
1810 goal_response_callback: _,
1811 feedback_callback: _,
1812 result_callback: _,
1813 cancel_response_callback: _,
1814 context: _,
1815 } = &*entry_ptr;
1816 }
1817
1818 let meta = CallbackMeta {
1819 offset,
1820 kind: EntryKind::ActionClient,
1821 arena_len: super::arena::ArenaLen::UNRECORDED,
1822 has_data: always_ready,
1823 pre_sample: no_pre_sample,
1824 invocation: InvocationMode::Always,
1825 try_process: action_client_raw_try_process::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
1826 drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
1827 };
1828 self.emplace_entry(slot, meta, TraceName::Text(spec.action_name));
1829 self.apply_node_default_sched(slot, node_id, None);
1830
1831 Ok(ActionClientRawHandle { entry_index: slot })
1832 }
1833
1834 #[allow(clippy::too_many_arguments, clippy::type_complexity)]
1841 pub(crate) fn register_action_client_callback<
1842 A,
1843 GRespF,
1844 FbF,
1845 ResF,
1846 const GOAL_BUF: usize,
1847 const RESULT_BUF: usize,
1848 const FEEDBACK_BUF: usize,
1849 >(
1850 &mut self,
1851 node_id: Option<super::node_record::NodeId>,
1852 action_name: &str,
1853 type_name: &str,
1854 type_hash: &str,
1855 feedback_depth: u16,
1856 on_goal_response: GRespF,
1857 on_feedback: FbF,
1858 on_result: ResF,
1859 ) -> Result<
1860 (
1861 HandleId,
1862 *mut ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
1863 ),
1864 NodeError,
1865 >
1866 where
1867 A: nros_core::RosAction + 'static,
1868 GRespF: FnMut(&nros_core::GoalUuid, bool) + 'static,
1869 FbF: FnMut(&nros_core::GoalUuid, &A::Feedback) + 'static,
1870 ResF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode, &A::Result) + 'static,
1871 {
1872 type Entry<A, G, Fb, R, const GB: usize, const RB: usize, const FB: usize> =
1873 ActionClientCallbackEntry<A, G, Fb, R, GB, RB, FB>;
1874
1875 let slot = self.next_entry_slot()?;
1876 let action_info = ActionInfo::new(action_name, type_name, type_hash);
1877 let hashes = ActionEndpointHashes::of::<A>();
1879 A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
1885 let domain_id = self.domain_id;
1889 let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
1890
1891 let (send_goal_client, cancel_goal_client, get_result_client, feedback_sub) = {
1892 let send_goal_type: heapless::String<256> =
1897 super::action_core::action_channel_type(type_name, "SendGoal");
1898 let get_result_type: heapless::String<256> =
1899 super::action_core::action_channel_type(type_name, "GetResult");
1900 let feedback_type: heapless::String<256> =
1901 super::action_core::action_channel_type(type_name, "FeedbackMessage");
1902
1903 let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1904 let mut send_goal_info =
1905 ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
1906 .with_namespace(&ns)
1907 .with_domain(domain_id);
1908 if !node_name.is_empty() {
1909 send_goal_info = send_goal_info.with_node_name(&node_name);
1910 }
1911 let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1912 let mut cancel_goal_info = ServiceInfo::new(
1913 &cancel_goal_keyexpr,
1914 "action_msgs::srv::dds_::CancelGoal_",
1915 hashes.cancel_goal,
1916 )
1917 .with_namespace(&ns)
1918 .with_domain(domain_id);
1919 if !node_name.is_empty() {
1920 cancel_goal_info = cancel_goal_info.with_node_name(&node_name);
1921 }
1922 let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1923 let mut get_result_info =
1924 ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
1925 .with_namespace(&ns)
1926 .with_domain(domain_id);
1927 if !node_name.is_empty() {
1928 get_result_info = get_result_info.with_node_name(&node_name);
1929 }
1930 let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1931 let mut feedback_topic =
1932 TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
1933 .with_namespace(&ns)
1934 .with_domain(domain_id);
1935 if !node_name.is_empty() {
1936 feedback_topic = feedback_topic.with_node_name(&node_name);
1937 }
1938 let session = self
1939 .session_at_mut(session_idx)
1940 .ok_or(NodeError::BackendMismatch)?;
1941 (
1942 session
1943 .create_client(&send_goal_info, QoSProfile::services_default())
1944 .map_err(NodeError::Transport)?,
1945 session
1946 .create_client(&cancel_goal_info, QoSProfile::services_default())
1947 .map_err(NodeError::Transport)?,
1948 session
1949 .create_client(&get_result_info, QoSProfile::services_default())
1950 .map_err(NodeError::Transport)?,
1951 session
1952 .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1953 .map_err(NodeError::Transport)?,
1954 )
1955 };
1956
1957 let core = ActionClientCore::new(
1958 send_goal_client,
1959 cancel_goal_client,
1960 get_result_client,
1961 feedback_sub,
1962 );
1963
1964 let (_slot_count, trailing_bytes) =
1968 buffered_region_size(feedback_depth as u32, FEEDBACK_BUF);
1969 let (offset, trailing_offset) = self.arena_alloc_with_trailing::<Entry<
1970 A,
1971 GRespF,
1972 FbF,
1973 ResF,
1974 GOAL_BUF,
1975 RESULT_BUF,
1976 FEEDBACK_BUF,
1977 >>(trailing_bytes)?;
1978 let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
1979 let feedback_buffer = if feedback_depth <= 1 {
1980 BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, FEEDBACK_BUF) })
1981 } else {
1982 BufferStrategy::Ring(unsafe {
1983 SpscRing::init(buf_ptr, FEEDBACK_BUF, feedback_depth as usize)
1984 })
1985 };
1986 let core_ptr = unsafe {
1987 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1988 let entry_ptr = arena_ptr.add(offset)
1989 as *mut Entry<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
1990 core::ptr::write(
1991 entry_ptr,
1992 ActionClientCallbackEntry {
1993 core,
1994 feedback_buffer,
1995 on_goal_response,
1996 on_feedback,
1997 on_result,
1998 _phantom: core::marker::PhantomData,
1999 },
2000 );
2001 core::ptr::addr_of_mut!((*entry_ptr).core)
2006 };
2007
2008 let meta = CallbackMeta {
2009 offset,
2010 kind: EntryKind::ActionClient,
2011 arena_len: super::arena::ArenaLen::UNRECORDED,
2012 has_data: always_ready,
2013 pre_sample: no_pre_sample,
2014 invocation: InvocationMode::Always,
2015 try_process: action_client_callback_try_process::<
2016 A,
2017 GRespF,
2018 FbF,
2019 ResF,
2020 GOAL_BUF,
2021 RESULT_BUF,
2022 FEEDBACK_BUF,
2023 >,
2024 drop_fn: drop_entry::<Entry<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
2025 };
2026 self.emplace_entry(slot, meta, TraceName::Text(action_name));
2027 self.apply_node_default_sched(slot, node_id, None);
2028 Ok((self.handle_for(slot), core_ptr))
2029 }
2030}
2031
2032impl<'s> Executor<'s> {
2033 #[doc(hidden)]
2039 pub(crate) fn register_action_client_core<
2040 const GOAL_BUF: usize,
2041 const RESULT_BUF: usize,
2042 const FEEDBACK_BUF: usize,
2043 >(
2044 &mut self,
2045 core: ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2046 goal_response_callback: Option<RawGoalResponseCallback>,
2047 feedback_callback: Option<RawFeedbackCallback>,
2048 result_callback: Option<RawResultCallback>,
2049 cancel_response_callback: Option<RawCancelResponseCallback>,
2050 context: *mut core::ffi::c_void,
2051 ) -> Result<ActionClientRawHandle, NodeError> {
2052 type Entry<const GB: usize, const RB: usize, const FB: usize> =
2053 ActionClientRawArenaEntry<GB, RB, FB>;
2054
2055 let slot = self.next_entry_slot()?;
2056 let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>()?;
2057
2058 unsafe {
2059 let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
2060 let entry_ptr = arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
2061 core::ptr::write(
2062 entry_ptr,
2063 Entry {
2064 core,
2065 goal_response_callback,
2066 feedback_callback,
2067 result_callback,
2068 cancel_response_callback,
2069 context,
2070 },
2071 );
2072 }
2073
2074 let meta = CallbackMeta {
2075 offset,
2076 kind: EntryKind::ActionClient,
2077 arena_len: super::arena::ArenaLen::UNRECORDED,
2078 has_data: always_ready,
2079 pre_sample: no_pre_sample,
2080 invocation: InvocationMode::Always,
2081 try_process: action_client_raw_try_process::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2082 drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
2083 };
2084 self.emplace_entry(slot, meta, TraceName::Slot("action_client", slot));
2085
2086 Ok(ActionClientRawHandle { entry_index: slot })
2087 }
2088}
2089
2090pub struct ActionClientRawHandle {
2095 entry_index: usize,
2096}
2097
2098impl ActionClientRawHandle {
2099 pub(crate) fn entry_index(&self) -> usize {
2101 self.entry_index
2102 }
2103}
2104
2105#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
2112mod terminal_verb_tests {
2113 use super::*;
2114 use core::sync::atomic::{AtomicI8, Ordering};
2115 use nros_core::{CdrReader, CdrWriter, DeserError, Deserialize, SerError, Serialize};
2116 use nros_rmw::TransportError;
2117
2118 use crate::mock::MockSession;
2119
2120 static LAST_STATUS: AtomicI8 = AtomicI8::new(-1);
2124
2125 #[derive(Default)]
2126 struct Unit;
2127
2128 impl Serialize for Unit {
2129 fn serialize(&self, _w: &mut CdrWriter) -> Result<(), SerError> {
2130 Ok(())
2131 }
2132 }
2133 impl Deserialize for Unit {
2134 fn deserialize(_r: &mut CdrReader) -> Result<Self, DeserError> {
2135 Ok(Self)
2136 }
2137 }
2138 impl nros_core::RosMessage for Unit {
2139 const TYPE_NAME: &'static str = "test/action/Verbs_Unit";
2140 const TYPE_HASH: &'static str = "test_hash";
2141 }
2142
2143 struct VerbAction;
2144
2145 impl RosAction for VerbAction {
2146 type Goal = Unit;
2147 type Result = Unit;
2148 type Feedback = Unit;
2149 type SendGoalRequest = Unit;
2150 type SendGoalResponse = Unit;
2151 type GetResultRequest = Unit;
2152 type GetResultResponse = Unit;
2153 type FeedbackMessage = Unit;
2154 const ACTION_NAME: &'static str = "test/action/dds_/Verbs_";
2155 const ACTION_HASH: &'static str = "test_hash";
2156 }
2157
2158 unsafe fn record_status(
2159 _data: *mut u8,
2160 _goal_id: &nros_core::GoalUuid,
2161 status: nros_core::GoalStatusCode,
2162 _result: Unit,
2163 ) -> Result<(), NodeError> {
2164 LAST_STATUS.store(status as i8, Ordering::SeqCst);
2165 Ok(())
2166 }
2167
2168 unsafe fn unused_feedback(
2169 _data: *mut u8,
2170 _goal_id: &nros_core::GoalUuid,
2171 _fb: &Unit,
2172 ) -> Result<(), NodeError> {
2173 unreachable!("the terminal-verb test never publishes feedback")
2174 }
2175
2176 unsafe fn unused_set_status(
2177 _data: *mut u8,
2178 _goal_id: &nros_core::GoalUuid,
2179 _status: nros_core::GoalStatusCode,
2180 ) {
2181 unreachable!("the terminal-verb test never sets a non-terminal status")
2182 }
2183
2184 unsafe fn unused_count(_data: *const u8) -> usize {
2185 unreachable!("the terminal-verb test never counts active goals")
2186 }
2187
2188 unsafe fn unused_for_each(_data: *const u8, _f: &mut dyn FnMut(&ActiveGoal<VerbAction>)) {
2189 unreachable!("the terminal-verb test never iterates active goals")
2190 }
2191
2192 unsafe fn unused_goal_exists(_data: *const u8, _goal_id: &nros_core::GoalUuid) -> bool {
2193 unreachable!("the terminal-verb test never asks whether a goal exists")
2194 }
2195
2196 unsafe fn unused_expire_goals(_data: *mut u8) -> usize {
2197 unreachable!("the terminal-verb test never expires goals")
2198 }
2199
2200 unsafe fn never_processes(
2201 _data: *mut u8,
2202 _delta_us: u64,
2203 _slot: u8,
2204 ) -> Result<bool, TransportError> {
2205 Ok(false)
2206 }
2207
2208 unsafe fn drops_nothing(_data: *mut u8) {}
2209
2210 fn handle() -> ActionServerHandle<VerbAction> {
2211 ActionServerHandle {
2212 entry_index: 0,
2213 publish_feedback_fn: unused_feedback,
2214 complete_goal_fn: record_status,
2215 set_goal_status_fn: unused_set_status,
2216 active_goal_count_fn: unused_count,
2217 goal_exists_fn: unused_goal_exists,
2218 expire_goals_fn: unused_expire_goals,
2219 for_each_active_goal_fn: unused_for_each,
2220 _phantom: PhantomData,
2221 }
2222 }
2223
2224 fn meta() -> CallbackMeta {
2225 CallbackMeta {
2226 offset: 0,
2227 kind: EntryKind::ActionServer,
2228 arena_len: crate::executor::arena::ArenaLen::UNRECORDED,
2229 try_process: never_processes,
2230 has_data: always_ready,
2231 pre_sample: no_pre_sample,
2232 invocation: InvocationMode::OnNewData,
2233 drop_fn: drops_nothing,
2234 }
2235 }
2236
2237 #[test]
2246 fn terminal_verbs_carry_their_spec_state_and_cancel_forwards_to_canceled() {
2247 let mut executor = Executor::from_session(MockSession::new());
2248 executor.entries[0] = Some(meta());
2249
2250 let h = handle();
2251 let goal = nros_core::GoalUuid::zero();
2252
2253 LAST_STATUS.store(-1, Ordering::SeqCst);
2254 h.succeed(&mut executor, &goal, Unit).unwrap();
2255 assert_eq!(
2256 LAST_STATUS.load(Ordering::SeqCst),
2257 nros_core::GoalStatusCode::Succeeded as i8,
2258 "succeed() must terminate the goal as SUCCEEDED"
2259 );
2260
2261 LAST_STATUS.store(-1, Ordering::SeqCst);
2262 h.abort(&mut executor, &goal, Unit).unwrap();
2263 assert_eq!(
2264 LAST_STATUS.load(Ordering::SeqCst),
2265 nros_core::GoalStatusCode::Aborted as i8,
2266 "abort() must terminate the goal as ABORTED"
2267 );
2268
2269 LAST_STATUS.store(-1, Ordering::SeqCst);
2273 h.canceled(&mut executor, &goal, Unit).unwrap();
2274 assert_eq!(
2275 LAST_STATUS.load(Ordering::SeqCst),
2276 nros_core::GoalStatusCode::Canceled as i8,
2277 "canceled() must terminate the goal as CANCELED"
2278 );
2279
2280 executor.entries[0] = None;
2283 }
2284}