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); impl Actions { // Return the iterator over the inner Vec of Actions pub fn iter(&self) -> std::slice::Iter { 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, // Button id -> mapping } #[derive(Deserialize, Debug)] pub struct MQTTServer { pub host: String, pub port: Option, pub user: Option, pub pass: Option, pub client_id: Option, pub topic_prefix: Option, } #[derive(Deserialize, Debug)] pub struct Config { pub mqtt_servers: HashMap, pub layers: HashMap, } impl Config { pub fn from_file(p: &Path) -> Result> { 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::() { Ok(c) => Ok(c), Err(e) => { println!("{}", e); Err(Box::new(e)) } } } }