/
NovAl
/
rust_rules
Обзор
Документация
Войти
/
NovAl
/
rust_rules
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
crates/rust_rules_config/src/lib.rs
148 строк
4 KB
Novikov Aleksandr
Первый коммит: проект без target и бинарников
21 июл 2026, 22:09
21 июл 2026, 22:09
f6008f1
Код
Авторство
О чём код?
//cd /d/Rust/projects/rune_rules/crates/wb_rust_config use std::collections::HashMap; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct Config { pub broker: BrokerConfig, pub devices: HashMap<String, HashMap<String, Control>>, pub scripts: ScriptsConfig, pub r#virtual: Option<HashMap<String, HashMap<String, VirtualControl>>>, } impl Config { pub fn load_config(path: &str) -> Self { let content = std::fs::read_to_string(path) .expect(&format!("Не удалось найти файл конфигурации: {}", path)); toml::from_str(&content) .expect("Ошибка в формате TOML") } pub fn all_topics(&self) -> Vec<String> { let mut topics = Vec::new(); for (_, controls) in &self.devices { for (_, info) in controls { topics.push(info.topic.clone()); } } topics } pub fn aliases(&self) -> HashMap<String, String> { let mut aliases = HashMap::new(); // Авто-алиасы из реальных устройств for (device_name, controls) in &self.devices { for (control_name, control) in controls { let alias = format!("{}.{}", device_name, control_name); aliases.insert(alias, control.topic.clone()); } } // Авто-алиасы из виртуальных устройств if let Some(virtual_devices) = &self.r#virtual { for (device_name, controls) in virtual_devices { for control_name in controls.keys() { let alias = format!("{}.{}", device_name, control_name); let topic = format!("/devices/{}/controls/{}", device_name, control_name); aliases.insert(alias, topic); } } } aliases } // /// Получить тип топика по его полному пути // pub fn get_type(&self, topic: &str) -> Option<String> { // } } #[derive(Debug, Deserialize)] pub struct ScriptsConfig { pub directory: String, // путь к папке со скриптами } #[derive(Debug, Deserialize)] pub struct BrokerConfig { pub host: String, pub port: u16, pub command_suffix: String, } #[derive(Debug, Deserialize)] pub struct Control { pub topic: String, pub r#type: String, } pub struct TopicTypes { map: HashMap<String, String>, // topic → type } impl TopicTypes { /// Создать из Config pub fn from_config(config: &Config) -> Self { let mut map = HashMap::new(); for (_, controls) in &config.devices { for (_, info) in controls { map.insert(info.topic.clone(), info.r#type.clone()); } } Self {map} } /// Получить тип топика. Если топик не найден — логирует и возвращает "string" pub fn get(&self, topic: &str) -> &str { match self.map.get(topic) { Some(t) => t.as_str(), None => { eprintln!("⚠️ Топик '{}' не найден в конфиге, тип = string", topic); "string" } } } /// Получить все топики pub fn all_topics(&self) -> Vec<String> { self.map.keys().cloned().collect() } } #[derive(Debug, Deserialize, Clone)] pub struct VirtualControl { /// Тип топика Wiren Board: "switch", "range", "value", "text", "rgb", "pushbutton" pub topic_type: String, /// Значение по умолчанию pub value: Option<serde_json::Value>, /// Тип данных: "bool", "i32", "f64", "string" #[serde(rename = "type")] pub value_type: String, // Опциональные мета-поля pub min: Option<f64>, pub max: Option<f64>, pub precision: Option<u32>, pub readonly: Option<bool>, #[serde(default)] pub force_default: bool, #[serde(default)] pub lazy_init: bool, #[serde(default)] pub retain: bool, }