desktop/src-tauri/src/rpc/manager.rs
2023-03-16 20:13:08 +08:00

64 lines
1.6 KiB
Rust

use paris::error;
use tokio::sync::{broadcast, OnceCell};
use std::fmt::Debug;
use crate::{display, models, picker::led_color::LedColor};
use super::mqtt::MqttRpc;
pub struct Manager {
client: MqttRpc,
initialized: bool,
}
impl Manager {
pub async fn global() -> &'static Self {
static RPC_MANAGER: OnceCell<Manager> = OnceCell::const_new();
RPC_MANAGER
.get_or_init(|| async { Manager::new().await.unwrap() })
.await
}
pub async fn new() -> anyhow::Result<Self> {
let mqtt = MqttRpc::new().await?;
let initialized = match mqtt.initialize().await {
Ok(_) => true,
Err(err) => {
error!("initialize for mqtt was failed. {:?}", err);
false
}
};
Ok(Self {
client: mqtt,
initialized,
})
}
pub async fn listen(&self) {
self.client.listen().await
}
pub async fn publish_led_colors(&self, colors: &Vec<LedColor>) -> anyhow::Result<()> {
let payload = colors
.iter()
.map(|c| c.get_rgb().clone())
.flatten()
.collect::<Vec<u8>>();
self.publish_led_sub_pixels(payload).await
}
pub async fn publish_led_sub_pixels(&self, payload: Vec<u8>) -> anyhow::Result<()> {
self.client.publish_led_sub_pixels(payload).await
}
pub async fn publish_desktop_cmd(&self, field: &str, payload: Vec<u8>) -> anyhow::Result<()>
{
self.client.publish_desktop_cmd(field, payload).await
}
pub fn client(&self) -> &MqttRpc {
&self.client
}
}