use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use crate::bus::{LogicalTime, OwnerCap};
use crate::model::v0::Robot;
use crate::participant::launch::ExecutionDeviceId;
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>,
execution_device_id: Option<ExecutionDeviceId>,
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>,
execution_device_id: Option<ExecutionDeviceId>,
) -> Self {
SetupContext {
bus,
owner_cap,
robot,
robot_root,
component_instance,
execution_device_id,
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 execution_device_id_ref(&self) -> Option<&ExecutionDeviceId> {
self.execution_device_id.as_ref()
}
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 {
epoch: u64,
step_index: u64,
time_ns: u64,
dt_ns: u64,
missed_ticks: u32,
}
impl StepContext {
pub(crate) fn new(
epoch: u64,
step_index: u64,
time_ns: u64,
dt_ns: u64,
missed_ticks: u32,
) -> Self {
StepContext {
epoch,
step_index,
time_ns,
dt_ns,
missed_ticks,
}
}
pub fn time(&self) -> LogicalTime {
LogicalTime::new(self.epoch, self.time_ns)
}
pub fn epoch(&self) -> u64 {
self.epoch
}
pub fn step_index(&self) -> u64 {
self.step_index
}
pub fn dt_ns(&self) -> u64 {
self.dt_ns
}
pub fn dt(&self) -> Duration {
Duration::from_nanos(self.dt_ns)
}
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
}
}