justaCasualCoder / Frigatify

A Rust client providing FRIGATe nvr linux desktop NOTIFications using only MQTT.
GNU General Public License v3.0
1 stars 0 forks source link

Async task handling #8

Open bazylhorsey opened 3 months ago

bazylhorsey commented 3 months ago
use rumqttc::{MqttOptions, Client, QoS};
use std::time::Duration;
use config::Config;
use serde::{Deserialize, Serialize};
use env_logger;

#[derive(Debug, Deserialize, Serialize)]
struct AppConfig {
    mqtt_host: String,
    mqtt_port: u16,
    frigate_host: String,
    notify_cmd: Option<String>,
}

#[tokio::main]
async fn main() {
    // Enable Logger
    env_logger::init();

    // Config file reading
    let file_path = std::path::Path::new("./config/config.toml");

    // Deserializing the config file into AppConfig struct
    let settings = Config::builder()
        .add_source(config::File::with_name(file_path.to_str().unwrap()))
        .build()
        .unwrap();
    let config_values: AppConfig = settings.try_deserialize().unwrap();

    // Set up MQTT
    let mut mqttoptions = MqttOptions::new("frigatify", config_values.mqtt_host, config_values.mqtt_port);
    mqttoptions.set_keep_alive(Duration::from_secs(20));
    mqttoptions.set_clean_session(false);

    let (client, mut connection) = Client::new(mqttoptions, 10);
    client.subscribe("frigate/events", QoS::ExactlyOnce).unwrap();

    // Handle MQTT connection and messages
    while let Ok(event) = connection.eventloop.poll().await {
        match event {
            rumqttc::Event::Incoming(rumqttc::Packet::Publish(publish)) => {
                let payload = String::from_utf8_lossy(&publish.payload);
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&payload) {
                    log::debug!("Deserialized JSON: {:?}", json);
                    if json["type"] == "new" {
                        tokio::spawn(async move {
                            println!("Hello, World!");
                        });
                    }
                } else {
                    eprintln!("Error deserializing JSON");
                }
            }
            rumqttc::Event::Incoming(rumqttc::Packet::ConnAck(data)) => {
                if data.code == rumqttc::ConnectReturnCode::Success {
                    println!("Connected!");
                }
            }
            other => {
                log::debug!("{:?}", other);
            }
        }
    }
}
bazylhorsey commented 3 months ago

What are stopping us from doing something like this? This is a rough draft not fully debugged.