use crate::BuildError;
use crate::flatten::FlatPart;
use litz_core::{Drive, Level, Part, PartState, PinId, Tick};
use litz_net::{AccessPoint, NearbyNetwork, NetworkConfig, Service};
pub const ENGINE: &str = "router";
fn attr(part: &FlatPart, name: &str) -> Option<String> {
part.attrs
.get(name)
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn ports(part: &FlatPart, name: &str) -> Result<Vec<u16>, BuildError> {
let Some(text) = attr(part, name) else {
return Ok(Vec::new());
};
text.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(|entry| {
entry.parse::<u16>().map_err(|_| {
BuildError::Message(format!(
"part {:?}: {name} = {entry:?} is not a port number",
part.id
))
})
})
.collect()
}
pub fn config(part: &FlatPart) -> Result<NetworkConfig, BuildError> {
let ssid = attr(part, "ssid").unwrap_or_else(|| "litz".to_string());
let channel = attr(part, "channel")
.map(|text| {
text.parse::<u8>().map_err(|_| {
BuildError::Message(format!(
"part {:?}: channel = {text:?} is not a number",
part.id
))
})
})
.transpose()?
.unwrap_or(6);
if !(1..=14).contains(&channel) {
return Err(BuildError::Message(format!(
"part {:?}: channel {channel} is outside 1 through 14",
part.id
)));
}
let mut network = NetworkConfig {
access_points: vec![AccessPoint {
ssid,
psk: attr(part, "psk"),
channel,
bssid: None,
epoch_s: None,
}],
..NetworkConfig::default()
};
if let Some(body) = attr(part, "http") {
network = network.with_service(Service::http(80, body));
}
if let Some(body) = attr(part, "https") {
network = network.with_service(Service::https(443, body));
}
for port in ports(part, "ws")? {
network = network.with_service(Service::websocket(port));
}
for port in ports(part, "wss")? {
network = network.with_service(Service::wss(port));
}
for port in ports(part, "echo")? {
network = network.with_service(Service::TcpEcho { port });
}
for port in ports(part, "udp_echo")? {
network = network.with_service(Service::UdpEcho { port });
}
if let Some(port) = ports(part, "mqtt")?.first().filter(|port| **port != 0) {
network = network.with_service(Service::mqtt(*port));
}
for name in attr(part, "nearby")
.map(|text| {
text.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(str::to_string)
.collect::<Vec<_>>()
})
.unwrap_or_default()
{
network.nearby.push(NearbyNetwork::new(name));
}
Ok(network)
}
pub struct RouterPart;
impl Part for RouterPart {
fn drive(&self, _pin: PinId) -> Drive {
Drive::HIGH_Z
}
fn set_pin(&mut self, _pin: PinId, _level: Level, _now: Tick) {}
fn state(&self) -> PartState {
PartState::None
}
}
pub fn build(part: &FlatPart) -> Result<Box<dyn Part>, BuildError> {
config(part)?;
Ok(Box::new(RouterPart))
}
pub fn board_network(parts: &[FlatPart]) -> Result<Option<NetworkConfig>, BuildError> {
let mut found: Option<(&FlatPart, NetworkConfig)> = None;
for part in parts {
if !matches!(&part.engine, crate::flatten::Engine::Builtin(engine) if engine == ENGINE) {
continue;
}
if let Some((first, _)) = found {
return Err(BuildError::Message(format!(
"the board has two routers ({:?} and {:?}); a circuit joins one network",
first.id, part.id
)));
}
found = Some((part, config(part)?));
}
Ok(found.map(|(_, network)| network))
}