Compare commits

..

No commits in common. "v0" and "master" have entirely different histories.
v0 ... master

25 changed files with 1013 additions and 1858 deletions

View File

@ -10,13 +10,13 @@
"tauri": "tauri"
},
"dependencies": {
"@emotion/react": "^11.10.6",
"@emotion/styled": "^11.10.6",
"@fortawesome/fontawesome-svg-core": "^6.3.0",
"@fortawesome/free-regular-svg-icons": "^6.3.0",
"@fortawesome/free-solid-svg-icons": "^6.3.0",
"@emotion/react": "^11.10.5",
"@emotion/styled": "^11.10.5",
"@fortawesome/fontawesome-svg-core": "^6.2.1",
"@fortawesome/free-regular-svg-icons": "^6.2.1",
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"@mui/material": "^5.11.13",
"@mui/material": "^5.11.4",
"@tauri-apps/api": "^1.2.0",
"clsx": "^1.2.1",
"debug": "^4.3.4",
@ -27,28 +27,28 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/plugin-transform-react-jsx": "^7.21.0",
"@babel/plugin-transform-react-jsx": "^7.20.7",
"@emotion/babel-plugin-jsx-pragmatic": "^0.2.0",
"@emotion/serialize": "^1.1.1",
"@tauri-apps/cli": "^1.2.3",
"@tauri-apps/cli": "^1.2.2",
"@types/debug": "^4.1.7",
"@types/node": "^18.15.3",
"@types/ramda": "^0.28.23",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@types/node": "^18.11.18",
"@types/ramda": "^0.28.20",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^2.2.0",
"autoprefixer": "^10.4.14",
"autoprefixer": "^10.4.13",
"babel-plugin-macros": "^3.1.0",
"eslint-config-prettier": "^8.7.0",
"eslint-plugin-import": "^2.27.5",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.4",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-simple-import-sort": "^8.0.0",
"postcss": "^8.4.21",
"prettier": "^2.8.4",
"tailwindcss": "^3.2.7",
"prettier": "^2.8.3",
"tailwindcss": "^3.2.4",
"twin.macro": "^3.1.0",
"typescript": "^4.9.5",
"typescript": "^4.9.4",
"vite": "^3.2.5"
}
}

File diff suppressed because it is too large Load Diff

