ApfelNetzwerk/crates/backend/src/main.rs

82 lines
2.1 KiB
Rust

use actix_web::{web, App, HttpServer};
use deku::prelude::*;
use sea_orm::{Database, DatabaseConnection};
use std::env;
use tokio::{io::AsyncReadExt, net::TcpListener};
mod controller;
mod routes;
use routes::config;
#[derive(Clone)]
struct AppState {
db: DatabaseConnection,
secret: String,
}
#[derive(DekuRead, DekuWrite, Debug)]
struct Data {
mac: [u8; 6],
temp: f32,
battery_voltage: f32,
up_time: u32,
}
#[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 jwt_secret = env::var("TOKEN_SECRET").expect("TOKEN_SECRET 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(),
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...");
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
}