Merge pull request 'feat: макрос uformat' (#21) from uformat into master

Reviewed-on: #21
Reviewed-by: nm17 <nm17@riseup.net>
This commit is contained in:
DarkCat09 2025-01-10 16:20:29 +03:00
commit c7ec61994b
3 changed files with 25 additions and 15 deletions

View file

@ -8,6 +8,7 @@
use crate::ingest_protocol::error::Error;
use crate::ingest_protocol::parser::parse_mac_address;
use crate::uformat;
use crate::utils::{EpochUTC, SupportedUnit};
use crate::web_server::app_error::{AppError, ServerRedisSnafu};
@ -18,7 +19,6 @@ use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use snafu::ResultExt;
use ufmt::uwrite;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
@ -102,8 +102,6 @@ impl NMDeviceDataPacket {
pub async fn save_to_db(&self, redis: &RedisClient) -> Result<(), AppError> {
let device_mac_enc = hex::encode(self.mac);
let mut key = String::new();
let now = Epoch::now().unwrap().into();
let mut device_time = self.time.unwrap_or(now);
@ -115,39 +113,42 @@ impl NMDeviceDataPacket {
let device_tai_timestamp = device_time.0.to_duration_since_j1900().to_seconds();
uwrite!(&mut key, "devices_{}", device_mac_enc).unwrap();
let key = uformat!("devices_{}", device_mac_enc);
let device_exists: Option<bool> = redis.hget(key.as_str(), "exists").await.context(ServerRedisSnafu)?;
let device_exists: Option<bool> = redis
.hget(key.as_str(), "exists")
.await
.context(ServerRedisSnafu)?;
if !device_exists.is_some_and(|v| v) {
return Err(AppError::DeviceNotFound { mac: hex::encode(self.mac) });
return Err(AppError::DeviceNotFound {
mac: hex::encode(self.mac),
});
}
// devices_{device_id}_{tai_timestamp}_{sensor_id}
for sensor in &self.values {
let mut key = String::new();
uwrite!(
&mut key,
let key = uformat!(
"devices_{}_{}_{}",
device_mac_enc,
device_tai_timestamp.to_string(),
sensor.mac
)
.unwrap();
);
redis
.set(key.as_str(), sensor.value.to_string(), None, None, false)
.await.context(ServerRedisSnafu)?;
.await
.context(ServerRedisSnafu)?;
}
if let Some(commands) = &self.commands {
for (cmd_key, cmd_value) in commands {
let mut key = String::new();
uwrite!(&mut key, "devices_{}_cmds_{}", device_mac_enc, cmd_key).unwrap();
let key = uformat!("devices_{}_cmds_{}", device_mac_enc, cmd_key);
redis
.set(key.as_str(), cmd_value, None, None, false)
.await.context(ServerRedisSnafu)?;
.await
.context(ServerRedisSnafu)?;
}
}

View file

@ -2,6 +2,7 @@
//!
mod hifitime_serde;
pub mod uformat;
use phf::phf_map;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

8
src/utils/uformat.rs Normal file
View file

@ -0,0 +1,8 @@
#[macro_export]
macro_rules! uformat {
($($arg:tt)*) => {{
let mut buf = String::new();
ufmt::uwrite!(&mut buf, $($arg)*).unwrap();
buf
}};
}