103 lines
3.0 KiB
Rust
103 lines
3.0 KiB
Rust
use serde::Deserialize;
|
|
use serde_dhall::StaticType;
|
|
use std::collections::HashMap;
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
use std::path::Path;
|
|
|
|
#[derive(Deserialize, StaticType, Debug)]
|
|
pub enum Action {
|
|
ActivateLayer(String), // Activate a layer
|
|
Print(String), // Print a string to console
|
|
MQTTPub { topic: String, payload: String }, // Publish payload on topic via MQTT
|
|
}
|
|
|
|
impl fmt::Display for Action {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match &self {
|
|
Action::ActivateLayer(layer) => write!(f, "ActivateLayer({})", layer),
|
|
Action::Print(p) => write!(f, "Print({})", p),
|
|
Action::MQTTPub { topic, payload } => {
|
|
write!(f, "MQTTPub(topic={},payload={})", topic, payload)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize, StaticType, Debug)]
|
|
pub struct Actions(Vec<Action>);
|
|
|
|
impl Actions {
|
|
// Return the iterator over the inner Vec of Actions
|
|
pub fn iter(&self) -> std::slice::Iter<Action> {
|
|
self.0.iter()
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Actions {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(f, "Actions(count={})", self.0.len())
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize, StaticType, Debug)]
|
|
pub enum Mapping {
|
|
NOP, // Do nothing.
|
|
Passthrough, // Passthrough to the layer below
|
|
Trigger(Action), // Trigger an action
|
|
TriggerMulti(Actions), // Trigger multiple actions in sequence
|
|
}
|
|
|
|
impl fmt::Display for Mapping {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(
|
|
f,
|
|
"{}",
|
|
match &self {
|
|
Mapping::NOP => "NOP".to_owned(),
|
|
Mapping::Passthrough => "Passthrough".to_owned(),
|
|
Mapping::Trigger(act) => format!("Trigger({})", act),
|
|
Mapping::TriggerMulti(acts) => format!("Trigger({})", acts),
|
|
},
|
|
)
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub struct Layer {
|
|
pub default_mapping: Mapping, // What do we do if there's no mapping for a button?
|
|
pub mappings: HashMap<String, Mapping>, // Button id -> mapping
|
|
}
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub struct MQTTServer {
|
|
pub host: String,
|
|
pub port: Option<u16>,
|
|
pub user: Option<String>,
|
|
pub pass: Option<String>,
|
|
pub client_id: Option<String>,
|
|
pub topic_prefix: Option<String>,
|
|
}
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub struct Config {
|
|
pub mqtt_servers: HashMap<String, MQTTServer>,
|
|
pub layers: HashMap<String, Layer>,
|
|
}
|
|
|
|
impl Config {
|
|
pub fn from_file(p: &Path) -> Result<Self, Box<dyn Error>> {
|
|
match serde_dhall::from_file(p)
|
|
.with_builtin_type("Mapping".to_string(), Mapping::static_type())
|
|
.with_builtin_type("Action".to_string(), Action::static_type())
|
|
.parse::<Self>()
|
|
{
|
|
Ok(c) => Ok(c),
|
|
Err(e) => {
|
|
println!("{}", e);
|
|
Err(Box::new(e))
|
|
}
|
|
}
|
|
}
|
|
}
|