Rename ControllerUid to a more general EmgauwaUid (for macros)

This commit is contained in:
Tobias Reisinger 2024-04-28 02:29:34 +02:00
parent 07d3322c5a
commit 51aa0d3c99
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
11 changed files with 55 additions and 57 deletions

View file

@ -3,7 +3,7 @@ use emgauwa_lib::db;
use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule}; use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
use emgauwa_lib::errors::EmgauwaError; use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::{Controller, FromDbModel}; use emgauwa_lib::models::{Controller, FromDbModel};
use emgauwa_lib::types::ControllerUid; use emgauwa_lib::types::EmgauwaUid;
use emgauwa_lib::utils::{drop_privileges, init_logging}; use emgauwa_lib::utils::{drop_privileges, init_logging};
use rppal_pfd::PiFaceDigital; use rppal_pfd::PiFaceDigital;
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
@ -26,7 +26,7 @@ async fn create_this_controller(
) -> Result<DbController, EmgauwaError> { ) -> Result<DbController, EmgauwaError> {
DbController::create( DbController::create(
conn, conn,
&ControllerUid::default(), &EmgauwaUid::default(),
&settings.name, &settings.name,
settings.relays.len() as i64, settings.relays.len() as i64,
) )

View file

@ -4,7 +4,7 @@ use actix::{Actor, Addr, Context, Handler, Message, Recipient};
use emgauwa_lib::db::DbController; use emgauwa_lib::db::DbController;
use emgauwa_lib::errors::EmgauwaError; use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::{convert_db_list, Controller, Relay}; use emgauwa_lib::models::{convert_db_list, Controller, Relay};
use emgauwa_lib::types::{ControllerUid, ControllerWsAction, RelayStates}; use emgauwa_lib::types::{ControllerWsAction, EmgauwaUid, RelayStates};
use futures::executor::block_on; use futures::executor::block_on;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
@ -13,7 +13,7 @@ use crate::handlers::v1::ws::relays::{RelaysWs, SendRelays};
#[derive(Message)] #[derive(Message)]
#[rtype(result = "Result<(), EmgauwaError>")] #[rtype(result = "Result<(), EmgauwaError>")]
pub struct DisconnectController { pub struct DisconnectController {
pub controller_uid: ControllerUid, pub controller_uid: EmgauwaUid,
} }
#[derive(Message)] #[derive(Message)]
@ -26,7 +26,7 @@ pub struct ConnectController {
#[derive(Message)] #[derive(Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
pub struct UpdateRelayStates { pub struct UpdateRelayStates {
pub controller_uid: ControllerUid, pub controller_uid: EmgauwaUid,
pub relay_states: RelayStates, pub relay_states: RelayStates,
} }
@ -37,7 +37,7 @@ pub struct GetRelays {}
#[derive(Message)] #[derive(Message)]
#[rtype(result = "Result<(), EmgauwaError>")] #[rtype(result = "Result<(), EmgauwaError>")]
pub struct Action { pub struct Action {
pub controller_uid: ControllerUid, pub controller_uid: EmgauwaUid,
pub action: ControllerWsAction, pub action: ControllerWsAction,
} }
@ -49,7 +49,7 @@ pub struct ConnectRelayClient {
pub struct AppState { pub struct AppState {
pub pool: Pool<Sqlite>, pub pool: Pool<Sqlite>,
pub connected_controllers: HashMap<ControllerUid, (Controller, Recipient<ControllerWsAction>)>, pub connected_controllers: HashMap<EmgauwaUid, (Controller, Recipient<ControllerWsAction>)>,
pub connected_relay_clients: Vec<Addr<RelaysWs>>, pub connected_relay_clients: Vec<Addr<RelaysWs>>,
} }

View file

@ -3,7 +3,7 @@ use actix_web::{delete, get, put, web, HttpResponse};
use emgauwa_lib::db::DbController; use emgauwa_lib::db::DbController;
use emgauwa_lib::errors::{DatabaseError, EmgauwaError}; use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
use emgauwa_lib::models::{convert_db_list, Controller, FromDbModel}; use emgauwa_lib::models::{convert_db_list, Controller, FromDbModel};
use emgauwa_lib::types::{ControllerUid, ControllerWsAction, RequestControllerUpdate}; use emgauwa_lib::types::{ControllerWsAction, EmgauwaUid, RequestControllerUpdate};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use crate::app_state; use crate::app_state;
@ -28,7 +28,7 @@ pub async fn show(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid,) = path.into_inner(); let (controller_uid,) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?
@ -40,15 +40,15 @@ pub async fn show(
#[put("/controllers/{controller_id}")] #[put("/controllers/{controller_id}")]
pub async fn update( pub async fn update(
pool: web::Data<Pool<Sqlite>>, pool: web::Data<Pool<Sqlite>>,
app_state: web::Data<Addr<AppState>>, app_state: web::Data<Addr<AppState>>,
path: web::Path<(String,)>, path: web::Path<(String,)>,
data: web::Json<RequestControllerUpdate>, data: web::Json<RequestControllerUpdate>,
) -> Result<HttpResponse, EmgauwaError> { ) -> Result<HttpResponse, EmgauwaError> {
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid,) = path.into_inner(); let (controller_uid,) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?
@ -79,7 +79,7 @@ pub async fn delete(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid,) = path.into_inner(); let (controller_uid,) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
app_state app_state
.send(app_state::DisconnectController { .send(app_state::DisconnectController {

View file

@ -3,9 +3,7 @@ use actix_web::{get, post, put, web, HttpResponse};
use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbTag}; use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbTag};
use emgauwa_lib::errors::{DatabaseError, EmgauwaError}; use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
use emgauwa_lib::models::{convert_db_list, FromDbModel, Relay}; use emgauwa_lib::models::{convert_db_list, FromDbModel, Relay};
use emgauwa_lib::types::{ use emgauwa_lib::types::{ControllerWsAction, EmgauwaUid, RequestRelayPulse, RequestRelayUpdate};
ControllerUid, ControllerWsAction, RequestRelayPulse, RequestRelayUpdate,
};
use emgauwa_lib::utils; use emgauwa_lib::utils;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
@ -49,7 +47,7 @@ pub async fn index_for_controller(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid,) = path.into_inner(); let (controller_uid,) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?
@ -69,7 +67,7 @@ pub async fn show_for_controller(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid, relay_num) = path.into_inner(); let (controller_uid, relay_num) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?
@ -93,7 +91,7 @@ pub async fn update_for_controller(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid, relay_num) = path.into_inner(); let (controller_uid, relay_num) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?
@ -162,7 +160,7 @@ pub async fn pulse(
let mut pool_conn = pool.acquire().await?; let mut pool_conn = pool.acquire().await?;
let (controller_uid, relay_num) = path.into_inner(); let (controller_uid, relay_num) = path.into_inner();
let uid = ControllerUid::try_from(controller_uid.as_str())?; let uid = EmgauwaUid::try_from(controller_uid.as_str())?;
let controller = DbController::get_by_uid(&mut pool_conn, &uid) let controller = DbController::get_by_uid(&mut pool_conn, &uid)
.await? .await?

View file

@ -2,7 +2,7 @@ use actix::{Actor, AsyncContext};
use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule}; use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
use emgauwa_lib::errors::{DatabaseError, EmgauwaError}; use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
use emgauwa_lib::models::{Controller, FromDbModel}; use emgauwa_lib::models::{Controller, FromDbModel};
use emgauwa_lib::types::{ControllerUid, ControllerWsAction, RelayStates}; use emgauwa_lib::types::{ControllerWsAction, EmgauwaUid, RelayStates};
use emgauwa_lib::utils; use emgauwa_lib::utils;
use futures::executor::block_on; use futures::executor::block_on;
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
@ -97,7 +97,7 @@ impl ControllersWs {
pub fn handle_relay_states( pub fn handle_relay_states(
&mut self, &mut self,
controller_uid: ControllerUid, controller_uid: EmgauwaUid,
relay_states: RelayStates, relay_states: RelayStates,
) -> Result<(), EmgauwaError> { ) -> Result<(), EmgauwaError> {
log::debug!( log::debug!(

View file

@ -7,7 +7,7 @@ use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError; use actix_web_actors::ws::ProtocolError;
use emgauwa_lib::constants::{HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT}; use emgauwa_lib::constants::{HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT};
use emgauwa_lib::errors::EmgauwaError; use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::types::{ControllerUid, ControllerWsAction}; use emgauwa_lib::types::{ControllerWsAction, EmgauwaUid};
use futures::executor::block_on; use futures::executor::block_on;
use sqlx::pool::PoolConnection; use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
@ -18,7 +18,7 @@ use crate::utils::flatten_result;
pub struct ControllersWs { pub struct ControllersWs {
pub pool: Pool<Sqlite>, pub pool: Pool<Sqlite>,
pub controller_uid: Option<ControllerUid>, pub controller_uid: Option<EmgauwaUid>,
pub app_state: Addr<AppState>, pub app_state: Addr<AppState>,
pub hb: Instant, pub hb: Instant,
} }

View file

@ -6,14 +6,14 @@ use sqlx::Sqlite;
use crate::db::{DbRelay, DbTag}; use crate::db::{DbRelay, DbTag};
use crate::errors::DatabaseError; use crate::errors::DatabaseError;
use crate::types::ControllerUid; use crate::types::EmgauwaUid;
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DbController { pub struct DbController {
#[serde(skip)] #[serde(skip)]
pub id: i64, pub id: i64,
#[serde(rename = "id")] #[serde(rename = "id")]
pub uid: ControllerUid, pub uid: EmgauwaUid,
pub name: String, pub name: String,
pub relay_count: i64, pub relay_count: i64,
pub active: bool, pub active: bool,
@ -41,7 +41,7 @@ impl DbController {
pub async fn get_by_uid( pub async fn get_by_uid(
conn: &mut PoolConnection<Sqlite>, conn: &mut PoolConnection<Sqlite>,
filter_uid: &ControllerUid, filter_uid: &EmgauwaUid,
) -> Result<Option<DbController>, DatabaseError> { ) -> Result<Option<DbController>, DatabaseError> {
sqlx::query_as!( sqlx::query_as!(
DbController, DbController,
@ -55,7 +55,7 @@ impl DbController {
pub async fn get_by_uid_or_create( pub async fn get_by_uid_or_create(
conn: &mut PoolConnection<Sqlite>, conn: &mut PoolConnection<Sqlite>,
uid: &ControllerUid, uid: &EmgauwaUid,
new_name: &str, new_name: &str,
new_relay_count: i64, new_relay_count: i64,
) -> Result<DbController, DatabaseError> { ) -> Result<DbController, DatabaseError> {
@ -77,7 +77,7 @@ impl DbController {
pub async fn delete_by_uid( pub async fn delete_by_uid(
conn: &mut PoolConnection<Sqlite>, conn: &mut PoolConnection<Sqlite>,
filter_uid: ControllerUid, filter_uid: EmgauwaUid,
) -> Result<(), DatabaseError> { ) -> Result<(), DatabaseError> {
if sqlx::query_scalar!("SELECT 1 FROM controllers WHERE uid = ?", filter_uid) if sqlx::query_scalar!("SELECT 1 FROM controllers WHERE uid = ?", filter_uid)
.fetch_optional(conn.deref_mut()) .fetch_optional(conn.deref_mut())
@ -98,7 +98,7 @@ impl DbController {
pub async fn create( pub async fn create(
conn: &mut PoolConnection<Sqlite>, conn: &mut PoolConnection<Sqlite>,
new_uid: &ControllerUid, new_uid: &EmgauwaUid,
new_name: &str, new_name: &str,
new_relay_count: i64, new_relay_count: i64,
) -> Result<DbController, DatabaseError> { ) -> Result<DbController, DatabaseError> {

View file

@ -13,7 +13,7 @@ use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use crate::errors::{ApiError, DatabaseError}; use crate::errors::{ApiError, DatabaseError};
use crate::types::ControllerUid; use crate::types::EmgauwaUid;
#[derive(Debug)] #[derive(Debug)]
pub enum EmgauwaError { pub enum EmgauwaError {
@ -23,7 +23,7 @@ pub enum EmgauwaError {
Database(DatabaseError), Database(DatabaseError),
Other(String), Other(String),
Internal(String), Internal(String),
Connection(ControllerUid), Connection(EmgauwaUid),
Hardware(String), Hardware(String),
} }

View file

@ -9,14 +9,14 @@ use sqlx::Sqlite;
use crate::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule}; use crate::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
use crate::errors::DatabaseError; use crate::errors::DatabaseError;
use crate::models::FromDbModel; use crate::models::FromDbModel;
use crate::types::ControllerUid; use crate::types::EmgauwaUid;
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Relay { pub struct Relay {
#[serde(flatten)] #[serde(flatten)]
pub r: DbRelay, pub r: DbRelay,
pub controller: DbController, pub controller: DbController,
pub controller_id: ControllerUid, pub controller_id: EmgauwaUid,
pub schedules: Vec<DbSchedule>, pub schedules: Vec<DbSchedule>,
pub active_schedule: DbSchedule, pub active_schedule: DbSchedule,
pub is_on: Option<bool>, pub is_on: Option<bool>,

View file

@ -10,21 +10,21 @@ use sqlx::{Decode, Encode, Sqlite, Type};
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug, Eq, PartialEq, Hash)] #[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ControllerUid(Uuid); pub struct EmgauwaUid(Uuid);
impl Default for ControllerUid { impl Default for EmgauwaUid {
fn default() -> Self { fn default() -> Self {
Self(Uuid::new_v4()) Self(Uuid::new_v4())
} }
} }
impl Display for ControllerUid { impl Display for EmgauwaUid {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from(self)) write!(f, "{}", String::from(self))
} }
} }
impl Serialize for ControllerUid { impl Serialize for EmgauwaUid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
@ -33,23 +33,23 @@ impl Serialize for ControllerUid {
} }
} }
impl<'de> Deserialize<'de> for ControllerUid { impl<'de> Deserialize<'de> for EmgauwaUid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
Self::try_from(String::deserialize(deserializer)?.as_str()) Self::try_from(String::deserialize(deserializer)?.as_str())
.map_err(|_| serde::de::Error::custom("invalid controller uid")) .map_err(|_| serde::de::Error::custom("invalid uid"))
} }
} }
impl From<&ControllerUid> for String { impl From<&EmgauwaUid> for String {
fn from(uid: &ControllerUid) -> String { fn from(uid: &EmgauwaUid) -> String {
uid.0.as_hyphenated().to_string() uid.0.as_hyphenated().to_string()
} }
} }
impl Type<Sqlite> for ControllerUid { impl Type<Sqlite> for EmgauwaUid {
fn type_info() -> SqliteTypeInfo { fn type_info() -> SqliteTypeInfo {
<&[u8] as Type<Sqlite>>::type_info() <&[u8] as Type<Sqlite>>::type_info()
} }
@ -59,27 +59,27 @@ impl Type<Sqlite> for ControllerUid {
} }
} }
impl<'q> Encode<'q, Sqlite> for ControllerUid { impl<'q> Encode<'q, Sqlite> for EmgauwaUid {
//noinspection DuplicatedCode //noinspection DuplicatedCode
fn encode_by_ref(&self, buf: &mut <Sqlite as HasArguments<'q>>::ArgumentBuffer) -> IsNull { fn encode_by_ref(&self, buf: &mut <Sqlite as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
<Vec<u8> as Encode<Sqlite>>::encode(Vec::from(self), buf) <Vec<u8> as Encode<Sqlite>>::encode(Vec::from(self), buf)
} }
} }
impl<'r> Decode<'r, Sqlite> for ControllerUid { impl<'r> Decode<'r, Sqlite> for EmgauwaUid {
//noinspection DuplicatedCode //noinspection DuplicatedCode
fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> { fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
Self::try_from(<&[u8] as Decode<Sqlite>>::decode(value)?).map_err(Into::into) Self::try_from(<&[u8] as Decode<Sqlite>>::decode(value)?).map_err(Into::into)
} }
} }
impl From<&ControllerUid> for Vec<u8> { impl From<&EmgauwaUid> for Vec<u8> {
fn from(uid: &ControllerUid) -> Vec<u8> { fn from(uid: &EmgauwaUid) -> Vec<u8> {
uid.0.as_bytes().to_vec() uid.0.as_bytes().to_vec()
} }
} }
impl TryFrom<&str> for ControllerUid { impl TryFrom<&str> for EmgauwaUid {
type Error = uuid::Error; type Error = uuid::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> { fn try_from(value: &str) -> Result<Self, Self::Error> {
@ -88,16 +88,16 @@ impl TryFrom<&str> for ControllerUid {
} }
} }
impl TryFrom<&[u8]> for ControllerUid { impl TryFrom<&[u8]> for EmgauwaUid {
type Error = uuid::Error; type Error = uuid::Error;
fn try_from(value: &[u8]) -> Result<ControllerUid, uuid::Error> { fn try_from(value: &[u8]) -> Result<EmgauwaUid, uuid::Error> {
Ok(Self(Uuid::from_slice(value)?)) Ok(Self(Uuid::from_slice(value)?))
} }
} }
impl From<Vec<u8>> for ControllerUid { impl From<Vec<u8>> for EmgauwaUid {
fn from(value: Vec<u8>) -> Self { fn from(value: Vec<u8>) -> Self {
Self::try_from(value.as_slice()).expect("Failed to parse controller uid from database") Self::try_from(value.as_slice()).expect("Failed to parse uid from database")
} }
} }

View file

@ -1,9 +1,9 @@
mod controller_uid; mod emgauwa_uid;
mod request; mod request;
mod schedule_uid; mod schedule_uid;
use actix::Message; use actix::Message;
pub use controller_uid::ControllerUid; pub use emgauwa_uid::EmgauwaUid;
pub use request::*; pub use request::*;
pub use schedule_uid::ScheduleUid; pub use schedule_uid::ScheduleUid;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
@ -24,6 +24,6 @@ pub enum ControllerWsAction {
Schedules(Vec<DbSchedule>), Schedules(Vec<DbSchedule>),
Relays(Vec<Relay>), Relays(Vec<Relay>),
Controller(Controller), Controller(Controller),
RelayStates((ControllerUid, RelayStates)), RelayStates((EmgauwaUid, RelayStates)),
RelayPulse((i64, Option<u32>)), RelayPulse((i64, Option<u32>)),
} }