1346
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -28,6 +28,7 @@ tokio = { version = "1.22.0", features = ["full"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.16"
hex = "0.4.3"
rumqttc = "0.17.0"
time = { version = "0.3.17", features = ["formatting"] }
color_space = "0.5.3"
futures = "0.3.25"
@ -35,11 +36,6 @@ either = "1.8.0"
image = "0.24.5"
mdns = "3.0.0"
macos-app-nap = "0.0.1"
ddc-hi = "0.4.1"
redb = "0.13.0"
paho-mqtt = "0.12.0"
core-graphics = "0.22.3"
display-info = "0.4.1"
[features]
# by default Tauri runs in production mode

View File

@ -75,8 +75,7 @@ impl CoreManager {
colors.push(color);
}
hue = (hue + 1.0) % 360.0;
match rpc::Manager::global()
.await
match rpc::manager::Manager::global()
.publish_led_colors(&colors)
.await
{
@ -140,6 +139,7 @@ impl CoreManager {
tokio::spawn(async move {
let mut global_sub_pixels = HashMap::new();
while let Some(screenshot) = rx.recv().await {
let start_at = Instant::now();
let colors = screenshot.get_colors();
let config = screenshot.get_config();
for (colors, config) in vec![
@ -183,12 +183,11 @@ impl CoreManager {
if global_sub_pixels.len() >= total_colors_count * 3 {
let mut colors = vec![];
for index in 0..global_sub_pixels.len() {
colors.push(*global_sub_pixels.get(&index).unwrap_or(&100));
colors.push(*global_sub_pixels.get(&index).unwrap());
}
// info!("{:?}", colors);
global_sub_pixels = HashMap::new();
match rpc::Manager::global()
.await
match rpc::manager::Manager::global()
.publish_led_sub_pixels(colors)
.await
{

View File

@ -1,25 +0,0 @@
use std::env::current_dir;
use once_cell::sync::OnceCell;
use redb::Database;
use tauri::api::path::config_dir;
use crate::picker;
trait GlobalDatabase<T> {
fn global() -> &'static T;
}
impl GlobalDatabase<Database> for Database {
fn global() -> &'static Database {
static GLOBAL_DATABASE: OnceCell<Database> = OnceCell::new();
GLOBAL_DATABASE.get_or_init(|| {
let path = config_dir()
.unwrap_or(current_dir().unwrap())
.join("main.redb");
let db = Database::create(path).unwrap();
return db;
})
}
}

View File

@ -1,3 +0,0 @@
mod db;
pub use db::*;

View File

@ -1,13 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum Brightness {
Relative(i16),
Absolute(u16),
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DisplayBrightness {
pub brightness: Brightness,
pub display_index: usize,
}

View File

@ -1,36 +0,0 @@
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DisplayConfig {
pub id: usize,
pub brightness: u16,
pub max_brightness: u16,
pub min_brightness: u16,
pub contrast: u16,
pub max_contrast: u16,
pub min_contrast: u16,
pub mode: u16,
pub max_mode: u16,
pub min_mode: u16,
pub last_modified_at: SystemTime,
}
impl DisplayConfig {
pub fn default(index: usize) -> Self {
Self {
id: index,
brightness: 30,
contrast: 50,
mode: 0,
last_modified_at: SystemTime::now(),
max_brightness: 100,
min_brightness: 0,
max_contrast: 100,
min_contrast: 0,
max_mode: 15,
min_mode: 0,
}
}
}

View File

@ -1,186 +0,0 @@
use std::{
borrow::Borrow,
collections::HashMap,
ops::Sub,
sync::Arc,
time::{Duration, SystemTime},
};
use base64::Config;
use ddc_hi::Display;
use paris::{error, info};
use tauri::async_runtime::Mutex;
use tokio::sync::{broadcast, OwnedMutexGuard};
use tracing::warn;
use crate::{display::Brightness, models, rpc};
use super::{display_config::DisplayConfig, DisplayBrightness};
use ddc_hi::Ddc;
pub struct Manager {
displays: Arc<Mutex<HashMap<usize, Arc<Mutex<DisplayConfig>>>>>,
}
impl Manager {
pub fn global() -> &'static Self {
static DISPLAY_MANAGER: once_cell::sync::OnceCell<Manager> =
once_cell::sync::OnceCell::new();
DISPLAY_MANAGER.get_or_init(|| Self::create())
}
pub fn create() -> Self {
let instance = Self {
displays: Arc::new(Mutex::new(HashMap::new())),
};
instance
}
pub async fn subscribe_display_brightness(&self) {
let rpc = rpc::Manager::global().await;
let mut rx = rpc.client().subscribe_change_display_brightness_rx();
loop {
if let Ok(display_brightness) = rx.recv().await {
if let Err(err) = self.set_display_brightness(display_brightness).await {
error!("set_display_brightness failed. {:?}", err);
}
}
}
}
fn read_display_config_by_ddc(index: usize) -> anyhow::Result<DisplayConfig> {
let mut displays = Display::enumerate();
match displays.get_mut(index) {
Some(display) => {
let mut config = DisplayConfig::default(index);
match display.handle.get_vcp_feature(0x10) {
Ok(value) => {
config.max_brightness = value.maximum();
config.min_brightness = 0;
config.brightness = value.value();
}
Err(_) => {}
};
match display.handle.get_vcp_feature(0x12) {
Ok(value) => {
config.max_contrast = value.maximum();
config.min_contrast = 0;
config.contrast = value.value();
}
Err(_) => {}
};
match display.handle.get_vcp_feature(0xdc) {
Ok(value) => {
config.max_mode = value.maximum();
config.min_mode = 0;
config.mode = value.value();
}
Err(_) => {}
};
Ok(config)
}
None => anyhow::bail!("display#{} is missed.", index),
}
}
async fn get_display(&self, index: usize) -> anyhow::Result<OwnedMutexGuard<DisplayConfig>> {
let mut displays = self.displays.lock().await;
match displays.get_mut(&index) {
Some(config) => {
let mut config = config.to_owned().lock_owned().await;
if config.last_modified_at > SystemTime::now().sub(Duration::from_secs(10)) {
info!("cached");
return Ok(config);
}
return match Self::read_display_config_by_ddc(index) {
Ok(config) => {
let id = config.id;
let value = Arc::new(Mutex::new(config));
let valueGuard = value.clone().lock_owned().await;
displays.insert(id, value);
info!("read form ddc");
Ok(valueGuard)
}
Err(err) => {
warn!(
"can not read config from display by ddc, use CACHED value. {:?}",
err
);
config.last_modified_at = SystemTime::now();
Ok(config)
}
};
}
None => {
let config = Self::read_display_config_by_ddc(index).map_err(|err| {
anyhow::anyhow!(
"can not read config from display by ddc,use DEFAULT value. {:?}",
err
)
})?;
let id = config.id;
let value = Arc::new(Mutex::new(config));
let valueGuard = value.clone().lock_owned().await;
displays.insert(id, value);
Ok(valueGuard)
}
}
}
pub async fn set_display_brightness(
&self,
display_brightness: DisplayBrightness,
) -> anyhow::Result<()> {
match Display::enumerate().get_mut(display_brightness.display_index) {
Some(display) => {
match self.get_display(display_brightness.display_index).await {
Ok(mut config) => {
let curr = config.brightness;
info!("curr_brightness: {:?}", curr);
let mut target = match display_brightness.brightness {
Brightness::Relative(v) => curr.wrapping_add_signed(v),
Brightness::Absolute(v) => v,
};
if target.gt(&config.max_brightness) {
target = config.max_brightness;
} else if target.lt(&config.min_brightness) {
target = config.min_brightness;
}
config.brightness = target;
display
.handle
.set_vcp_feature(0x10, target as u16)
.map_err(|err| anyhow::anyhow!("can not set brightness. {:?}", err))?;
let rpc = rpc::Manager::global().await;
rpc.publish_desktop_cmd(
format!("display{}/brightness", display_brightness.display_index).as_str(),
target.to_be_bytes().to_vec(),
)
.await;
}
Err(err) => {
info!(
"can not get display#{} brightness. {:?}",
display_brightness.display_index, err
);
if let Brightness::Absolute(v) = display_brightness.brightness {
display.handle.set_vcp_feature(0x10, v).map_err(|err| {
anyhow::anyhow!("can not set brightness. {:?}", err)
})?;
};
}
};
}
None => {
warn!("display#{} is not found.", display_brightness.display_index);
}
}
Ok(())
}
}

View File

@ -1,9 +0,0 @@
mod brightness;
mod manager;
mod display_config;
pub use brightness::*;
pub use manager::*;

View File

@ -5,30 +5,24 @@
#![feature(bool_to_option)]
mod core;
mod db;
mod display;
mod picker;
mod rpc;
mod models;
use crate::core::AmbientLightMode;
use crate::core::CoreManager;
use once_cell::sync::OnceCell;
use paris::*;
use picker::config::DisplayConfig;
use picker::manager::Picker;
use picker::screenshot::ScreenshotDto;
use tauri::async_runtime::Mutex;
use once_cell::sync::OnceCell;
static GET_SCREENSHOT_LOCK: OnceCell<Mutex<bool>> = OnceCell::new();
#[tauri::command]
async fn take_snapshot() -> Vec<ScreenshotDto> {
info!("Hi?");
let _lock = GET_SCREENSHOT_LOCK
.get_or_init(|| Mutex::new(false))
.lock()
.await;
let _lock = GET_SCREENSHOT_LOCK.get_or_init(|| Mutex::new(false)).lock().await;
info!("Hi!");
let manager = Picker::global().await;
@ -95,11 +89,7 @@ async fn play_mode(target_mode: AmbientLightMode) {
#[tokio::main]
async fn main() {
let display_manager = display::Manager::global();
tokio::spawn(display_manager.subscribe_display_brightness());
let rpc_manager = rpc::Manager::global().await;
tokio::spawn(rpc_manager.listen());
rpc::manager::Manager::global();
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
take_snapshot,

View File

@ -1,8 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct CmdRespWithRange<T = u16> {
pub value: T,
pub max: T,
pub min: T,
}

View File

@ -1,10 +0,0 @@
use serde::{Serialize, Deserialize};
use super::control_value::ControlValue;
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct ConfigDisplayCmd<T = ControlValue> {
pub display_index: usize,
pub value: T,
}

View File

@ -1,8 +0,0 @@
use serde::{Serialize, Deserialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum ControlValue<AT = u16, RT = i16> {
Absolute(AT),
Relative(RT),
}

View File

@ -1,10 +0,0 @@
mod control_value;
mod mq_message;
mod config_display_cmd;
mod cmd_resp_with_range;
pub use control_value::*;
pub use mq_message::*;
pub use config_display_cmd::*;
pub use cmd_resp_with_range::*;

View File

@ -1,17 +0,0 @@
use serde::{Serialize, Deserialize};
use super::{ConfigDisplayCmd, CmdRespWithRange};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum CmdMqMessage {
Brightness(ConfigDisplayCmd),
Contrast(ConfigDisplayCmd),
PresetMode(ConfigDisplayCmd),
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum CmdRespMqMessage {
Brightness(ConfigDisplayCmd<CmdRespWithRange>),
Contrast(ConfigDisplayCmd<CmdRespWithRange>),
PresetMode(ConfigDisplayCmd<CmdRespWithRange>),
}

View File

@ -17,12 +17,11 @@ pub struct LedStripConfig {
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DisplayConfig {
pub id: u32,
pub id: usize,
pub index_of_display: usize,
pub display_width: usize,
pub display_height: usize,
pub led_strip_of_borders: LedStripConfigOfBorders,
pub scale_factor: f32,
}
impl LedStripConfigOfBorders {
@ -38,11 +37,10 @@ impl LedStripConfigOfBorders {
impl DisplayConfig {
pub fn default(
id: u32,
id: usize,
index_of_display: usize,
display_width: usize,
display_height: usize,
scale_factor: f32,
) -> Self {
Self {
id,
@ -50,7 +48,6 @@ impl DisplayConfig {
display_width,
display_height,
led_strip_of_borders: LedStripConfigOfBorders::default(),
scale_factor,
}
}
}

View File

@ -115,6 +115,7 @@ mod tests {
async fn write_config_to_disk_should_be_successful() {
let temp = TestDir::temp().create("config_dir", test_dir::FileType::Dir);
let config_file_path = temp.path("config_dir").join("picker.config.json");
let manager = crate::picker::config::manger::Manager::default();
crate::picker::config::manger::Manager::write_config_to_disk(
config_file_path.clone(),
&Configuration::default(),

View File

@ -1,9 +1,5 @@
use core_graphics::display::{
kCGNullWindowID, kCGWindowImageDefault, kCGWindowListOptionOnScreenOnly, CGDisplay,
};
use paris::info;
use scrap::{Capturer, Display};
use tracing::debug;
use super::{config::DisplayConfig, screen::Screen, screenshot::Screenshot};
@ -13,10 +9,17 @@ pub struct DisplayPicker {
}
impl DisplayPicker {
pub fn new(screen: Screen, config: DisplayConfig) -> Self {
Self { screen, config }
}
pub fn from_config(config: DisplayConfig) -> anyhow::Result<Self> {
let displays = Display::all()
.map_err(|error| anyhow::anyhow!("Can not get all of displays. {}", error))?;
let display = displays.into_iter().skip(config.index_of_display).next();
let display = displays
.into_iter()
.skip(config.index_of_display)
.next();
match display {
Some(display) => {
@ -36,67 +39,13 @@ impl DisplayPicker {
}
pub fn take_screenshot(&mut self) -> anyhow::Result<Screenshot> {
debug!("take_screenshot");
let start_at = std::time::Instant::now();
let cg_display = CGDisplay::new(self.config.id);
let cg_image = CGDisplay::screenshot(
cg_display.bounds(),
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID,
kCGWindowImageDefault,
)
.ok_or_else(|| anyhow::anyhow!("Display#{}: take screenshot failed", self.config.id))?;
debug!("take screenshot took {}ms", start_at.elapsed().as_millis());
let buffer = cg_image.data();
let bytes_per_row = cg_image.bytes_per_row() as f32;
let height = cg_image.height();
let width = cg_image.width();
let scale_factor = self.config.scale_factor;
let image_height = (height as f32 / scale_factor) as u32;
let image_width = (width as f32 / scale_factor) as u32;
debug!(
"raw image: {}x{}, output image: {}x{}",
width, height, image_width, image_height
);
// // from bitmap vec
let mut image_buffer = vec![0u8; (image_width * image_height * 3) as usize];
for y in 0..image_height {
for x in 0..image_width {
let offset =
(((y as f32) * bytes_per_row + (x as f32) * 4.0) * scale_factor) as usize;
let b = buffer[offset];
let g = buffer[offset + 1];
let r = buffer[offset + 2];
let a = buffer[offset + 3];
let offset = (y * image_width + x) as usize;
image_buffer[offset * 3] = r;
image_buffer[offset * 3 + 1] = g;
image_buffer[offset * 3 + 2] = b;
}
}
debug!(
"convert to image buffer took {}ms",
start_at.elapsed().as_millis()
);
// println!("encode to png took {}ms", start_at.elapsed().as_millis());
// // // base64 image
// let mut image_base64 = String::new();
// image_base64.push_str("data:image/png;base64,");
// let encoded = base64::engine::general_purpose::STANDARD_NO_PAD.encode(image_png);
// image_base64.push_str(encoded.as_str());
// println!("took {}ms", start_at.elapsed().as_millis());
// println!("image_base64: {}", image_base64.len());
let bitmap = self
.screen
.take()
.map_err(|error| anyhow::anyhow!("take screenshot for display failed. {}", error))?;
// info!("bitmap size {}", bitmap.len());
let screenshot = Screenshot::new(image_buffer, self.config);
let screenshot = Screenshot::new(bitmap, self.config);
Ok(screenshot)
}
}

View File

@ -1,5 +1,3 @@
use core_graphics::display::CGDisplay;
use display_info::DisplayInfo;
use futures::{stream::FuturesUnordered, StreamExt};
use paris::info;
use scrap::Display;
@ -45,16 +43,16 @@ impl Picker {
pub async fn list_displays(&self) -> anyhow::Result<Vec<ScreenshotDto>> {
let mut configs = vec![];
let displays = DisplayInfo::all()
let displays = Display::all()
.map_err(|error| anyhow::anyhow!("Can not get all of displays. {}", error))?;
// configs.clear();
let mut futs = FuturesUnordered::new();
for (index, display) in displays.iter().enumerate() {
let height = display.height as usize;
let width = display.width as usize;
let config = DisplayConfig::default(display.id, index, width, height, display.scale_factor);
let height = display.height();
let width = display.width();
let config = DisplayConfig::default(index, index, width, height);
configs.push(config);
}

View File

@ -3,6 +3,7 @@ use std::{io::ErrorKind::WouldBlock, time::Duration, thread};
pub struct Screen {
capturer: Option<Capturer>,
init_error: Option<anyhow::Error>,
pub width: usize,
pub height: usize,
}
@ -11,6 +12,16 @@ impl Screen {
pub fn new(capturer: Capturer, width: usize, height: usize) -> Self {
Self {
capturer: Some(capturer),
init_error: None,
width,
height,
}
}
pub fn new_failed(init_error: anyhow::Error, width: usize, height: usize) -> Self {
Self {
capturer: None,
init_error: Some(init_error),
width,
height,
}

View File

@ -1,42 +1,23 @@
use paris::error;
use tokio::sync::{broadcast, OnceCell};
use std::fmt::Debug;
use crate::picker::led_color::LedColor;
use crate::{display, models, picker::led_color::LedColor};
use super::mqtt::MqttRpc;
use super::mqtt::MqttConnection;
use once_cell::sync::OnceCell;
pub struct Manager {
client: MqttRpc,
initialized: bool,
mqtt: MqttConnection,
}
impl Manager {
pub async fn global() -> &'static Self {
static RPC_MANAGER: OnceCell<Manager> = OnceCell::const_new();
pub fn global() -> &'static Self {
static RPC_MANAGER: OnceCell<Manager> = OnceCell::new();
RPC_MANAGER
.get_or_init(|| async { Manager::new().await.unwrap() })
.await
RPC_MANAGER.get_or_init(|| Manager::new())
}
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 fn new() -> Self {
let mut mqtt = MqttConnection::new();
mqtt.initialize();
Self { mqtt }
}
pub async fn publish_led_colors(&self, colors: &Vec<LedColor>) -> anyhow::Result<()> {
@ -46,18 +27,29 @@ impl Manager {
.flatten()
.collect::<Vec<u8>>();
self.publish_led_sub_pixels(payload).await
self.mqtt
.client
.publish(
"display-ambient-light/desktop/colors",
rumqttc::QoS::AtLeastOnce,
false,
payload,
)
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
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
self.mqtt
.client
.publish(
"display-ambient-light/desktop/colors",
rumqttc::QoS::AtLeastOnce,
false,
payload,
)
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
}

View File

@ -1,4 +1,2 @@
mod manager;
pub mod manager;
pub mod mqtt;
pub use manager::*;

View File

@ -1,187 +1,44 @@
use crate::{display, models};
use futures::StreamExt;
use paho_mqtt as mqtt;
use paris::{error, info, warn};
use serde_json::json;
use std::{borrow::Borrow, fmt::Debug, rc::Rc, sync::Arc, time::Duration};
use tauri::async_runtime::{Mutex, TokioJoinHandle};
use rumqttc::{AsyncClient, MqttOptions, QoS};
use std::time::Duration;
use time::{format_description, OffsetDateTime};
use tokio::{sync::broadcast, task, time::sleep};
use tokio::task;
use tracing::warn;
const DISPLAY_TOPIC: &'static str = "display-ambient-light/display";
const DESKTOP_TOPIC: &'static str = "display-ambient-light/desktop";
const DISPLAY_BRIGHTNESS_TOPIC: &'static str = "display-ambient-light/board/brightness";
const BOARD_SEND_CMD: &'static str = "display-ambient-light/board/cmd";
pub struct MqttRpc {
client: mqtt::AsyncClient,
change_display_brightness_tx: broadcast::Sender<display::DisplayBrightness>,
message_tx: broadcast::Sender<models::CmdMqMessage>,
pub struct MqttConnection {
pub client: AsyncClient,
}
impl MqttRpc {
pub async fn new() -> anyhow::Result<Self> {
let client = mqtt::AsyncClient::new("tcp://192.168.31.11:1883")
.map_err(|err| anyhow::anyhow!("can not create MQTT client. {:?}", err))?;
impl MqttConnection {
pub fn new() -> Self {
let mut options = MqttOptions::new("rumqtt-async", "192.168.31.11", 1883);
options.set_keep_alive(Duration::from_secs(5));
client.set_connected_callback(|client| {
info!("MQTT server connected.");
client.subscribe("display-ambient-light/board/#", mqtt::QOS_1);
client.subscribe(format!("{}/#", DISPLAY_TOPIC), mqtt::QOS_1);
});
client.set_connection_lost_callback(|client| {
info!("MQTT server connection lost.");
});
client.set_disconnected_callback(|_, a1, a2| {
info!("MQTT server disconnected. {:?} {:?}", a1, a2);
});
let mut last_will_payload = serde_json::Map::new();
last_will_payload.insert("message".to_string(), json!("offline"));
last_will_payload.insert(
"time".to_string(),
serde_json::Value::String(
OffsetDateTime::now_utc()
.format(
&format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")
.unwrap(),
)
.unwrap()
.to_string(),
),
);
let last_will = mqtt::Message::new(
format!("{}/status", DESKTOP_TOPIC),
serde_json::to_string(&last_will_payload)
.unwrap()
.as_bytes(),
mqtt::QOS_1,
);
let connect_options = mqtt::ConnectOptionsBuilder::new()
.keep_alive_interval(Duration::from_secs(5))
.will_message(last_will)
.automatic_reconnect(Duration::from_secs(1), Duration::from_secs(5))
.finalize();
let token = client.connect(connect_options);
token.await.map_err(|err| {
anyhow::anyhow!(
"can not connect MQTT server. wait for connect token failed. {:?}",
err
)
})?;
let (change_display_brightness_tx, _) =
broadcast::channel::<display::DisplayBrightness>(16);
let (message_tx, _) = broadcast::channel::<models::CmdMqMessage>(32);
Ok(Self {
client,
change_display_brightness_tx,
message_tx,
})
}
pub async fn listen(&self) {
let change_display_brightness_tx2 = self.change_display_brightness_tx.clone();
let message_tx_cloned = self.message_tx.clone();
let mut stream = self.client.to_owned().get_stream(100);
while let Some(notification) = stream.next().await {
match notification {
Some(notification) => match notification.topic() {
DISPLAY_BRIGHTNESS_TOPIC => {
let payload_text = String::from_utf8(notification.payload().to_vec());
match payload_text {
Ok(payload_text) => {
let display_brightness: Result<display::DisplayBrightness, _> =
serde_json::from_str(payload_text.as_str());
match display_brightness {
Ok(display_brightness) => {
match change_display_brightness_tx2.send(display_brightness)
{
let (client, mut eventloop) = AsyncClient::new(options, 10);
task::spawn(async move {
loop {
match eventloop.poll().await {
Ok(_) => {}
Err(err) => {
warn!(
"can not send display brightness to channel. {:?}",
err
);
}
}
}
Err(err) => {
warn!(
"can not parse display brightness from payload. {:?}",
err
);
}
}
}
Err(err) => {
warn!("can not parse display brightness from payload. {:?}", err);
}
}
}
BOARD_SEND_CMD => {
let payload_text = String::from_utf8(notification.payload().to_vec());
match payload_text {
Ok(payload_text) => {
let message: Result<models::CmdMqMessage, _> =
serde_json::from_str(payload_text.as_str());
match message {
Ok(message) => match message_tx_cloned.send(message) {
Ok(_) => {}
Err(err) => {
warn!("can not send message to channel. {:?}", err);
}
},
Err(err) => {
warn!("can not parse message from payload. {:?}", err);
}
}
}
Err(err) => {
warn!("can not parse message from payload. {:?}", err);
}
}
}
_ => {}
},
_ => {
warn!("can not get notification from MQTT server.");
println!("MQTT Error Event = {:?}", err);
}
}
}
});
Self { client }
}
pub async fn initialize(&self) -> anyhow::Result<()> {
// self.subscribe_board()?;
// self.subscribe_display()?;
pub fn initialize(&mut self) {
self.subscribe_board();
self.broadcast_desktop_online();
anyhow::Ok(())
}
fn subscribe_board(&self) -> anyhow::Result<()> {
async fn subscribe_board(&self) {
self.client
.subscribe("display-ambient-light/board/#", mqtt::QOS_1)
.wait()
.map_err(|err| anyhow::anyhow!("subscribe board failed. {:?}", err))
.map(|_| ())
}
fn subscribe_display(&self) -> anyhow::Result<()> {
self.client
.subscribe(format!("{}/#", DISPLAY_TOPIC), mqtt::QOS_1)
.wait()
.map_err(|err| anyhow::anyhow!("subscribe board failed. {:?}", err))
.map(|_| ())
.subscribe("display-ambient-light/board/#", QoS::AtMostOnce)
.await;
}
fn broadcast_desktop_online(&self) {
fn broadcast_desktop_online(&mut self) {
let client = self.client.to_owned();
task::spawn(async move {
loop {
@ -189,12 +46,15 @@ impl MqttRpc {
.format(&format_description::well_known::Iso8601::DEFAULT)
{
Ok(now_str) => {
let msg = mqtt::Message::new(
match client
.publish(
"display-ambient-light/desktop/online",
QoS::AtLeastOnce,
false,
now_str.as_bytes(),
mqtt::QOS_0,
);
match client.publish(msg).await {
)
.await
{
Ok(_) => {}
Err(error) => {
warn!("can not publish last online time. {}", error)
@ -209,32 +69,4 @@ impl MqttRpc {
}
});
}
pub async fn publish_led_sub_pixels(&self, payload: Vec<u8>) -> anyhow::Result<()> {
self.client
.publish(mqtt::Message::new(
"display-ambient-light/desktop/colors",
payload,
mqtt::QOS_1,
))
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
pub fn subscribe_change_display_brightness_rx(
&self,
) -> broadcast::Receiver<display::DisplayBrightness> {
self.change_display_brightness_tx.subscribe()
}
pub async fn publish_desktop_cmd(&self, field: &str, payload: Vec<u8>) -> anyhow::Result<()>
{
self.client
.publish(mqtt::Message::new(
format!("{}/{}", DESKTOP_TOPIC, field),
payload,
mqtt::QOS_1,
))
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
}