Files
rust_leptos/src/models/value.rs
2024-12-06 23:58:13 +01:00

123 lines
3.1 KiB
Rust

use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub struct Option {
pub value: &'static str,
pub name: &'static str,
service: &'static str,
device: &'static str,
r_type: &'static str,
}
pub const OPTIONS: &[Option] = &[
Option {
value: "citerne",
name: "Citerne",
service: "home",
device: "citerne",
r_type: "height",
},
Option {
value: "eau",
name: "Eau",
service: "home",
device: "eau",
r_type: "volume",
},
Option {
value: "elec-hight",
name: "Electricité heure pleine",
service: "home",
device: "elec",
r_type: "pleine",
},
Option {
value: "elec-low",
name: "Electricité heure creuse",
service: "home",
device: "elec",
r_type: "creuse",
},
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Value {
id: i32,
service: String,
capteur: String,
type_donnee: String,
pub donnee: String,
pub date_donnee: String,
}
impl Value {
#[cfg(feature = "ssr")]
pub async fn insert(
device: String,
value: String,
) -> Result<sqlx::mysql::MySqlQueryResult, sqlx::Error> {
let option = match find_option(&device) {
Ok(option) => option,
Err(err) => panic!("{}", err),
};
sqlx::query!(
"INSERT INTO donnees(service, capteur, type, donnee, date_donnee) VALUES (?, ?, ?, ?, ?)",
option.service,
option.device,
option.r_type,
value,
chrono::Local::now().naive_local(),
)
.execute(crate::database::get_db())
.await
}
#[cfg(feature = "ssr")]
pub async fn get_one(topic: String) -> Result<Self, sqlx::Error> {
let split: Vec<&str> = topic.split("/").collect();
let unknow_value = Value {
id: 0,
service: "".to_string(),
capteur: "".to_string(),
type_donnee: "".to_string(),
donnee: "--".to_string(),
date_donnee: "--:--".to_string(),
};
if split.len() == 3 {
let res = sqlx::query!(
"SELECT * FROM donnees WHERE service = ? AND capteur = ? AND type = ?",
split[0],
split[1],
split[2],
//chrono::Local::now().naive_local(),
)
.map(|x| Self {
id: x.id,
service: x.service,
capteur: x.capteur,
type_donnee: x.r#type,
donnee: x.donnee,
date_donnee: x.date_donnee.format("%H:%M").to_string(),
})
.fetch_one(crate::database::get_db())
.await;
match res {
Ok(res) => Ok(res),
Err(_) => Ok(unknow_value)
}
} else {
Ok(unknow_value)
}
}
}
fn find_option(value: &str) -> Result<&Option, &str> {
OPTIONS
.iter()
.find(|&option| option.value == value)
.ok_or("No option found with the given value")
}