102 lines
3 KiB
Rust
102 lines
3 KiB
Rust
use actix_web::{web, App, HttpServer};
|
|
use deku::prelude::*;
|
|
use sea_orm::{ActiveModelTrait, ActiveValue, Database, DatabaseConnection};
|
|
use std::env;
|
|
use tokio::{io::AsyncReadExt, net::TcpListener};
|
|
|
|
mod controller;
|
|
|
|
mod routes;
|
|
use routes::config;
|
|
|
|
#[derive(Clone)]
|
|
struct AppState {
|
|
db: DatabaseConnection,
|
|
}
|
|
|
|
#[derive(DekuRead, DekuWrite, Debug)]
|
|
#[deku(endian = "little")]
|
|
struct Data {
|
|
#[deku(bytes = 8)]
|
|
mac: [u8; 8],
|
|
temp: f32,
|
|
battery_voltage: f32,
|
|
up_time: u64,
|
|
}
|
|
|
|
#[actix_web::main]
|
|
async fn main() -> std::io::Result<()> {
|
|
#[cfg(debug_assertions)]
|
|
println!("Running debug build -> enabling permissive CORS");
|
|
|
|
dotenvy::dotenv().ok();
|
|
|
|
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
|
|
|
let conn = Database::connect(&db_url)
|
|
.await
|
|
.expect("Connecting to Database failed");
|
|
|
|
println!("Finished running migrations");
|
|
|
|
let state = AppState { db: conn.clone() };
|
|
|
|
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 {
|
|
println!("ESP CONNECTED");
|
|
let mut buffer = vec![0; 24];
|
|
loop {
|
|
if let Ok(_) = stream.read(&mut buffer).await {
|
|
println!("{:#x?}", &buffer);
|
|
if let Ok((_, mut value)) = Data::from_bytes((&buffer, 0)) {
|
|
println!("Received: {:#?}", value);
|
|
|
|
value.mac.rotate_right(2);
|
|
|
|
let mac = i64::from_be_bytes(value.mac);
|
|
|
|
let sensor_data = entity::sensor_data::ActiveModel {
|
|
id: ActiveValue::Set(mac),
|
|
timestamp: ActiveValue::Set(chrono::Utc::now().naive_utc()),
|
|
temperature: ActiveValue::Set(value.temp),
|
|
voltage: ActiveValue::Set(value.battery_voltage),
|
|
uptime: ActiveValue::Set(value.up_time as i64),
|
|
};
|
|
|
|
let result = sensor_data.insert(&db).await;
|
|
|
|
match result {
|
|
Err(_) => println!("Failed to insert data"),
|
|
_ => (),
|
|
}
|
|
} else {
|
|
println!("Failed to parse data");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
println!("Listening for connections...");
|
|
HttpServer::new(move || {
|
|
let cors = if cfg!(debug_assertions) {
|
|
actix_cors::Cors::permissive()
|
|
} else {
|
|
actix_cors::Cors::default()
|
|
};
|
|
App::new()
|
|
.wrap(cors)
|
|
.app_data(web::Data::new(state.clone()))
|
|
.configure(config)
|
|
})
|
|
.bind(("0.0.0.0", 8080))?
|
|
.run()
|
|
.await
|
|
}
|