use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::collections::BTreeMap;
use weft_parts::BusKind;
const BUILTIN: &[(&str, &str)] = &[(
"raspberry-pi-40pin",
include_str!("../data/hosts/raspberry-pi-40pin.toml"),
)];
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bus {
pub labels: Vec<String>,
pub kind: BusKind,
pub signals: BTreeMap<String, u32>,
#[serde(default)]
pub cs: Vec<u32>,
}
impl Bus {
pub fn name(&self) -> &str {
self.labels.first().map_or("?", String::as_str)
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Host {
pub name: String,
pub gpio_label: String,
pub gpio_cells: usize,
pub interrupt_cells: usize,
pub ground_pins: Vec<String>,
#[serde(default)]
pub power_pins: BTreeMap<String, Vec<String>>,
pub gpio_pins: BTreeMap<String, u32>,
pub bus: Vec<Bus>,
}
impl Host {
pub fn builtin_names() -> impl Iterator<Item = &'static str> {
BUILTIN.iter().map(|(name, _)| *name)
}
pub fn builtin(name: &str) -> Result<Self> {
let Some((_, text)) = BUILTIN.iter().find(|(n, _)| *n == name) else {
bail!(
"unknown host profile {name} (built-in: {})",
Self::builtin_names().collect::<Vec<_>>().join(", ")
);
};
Self::from_toml(text, name)
}
pub fn from_toml(text: &str, origin: &str) -> Result<Self> {
toml::from_str(text).with_context(|| format!("host profile {origin}: invalid"))
}
pub fn bus_by_label(&self, label: &str) -> Option<usize> {
self.bus
.iter()
.position(|b| b.labels.iter().any(|l| l == label))
}
}