lj_rust/src/redis_ctrl.rs

77 lines
1.6 KiB
Rust

use redis::{Client, Commands, Connection};
use ron::de::from_str;
use crate::errors::{LJError,LJResult};
#[repr(u8)]
#[derive(Debug, PartialEq)]
pub enum Order {
Draw = 0,
Edh, //homography
Black,
Grid,
Resampler,
ClientKey,
Intensity,
Kpps,
ColorBalance,
}
impl TryFrom<u8> for Order {
type Error = String;
fn try_from(value: u8) -> Result<Self, Self::Error> {
use Order::*;
if value > 8 {
return Err("order out of range".to_string());
}
Ok(match value {
0 => Draw,
1 => Edh,
2 => Black,
3 => Grid,
4 => Resampler,
5 => ClientKey,
6 => Intensity,
7 => Kpps,
8 => ColorBalance,
_ => unreachable!()
})
}
}
pub type Line = Vec<(f32, f32, u32)>;
pub struct RedisCtrl {
pub client: Client,
pub connection: Connection,
}
impl RedisCtrl {
pub fn new(url: &str) -> LJResult<Self> {
let client = Client::open(url)
.map_err(LJError::RedisConnect)?;
let connection = client.get_connection()
.map_err(LJError::RedisConnect)?;
Ok(RedisCtrl { client, connection })
}
pub fn get(&mut self, key: &str) -> LJResult<Line> {
let val: String = self.connection.get(key)?;
let line: Line = from_str(&val)?;
Ok(line)
}
pub fn get_order(&mut self, id: u8) -> LJResult<Order> {
let path = format!("/order/{id}");
let val: u8 = self.connection.get(path.clone())?;
if val == 1 || val >= 4 {
self.connection.set(path, 0)?;
}
Ok(val.try_into()?)
}
}