use std::collections::BTreeMap;
use std::time::Duration;
use crate::records::{MaterialName, SafetyEnvelope, SheetId};
use printobserver_types::PrintId;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_vision_api::WebAddress;
pub const PRINT_ID_PLACEHOLDER: &str = "{print_id}";
pub const DEFAULT_EXPIRY_POLL: Duration = Duration::from_millis(250);
pub const DEFAULT_RECENT_EVENTS: u32 = 20;
pub const DEFAULT_DETECTOR_RESUME_GRACE: Duration = Duration::from_secs(20);
pub const DEFAULT_OBSERVATION_INTERVAL: Duration = Duration::from_secs(120);
pub const MAX_LOOK_WAIT_S: u32 = 90;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
pub enum PreflightMode {
#[default]
Refuse,
Warn,
Off,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde", default, deny_unknown_fields)]
pub struct SpoolPolicy {
pub preflight: PreflightMode,
pub buffer_percent: f64,
pub buffer_min_g: f64,
pub analysis_wait_s: u64,
}
impl Default for SpoolPolicy {
fn default() -> Self {
Self {
preflight: PreflightMode::Refuse,
buffer_percent: 10.0,
buffer_min_g: 5.0,
analysis_wait_s: 300,
}
}
}
pub const DEFAULT_SHEETS: [(&str, &[&str]); 2] =
[("PLA", &["smooth-pei"]), ("PETG", &["textured-pei"])];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheetTable {
entries: BTreeMap<MaterialName, Vec<SheetId>>,
}
impl SheetTable {
pub fn new(entries: BTreeMap<String, Vec<String>>) -> Result<Self, String> {
let mut table: BTreeMap<MaterialName, Vec<SheetId>> = BTreeMap::new();
for (material, sheets) in entries {
let material = MaterialName::try_from(material)?;
if table.keys().any(|listed| listed.same(&material)) {
return Err(format!(
"{material} is listed twice, once differing only in case or space"
));
}
if sheets.is_empty() {
return Err(format!(
"{material} lists no sheet; leave a material out rather than list it on none"
));
}
let sheets = sheets
.into_iter()
.map(SheetId::try_from)
.collect::<Result<Vec<_>, _>>()
.map_err(|why| format!("{material} lists a sheet that is blank: {why}"))?;
table.insert(material, sheets);
}
Ok(Self { entries: table })
}
#[must_use]
pub fn allowed_for(&self, material: &MaterialName) -> Option<&[SheetId]> {
self.entries
.iter()
.find(|(listed, _)| listed.same(material))
.map(|(_, sheets)| sheets.as_slice())
}
#[must_use]
pub fn lists(&self, sheet: &SheetId) -> bool {
self.entries
.values()
.flatten()
.any(|listed| listed.same(sheet))
}
#[must_use]
pub fn sheets(&self) -> Vec<SheetId> {
let mut known: Vec<SheetId> = Vec::new();
for sheet in self.entries.values().flatten() {
if !known.iter().any(|listed| listed.same(sheet)) {
known.push(sheet.clone());
}
}
known.sort();
known
}
}
impl Default for SheetTable {
fn default() -> Self {
Self::new(
DEFAULT_SHEETS
.iter()
.map(|(material, sheets)| {
(
(*material).to_owned(),
sheets.iter().map(|sheet| (*sheet).to_owned()).collect(),
)
})
.collect(),
)
.unwrap_or_else(|why| unreachable!("the default sheet table is a table: {why}"))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CoreConfig {
pub envelope: SafetyEnvelope,
pub context_command: String,
pub recent_events: u32,
pub expiry_poll: Duration,
pub camera_snapshot_url: Option<WebAddress>,
pub camera_retry: crate::look::CameraRetry,
pub detector_resume_grace: Duration,
pub observation_interval: Duration,
pub spools: SpoolPolicy,
pub sheets: SheetTable,
pub printer_poll: Duration,
pub unattended_window: Duration,
pub recovery: Option<crate::records::RecoveryConfig>,
pub recovery_grants: crate::records::RecoveryGrants,
pub gcode_spool_dir: Option<std::path::PathBuf>,
}
impl CoreConfig {
#[must_use]
pub fn new(envelope: SafetyEnvelope, context_command: String) -> Self {
Self {
envelope,
context_command,
recent_events: DEFAULT_RECENT_EVENTS,
expiry_poll: DEFAULT_EXPIRY_POLL,
camera_snapshot_url: None,
camera_retry: crate::look::CameraRetry::default(),
detector_resume_grace: DEFAULT_DETECTOR_RESUME_GRACE,
observation_interval: DEFAULT_OBSERVATION_INTERVAL,
spools: SpoolPolicy::default(),
sheets: SheetTable::default(),
printer_poll: crate::watch::DEFAULT_PRINTER_POLL,
unattended_window: crate::watch::DEFAULT_UNATTENDED_WINDOW,
recovery: None,
recovery_grants: crate::records::RecoveryGrants::default(),
gcode_spool_dir: None,
}
}
#[must_use]
pub fn context_command_for(&self, print_id: PrintId) -> String {
self.context_command
.replace(PRINT_ID_PLACEHOLDER, &print_id.to_string())
}
}