Switched to tokio and added webserver

This commit is contained in:
Niklas Kapelle 2025-04-16 16:28:45 +02:00
parent 9a26dad304
commit eb39b09632
Signed by: niklas
GPG Key ID: 4EB651B36D841D16
5 changed files with 1521 additions and 19 deletions

1475
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -6,3 +6,5 @@ edition = "2024"
[dependencies]
chrono = { version = "0.4.40", features = ["serde"] }
regex = "1.11.1"
rocket = "0.5.1"
tokio = { version = "1.44.2", features = ["full"] }

View File

@ -1,18 +1,37 @@
use pm3::{pm3_mock, run_pm3};
use std::{sync::mpsc::channel, thread};
use tokio::sync::mpsc;
use webserver::start_webserver;
mod id_store;
mod parser;
mod pm3;
mod webserver;
fn main() {
let (sender, receiver) = channel();
thread::spawn(move || {
// run_pm3(sender);
pm3_mock(sender);
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(32);
tokio::spawn(async move {
match pm3_mock(tx).await {
Ok(()) => {
println!("PM3 exited with an zero error code");
}
Err(e) => {
println!("PM3 failed to run: {}", e);
}
}
});
while true {
println!("{}", receiver.recv().unwrap());
tokio::spawn(async move {
while let Some(line) = rx.recv().await {
println!("Got from channel: {}", line);
}
});
match start_webserver().await {
Ok(()) => {}
Err(e) => {
eprintln!("Failed to start webserver: {}", e);
}
}
}

View File

@ -1,10 +1,11 @@
use std::error::Error;
use std::io::{self, BufRead};
use std::process::{Command, Stdio};
use std::sync::mpsc::Sender;
use std::{thread, time};
use tokio::time::{Duration, sleep};
pub fn run_pm3(sender: Sender<String>) -> Result<(), Box<dyn Error>> {
use tokio::sync::mpsc;
pub async fn run_pm3(tx: mpsc::Sender<String>) -> Result<(), Box<dyn Error>> {
let mut cmd = Command::new("stdbuf")
.arg("-oL")
.arg("pm3")
@ -21,8 +22,8 @@ pub fn run_pm3(sender: Sender<String>) -> Result<(), Box<dyn Error>> {
Ok(line) => {
let parse_result = super::parser::parse_line(&line);
if let Some(uid) = parse_result {
match sender.send(uid) {
Ok(_) => {}
match tx.send(uid).await {
Ok(()) => {}
Err(e) => {
eprintln!("Failed to send to channel: {}", e);
}
@ -44,17 +45,17 @@ pub fn run_pm3(sender: Sender<String>) -> Result<(), Box<dyn Error>> {
}
}
pub fn pm3_mock(sender: Sender<String>) -> Result<(), Box<dyn Error>> {
pub async fn pm3_mock(tx: mpsc::Sender<String>) -> Result<(), Box<dyn Error>> {
#![allow(while_true)]
while true {
match sender.send("F1409618".to_owned()) {
match tx.send("F1409618".to_owned()).await {
Ok(()) => {}
Err(e) => {
eprintln!("Failed to send to channel: {}", e);
}
}
thread::sleep(time::Duration::from_secs(2));
sleep(Duration::from_millis(1000)).await;
}
Ok(())

11
src/webserver.rs Normal file
View File

@ -0,0 +1,11 @@
use rocket::{get, routes};
pub async fn start_webserver() -> Result<(), rocket::Error> {
rocket::build().mount("/", routes![index]).launch().await?;
Ok(())
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}