change database structure ... again...

This commit is contained in:
Mika Bomm 2024-10-13 22:06:20 +02:00
parent a696a05595
commit 38a0f4d189
8 changed files with 110 additions and 28 deletions

43
Cargo.lock generated
View file

@ -544,6 +544,7 @@ dependencies = [
"actix-web", "actix-web",
"argon2", "argon2",
"chrono", "chrono",
"deku",
"dotenvy", "dotenvy",
"entity", "entity",
"eui48", "eui48",
@ -551,6 +552,7 @@ dependencies = [
"jsonwebtoken", "jsonwebtoken",
"sea-orm", "sea-orm",
"serde", "serde",
"tokio",
"uuid", "uuid",
] ]
@ -954,6 +956,7 @@ dependencies = [
"ident_case", "ident_case",
"proc-macro2", "proc-macro2",
"quote", "quote",
"strsim",
"syn 2.0.79", "syn 2.0.79",
] ]
@ -968,6 +971,31 @@ dependencies = [
"syn 2.0.79", "syn 2.0.79",
] ]
[[package]]
name = "deku"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9711031e209dc1306d66985363b4397d4c7b911597580340b93c9729b55f6eb"
dependencies = [
"bitvec",
"deku_derive",
"no_std_io2",
"rustversion",
]
[[package]]
name = "deku_derive"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58cb0719583cbe4e81fb40434ace2f0d22ccc3e39a74bb3796c22b451b4f139d"
dependencies = [
"darling",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 2.0.79",
]
[[package]] [[package]]
name = "der" name = "der"
version = "0.7.9" version = "0.7.9"
@ -1772,6 +1800,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "no_std_io2"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a3564ce7035b1e4778d8cb6cacebb5d766b5e8fe5a75b9e441e33fb61a872c6"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@ -2385,6 +2422,12 @@ dependencies = [
"untrusted", "untrusted",
] ]
[[package]]
name = "rustversion"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6"
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.18" version = "1.0.18"

View file

@ -20,3 +20,5 @@ jsonwebtoken = "*"
futures = "*" futures = "*"
chrono = "*" chrono = "*"
eui48 = "*" eui48 = "*"
tokio = { version = "1", features = ["full"] }
deku = "*"

View file

