use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use crate::bus::{OwnerCap, RobotInstant, StepToken, TimelineId};
use crate::model::v0::Robot;
use crate::participant::managed::{ManagedTaskPolicy, ManagedTasks};
use phoxal_bus::Bus;
pub struct SetupContext<R> {
bus: Bus,
owner_cap: OwnerCap,
robot: Option<Arc<Robot>>,
robot_root: Option<PathBuf>,
component_instance: Option<String>,
managed_tasks: ManagedTasks,
_runtime: PhantomData<fn() -> R>,
}
impl<R> SetupContext<R> {
pub(crate) fn new(
bus: Bus,
owner_cap: OwnerCap,
robot: Option<Arc<Robot>>,
robot_root: Option<PathBuf>,
component_instance: Option<String>,
) -> Self {
SetupContext {
bus,
owner_cap,
robot,
robot_root,
component_instance,
managed_tasks: ManagedTasks::default(),
_runtime: PhantomData,
}
}
pub fn spawn_managed<F>(&mut self, name: impl Into<String>, future: F)
where
F: std::future::Future<Output = ()> + Send + 'static,
{
self.spawn_managed_with(name, ManagedTaskPolicy::FaultOnExit, future);
}
pub fn spawn_managed_with<F>(
&mut self,
name: impl Into<String>,
policy: ManagedTaskPolicy,
future: F,
) where
F: std::future::Future<Output = ()> + Send + 'static,
{
self.managed_tasks.spawn(name, policy, future);
}
pub(crate) fn take_managed_tasks(&mut self) -> ManagedTasks {
std::mem::take(&mut self.managed_tasks)
}
pub(crate) fn bus(&self) -> &Bus {
&self.bus
}
pub(crate) fn owner_cap(&self) -> OwnerCap {
self.owner_cap
}
pub(crate) fn component_instance(&self) -> Option<&str> {
self.component_instance.as_deref()
}
pub(crate) fn robot_ref(&self) -> Option<&Robot> {
self.robot.as_deref()
}
pub(crate) fn robot_root_ref(&self) -> Option<&Path> {
self.robot_root.as_deref()
}
}
#[derive(Clone, Copy, Debug)]
pub struct StepContext {
token: StepToken,
step_index: u64,
dt: Duration,
missed_ticks: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ResetContext {
previous_timeline: TimelineId,
new_timeline: TimelineId,
}
impl ResetContext {
pub(crate) fn new(previous_timeline: TimelineId, new_timeline: TimelineId) -> Self {
Self {
previous_timeline,
new_timeline,
}
}
pub fn previous_timeline(&self) -> TimelineId {
self.previous_timeline
}
pub fn new_timeline(&self) -> TimelineId {
self.new_timeline
}
}
impl StepContext {
pub(crate) fn new(token: StepToken, step_index: u64, dt: Duration, missed_ticks: u32) -> Self {
StepContext {
token,
step_index,
dt,
missed_ticks,
}
}
pub fn token(&self) -> &StepToken {
&self.token
}
pub fn now(&self) -> RobotInstant {
crate::bus::StepStamp::instant(&self.token)
}
pub fn timeline(&self) -> TimelineId {
self.now().timeline()
}
pub fn step_index(&self) -> u64 {
self.step_index
}
pub fn dt(&self) -> Duration {
self.dt
}
pub fn missed_ticks(&self) -> u32 {
self.missed_ticks
}
}
#[derive(Clone, Copy, Debug)]
pub struct ShutdownContext {
grace: Duration,
}
impl ShutdownContext {
pub(crate) fn new(grace: Duration) -> Self {
ShutdownContext { grace }
}
pub fn grace(&self) -> Duration {
self.grace
}
}