Files
test/main.rs
2023-04-27 20:24:52 +02:00

124 lines
3.4 KiB
Rust

use std::fmt::Debug;
use std::str::from_utf8;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use actix_web::{App, get, HttpServer, web::Data};
use rumqttc::{Client, Event, Incoming, MqttOptions, QoS};
use serde::{Deserialize, Serialize};
use todolist::services;
mod todolist;
struct AppState {
todolist_entries: Mutex<Vec<TodolistEntry>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
struct TodolistEntry {
id: i32,
date: i64,
title: String,
}
#[get("/")]
async fn index() -> String {
"This is a health check".to_string()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let state = AppState {
todolist_entries: Mutex::new(Vec::new()),
};
let app_data = Data::new(state);
let state_arc = app_data.clone().into_inner();
let state_arc_cloned = state_arc.clone();
thread::spawn(move || {
loop {
{
let todolist = match state_arc_cloned.todolist_entries.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
println!("Data: {:?}", todolist.to_vec());
}
thread::sleep(Duration::from_millis(1000));
}
});
let mut mqttoptions = MqttOptions::new("rumqtt-sync", "test.mosquitto.org", 1883);
mqttoptions.set_keep_alive(Duration::from_secs(5));
let (mut client, mut connection) = Client::new(mqttoptions, 10);
let result = client.subscribe("hello/rumqtt", QoS::AtLeastOnce);
match result {
Ok(val) => {
println!("Subscribed. {:?}", val)
}
Err(e) => {
println!("Error subscribing. {:?}", e)
}
}
// let result = client.subscribe("zigbee2mqtt/#", QoS::AtLeastOnce);
// match result {
// Ok(val) => {
// println!("Subscribed. {:?}", val)
// }
// Err(e) => {
// println!("Error subscribing. {:?}", e)
// }
// }
thread::spawn(move || {
for i in 0..10 {
client.publish("hello/rumqtt", QoS::AtLeastOnce, false, vec![i; i as usize]).unwrap();
thread::sleep(Duration::from_millis(100));
}
});
thread::spawn(move || {
for (_i, notification) in connection.iter().enumerate() {
match notification {
Ok(event) => {
match event {
Event::Incoming(Incoming::Publish(publish)) => {
let payload = from_utf8(&publish.payload).unwrap_or("");
println!("Topic: {:?}, Qos: {:?}, Retain: {}, Pkid: {:?}, Payload: {:?}",
publish.topic,
publish.qos,
publish.retain,
publish.pkid,
payload,
);
}
Event::Incoming(e) => {
println!("{:?}", e)
}
_ => {}
}
}
_ => {}
}
}
println!("ENDE");
});
HttpServer::new(move || {
App::new()
.app_data(app_data.clone())
.service(index)
.configure(services::config)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}