@ -1,13 +1,12 @@
use crate::AppState; use crate::AppState;
use actix_web::{ use actix_web::{
error::{ErrorBadRequest, ErrorInternalServerError}, error::{ErrorBadRequest, ErrorInternalServerError},
web, HttpResponse, Responder, web, Responder,
}; };
use chrono::Utc; use chrono::Utc;
use entity::{node, node_group, sensor_data}; use entity::{node, node_group, sensor_data};
use sea_orm::{entity::*, query::*, ActiveModelTrait, ActiveValue, DbBackend, EntityTrait}; use sea_orm::{entity::*, query::*, ActiveModelTrait, ActiveValue, EntityTrait};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Serialize)] #[derive(Serialize)]
struct NodeWithSensorData { struct NodeWithSensorData {
@ -23,6 +22,10 @@ pub struct CreateGroupWithoutId {
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct NodeWithMac { pub struct NodeWithMac {
mac: String, mac: String,
coord_la: f64,
coord_lo: f64,
battery_minimum: f64,
battery_maximum: f64,
group: uuid::Uuid, group: uuid::Uuid,
} }
@ -35,6 +38,10 @@ impl From<node::Model> for NodeWithMac {
Self { Self {
mac, mac,
coord_la: value.coord_la,
coord_lo: value.coord_lo,
battery_minimum: value.battery_minimum,
battery_maximum: value.battery_maximum,
group: value.group, group: value.group,
} }
} }
@ -51,6 +58,10 @@ impl TryInto<node::Model> for NodeWithMac {
let mac_id = i64::from_be_bytes(mac_id_bytes); let mac_id = i64::from_be_bytes(mac_id_bytes);
Ok(node::Model { Ok(node::Model {
id: mac_id, id: mac_id,
coord_la: self.coord_la,
coord_lo: self.coord_lo,
battery_minimum: self.battery_minimum,
battery_maximum: self.battery_maximum,
group: self.group, group: self.group,
}) })
} }

View file

@ -1,6 +1,8 @@
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
use deku::prelude::*;
use sea_orm::{Database, DatabaseConnection}; use sea_orm::{Database, DatabaseConnection};
use std::env; use std::env;
use tokio::{io::AsyncReadExt, net::TcpListener};
mod controller; mod controller;
@ -13,6 +15,14 @@ struct AppState {
secret: String, secret: String,
} }
#[derive(DekuRead, DekuWrite, Debug)]
struct Data {
mac: [u8; 6],
temp: f32,
battery_voltage: f32,
up_time: u32,
}
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -30,10 +40,30 @@ async fn main() -> std::io::Result<()> {
println!("Finished running migrations"); println!("Finished running migrations");
let state = AppState { let state = AppState {
db: conn, db: conn.clone(),
secret: jwt_secret, secret: jwt_secret,
}; };
tokio::spawn(async {
let db = conn;
let listener = TcpListener::bind("0.0.0.0:7999")
.await
.expect("Couldnt bind to port 7999");
loop {
if let Ok((mut stream, _)) = listener.accept().await {
let mut buffer = vec![0; 1024];
if let Ok(size) = stream.read(&mut buffer).await {
buffer.truncate(size);
if let Ok((data, _)) = Data::from_bytes((&buffer, 0)) {
println!("Received: {:?}", data);
// Process the data or save it to the database
}
}
}
}
});
println!("Listening for connections..."); println!("Listening for connections...");
HttpServer::new(move || { HttpServer::new(move || {
let cors = if cfg!(debug_assertions) { let cors = if cfg!(debug_assertions) {

View file

@ -3,11 +3,19 @@
use sea_orm::entity::prelude::*; use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "node")] #[sea_orm(table_name = "node")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key, auto_increment = false)] #[sea_orm(primary_key, auto_increment = false)]
pub id: i64, pub id: i64,
#[sea_orm(column_type = "Double")]
pub coord_la: f64,
#[sea_orm(column_type = "Double")]
pub coord_lo: f64,
#[sea_orm(column_type = "Double")]
pub battery_minimum: f64,
#[sea_orm(column_type = "Double")]
pub battery_maximum: f64,
pub group: Uuid, pub group: Uuid,
} }

View file

@ -10,19 +10,9 @@ pub struct Model {
pub id: i32, pub id: i32,
#[sea_orm(primary_key, auto_increment = false)] #[sea_orm(primary_key, auto_increment = false)]
pub timestamp: DateTime, pub timestamp: DateTime,
#[sea_orm(column_type = "Double")]
pub coord_la: f64,
#[sea_orm(column_type = "Double")]
pub coord_lo: f64,
#[sea_orm(column_type = "Float")] #[sea_orm(column_type = "Float")]
pub temperature: f32, pub temperature: f32,
#[sea_orm(column_type = "Double")] #[sea_orm(column_type = "Double")]
pub battery_minimum: f64,
#[sea_orm(column_type = "Double")]
pub battery_current: f64,
#[sea_orm(column_type = "Double")]
pub battery_maximum: f64,
#[sea_orm(column_type = "Double")]
pub voltage: f64, pub voltage: f64,
pub uptime: i64, pub uptime: i64,
pub node_id: i64, pub node_id: i64,

View file

@ -27,6 +27,10 @@ impl MigrationTrait for Migration {
.table(Node::Table) .table(Node::Table)
.if_not_exists() .if_not_exists()
.col(big_unsigned(Node::Id).primary_key()) .col(big_unsigned(Node::Id).primary_key())
.col(double(Node::CoordLa))
.col(double(Node::CoordLo))
.col(double(Node::BatteryMinimum).default(-127))
.col(double(Node::BatteryMaximum).default(-127))
.col(uuid(Node::Group)) .col(uuid(Node::Group))
.foreign_key( .foreign_key(
ForeignKey::create() ForeignKey::create()
@ -60,6 +64,10 @@ impl MigrationTrait for Migration {
pub enum Node { pub enum Node {
Table, Table,
Id, // Mac address Id, // Mac address
CoordLa,
CoordLo,
BatteryMinimum, // def: -127
BatteryMaximum, // def: -127
Group, Group,
} }

View file

@ -19,12 +19,7 @@ impl MigrationTrait for Migration {
.col(SensorData::Id) .col(SensorData::Id)
.col(SensorData::Timestamp), .col(SensorData::Timestamp),
) )
.col(double(SensorData::CoordLa))
.col(double(SensorData::CoordLo))
.col(float(SensorData::Temperature).default(-127)) .col(float(SensorData::Temperature).default(-127))
.col(double(SensorData::BatteryMinimum).default(-127))
.col(double(SensorData::BatteryCurrent).default(-127))
.col(double(SensorData::BatteryMaximum).default(-127))
.col(double(SensorData::Voltage).default(-127)) .col(double(SensorData::Voltage).default(-127))
.col(big_unsigned(SensorData::Uptime).default(0)) .col(big_unsigned(SensorData::Uptime).default(0))
.col(big_unsigned(SensorData::NodeId)) .col(big_unsigned(SensorData::NodeId))
@ -55,13 +50,8 @@ enum SensorData {
Table, Table,
Id, // Mac address Id, // Mac address
Timestamp, Timestamp,
CoordLa, Temperature, // def: -127
CoordLo, Voltage, // def: -127
Temperature, // def: -127 Uptime, // def: 0
BatteryMinimum, // def: -127
BatteryCurrent, // def: -127
BatteryMaximum, // def: -127
Voltage, // def: -127
Uptime, // def: 0
NodeId, NodeId,
} }