Compare commits

..

3 Commits

10 changed files with 261 additions and 172 deletions

16
src-tauri/Cargo.lock generated
View File

@ -563,6 +563,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bd4b30a6560bbd9b4620f4de34c3f14f60848e58a9b7216801afcb4c7b31c3c"
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "embed_plist"
version = "1.2.2"
@ -1266,6 +1272,15 @@ dependencies = [
"windows-sys 0.45.0",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "0.4.8"
@ -2758,6 +2773,7 @@ dependencies = [
"display-info",
"env_logger",
"hex",
"itertools",
"log",
"paho-mqtt",
"paris",

View File

@ -30,6 +30,7 @@ hex = "0.4.3"
toml = "0.7.3"
paho-mqtt = "0.12.1"
time = {version="0.3.20", features= ["formatting"] }
itertools = "0.10.5"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem

View File

@ -1,4 +1,4 @@
use std::env::current_dir;
use std::{env::current_dir, fmt::format};
use paris::{error, info};
use serde::{Deserialize, Serialize};
@ -56,6 +56,8 @@ impl LedStripConfigGroup {
let config: LedStripConfigGroup = toml::from_str(&config)
.map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?;
log::info!("config loaded: {:?}", config.strips.iter().map(|c| format!("{}#{}", c.index, c.display_id)).collect::<Vec<_>>());
Ok(config)
} else {
info!("config file not exist, fallback to default config");

View File

@ -5,7 +5,7 @@ use tokio::sync::OnceCell;
use crate::ambient_light::{config, LedStripConfigGroup};
use super::Border;
use super::{Border, SamplePointMapper};
pub struct ConfigManager {
config: Arc<RwLock<LedStripConfigGroup>>,
@ -62,19 +62,21 @@ impl ConfigManager {
) -> anyhow::Result<()> {
let mut config = self.config.write().await;
for config in config.strips.iter_mut() {
if config.display_id == display_id && config.border == border {
let target = config.len as i64 + delta_len as i64;
for strip in config.strips.iter_mut() {
if strip.display_id == display_id && strip.border == border {
let target = strip.len as i64 + delta_len as i64;
if target < 0 || target > 1000 {
return Err(anyhow::anyhow!(
"Overflow. range: 0-1000, current: {}",
target
));
}
config.len = target as usize;
strip.len = target as usize;
}
}
Self::rebuild_mappers(&mut config);
let cloned_config = config.clone();
drop(config);
@ -88,6 +90,24 @@ impl ConfigManager {
Ok(())
}
fn rebuild_mappers(config: &mut LedStripConfigGroup) {
let mut prev_end = 0;
let mappers: Vec<SamplePointMapper> = config
.strips
.iter()
.map(|strip| {
let mapper = SamplePointMapper {
start: prev_end,
end: prev_end + strip.len,
};
prev_end = mapper.end;
mapper
})
.collect();
config.mappers = mappers;
}
pub async fn set_items(&self, items: Vec<config::LedStripConfig>) -> anyhow::Result<()> {
let mut config = self.config.write().await;

View File

@ -1,15 +1,20 @@
use std::sync::Arc;
use std::{borrow::BorrowMut, collections::HashMap, sync::Arc, time::Duration};
use paris::warn;
use tauri::async_runtime::RwLock;
use tokio::sync::watch;
use tauri::async_runtime::{Mutex, RwLock};
use tokio::{sync::watch, time::sleep};
use crate::{
ambient_light::{config, ConfigManager},
rpc::MqttRpc,
screenshot::Screenshot,
screenshot_manager::ScreenshotManager,
};
use itertools::Itertools;
use super::{LedStripConfigGroup, SamplePointConfig};
pub struct LedColorsPublisher {
rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
@ -35,59 +40,85 @@ impl LedColorsPublisher {
pub fn start(&self) -> anyhow::Result<()> {
let tx = self.tx.clone();
tokio::spawn(async move {
let tx = tx.write().await;
let handler = tokio::spawn(async move {
loop {
log::info!("colors update loop AAA");
let screenshot_manager = ScreenshotManager::global().await;
let tx = tx.write().await;
let screenshot_manager = ScreenshotManager::global().await;
let config_manager = ConfigManager::global().await;
let config_receiver = config_manager.clone_config_update_receiver();
let configs = config_receiver.borrow().clone();
let configs = Self::get_colors_configs(&configs).await;
let mut some_screenshot_receiver_is_none = false;
loop {
let mut screenshots = Vec::new();
for rx in configs.screenshot_receivers.to_owned() {
let mut rx = rx.lock_owned().await;
if rx.is_none() {
some_screenshot_receiver_is_none = true;
warn!("screenshot receiver is none");
continue;
}
let rx = rx.as_mut().unwrap();
if let Err(err) = rx.changed().await {
warn!("rx changed error: {}", err);
continue;
}
log::info!("screenshot updated");
let screenshot = rx.borrow().clone();
screenshots.push(screenshot);
}
let colors = screenshot_manager
.get_all_colors(
&configs.sample_point_groups,
&configs.mappers,
&screenshots,
)
.await;
match tx.send(colors) {
Ok(_) => {
// log::info!("colors updated");
}
Err(_) => {
warn!("colors update failed");
}
}
if some_screenshot_receiver_is_none
|| config_receiver.has_changed().unwrap_or(true)
{
break;
}
}
}
});
tokio::spawn(async move {
let config_manager = ConfigManager::global().await;
let mut config_receiver = config_manager.clone_config_update_receiver();
loop {
let configs = config_manager.configs().await;
let channels = screenshot_manager.channels.read().await;
let mut colors_configs = Vec::new();
for (display_id, rx) in channels.iter() {
let led_strip_configs: Vec<_> = configs
.strips
.iter()
.filter(|c| c.display_id == *display_id)
.collect();
if led_strip_configs.len() == 0 {
warn!("no led strip config for display_id: {}", display_id);
continue;
}
let mut rx = rx.clone();
if rx.changed().await.is_ok() {
let screenshot = rx.borrow().clone();
// log::info!("screenshot updated: {:?}", display_id);
let points: Vec<_> = led_strip_configs
.iter()
.map(|config| screenshot.get_sample_points(&config))
.flatten()
.collect();
let colors_config = config::SamplePointConfig {
display_id: *display_id,
points,
};
colors_configs.push(colors_config);
}
}
let colors = screenshot_manager.get_all_colors(&colors_configs, &configs.mappers, &channels).await;
match tx.send(colors) {
Ok(_) => {
// log::info!("colors updated");
}
Err(_) => {
warn!("colors update failed");
}
if let Err(err) = config_receiver.changed().await {
warn!("config receiver changed error: {}", err);
continue;
}
let configs = config_receiver.borrow().clone();
let configs = Self::get_colors_configs(&configs).await;
handler.abort();
break;
}
});
Ok(())
@ -102,4 +133,78 @@ impl LedColorsPublisher {
pub async fn clone_receiver(&self) -> watch::Receiver<Vec<u8>> {
self.rx.read().await.clone()
}
pub async fn get_colors_configs(configs: &LedStripConfigGroup) -> AllColorConfig {
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.read().await;
let display_ids = configs
.strips
.iter()
.map(|c| c.display_id)
.unique()
.collect::<Vec<_>>();
let mappers = configs.mappers.clone();
let mut local_rx_list = Vec::new();
let mut colors_configs = Vec::new();
for display_id in display_ids.clone().iter() {
let display_id = *display_id;
let channel = channels.get(&display_id);
let channel = match channel {
Some(channel) => Some(channel.clone()),
None => None,
};
local_rx_list.push(Arc::new(Mutex::new(channel.clone())));
let led_strip_configs: Vec<_> = configs
.strips
.iter()
.filter(|c| c.display_id == display_id)
.collect();
let rx = channel;
if rx.is_none() {
warn!("no channel for display_id: {}", display_id);
continue;
}
if led_strip_configs.len() == 0 {
warn!("no led strip config for display_id: {}", display_id);
continue;
}
let mut rx = rx.unwrap().to_owned();
if rx.changed().await.is_ok() {
let screenshot = rx.borrow().clone();
log::info!("screenshot updated: {:?}", display_id);
let points: Vec<_> = led_strip_configs
.iter()
.map(|config| screenshot.get_sample_points(&config))
.flatten()
.collect();
let colors_config = config::SamplePointConfig { display_id, points };
colors_configs.push(colors_config);
}
}
return AllColorConfig {
sample_point_groups: colors_configs,
mappers,
screenshot_receivers: local_rx_list,
};
}
}
pub struct AllColorConfig {
pub sample_point_groups: Vec<SamplePointConfig>,
pub mappers: Vec<config::SamplePointMapper>,
pub screenshot_receivers: Vec<Arc<Mutex<Option<watch::Receiver<Screenshot>>>>>,
}

View File

@ -130,21 +130,6 @@ async fn get_one_edge_colors(
}
}
#[tauri::command]
async fn get_all_colors(
configs: Vec<ambient_light::SamplePointConfig>,
mappers: Vec<ambient_light::SamplePointMapper>,
) -> Result<Vec<u8>, String> {
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.to_owned();
let channels = channels.read().await;
Ok(screenshot_manager
.get_all_colors(&configs, &mappers, &channels)
.await)
}
#[tauri::command]
async fn patch_led_strip_len(display_id: u32, border: Border, delta_len: i8) -> Result<(), String> {
info!(
@ -195,7 +180,6 @@ async fn main() {
get_one_edge_colors,
patch_led_strip_len,
send_colors,
get_all_colors
])
.register_uri_scheme_protocol("ambient-light", move |_app, request| {
let response = ResponseBuilder::new().header("Access-Control-Allow-Origin", "*");
@ -356,7 +340,9 @@ async fn main() {
let publisher = publisher_update_receiver.borrow().clone();
app_handle.emit_all("led_colors_changed", publisher).unwrap();
app_handle
.emit_all("led_colors_changed", publisher)
.unwrap();
}
});

View File

@ -209,6 +209,7 @@ impl ScreenshotManager {
let screenshot = take_screenshot(display_id, scale_factor);
if let Ok(screenshot) = screenshot {
tx.send(screenshot).unwrap();
log::info!("take_screenshot_loop: send success. display#{}", display_id)
} else {
warn!("take_screenshot_loop: {}", screenshot.err().unwrap());
}
@ -218,7 +219,7 @@ impl ScreenshotManager {
&self,
configs: &Vec<SamplePointConfig>,
mappers: &Vec<SamplePointMapper>,
channels: &HashMap<u32, watch::Receiver<Screenshot>>,
screenshots: &Vec<Screenshot>,
) -> Vec<u8> {
let total_leds = configs
.iter()
@ -226,17 +227,9 @@ impl ScreenshotManager {
let mut global_colors = vec![0u8; total_leds * 3];
let mut all_colors = vec![];
for config in configs {
let rx = channels.get(&config.display_id);
if rx.is_none() {
error!(
"get_all_colors: can not find display_id {}",
config.display_id
);
continue;
}
let rx = rx.unwrap();
let screenshot = rx.borrow().clone();
for (index, screenshot) in screenshots.iter().enumerate() {
let config = &configs[index];
let mut colors = screenshot.get_colors_by_sample_points(&config.points).await;
all_colors.append(&mut colors);
@ -244,11 +237,17 @@ impl ScreenshotManager {
let mut color_index = 0;
mappers.iter().for_each(|group| {
if group.end >= all_colors.len() || group.start >= all_colors.len() {
if group.end > all_colors.len() || group.start > all_colors.len() {
warn!(
"get_all_colors: group out of range. start: {}, end: {}, all_colors.len(): {}",
group.start,
group.end,
all_colors.len()
);
return;
}
}
if group.end > group.start {
for i in group.start..group.end - 1 {
for i in group.start..group.end {
let rgb = all_colors[color_index].get_rgb();
color_index += 1;
@ -257,7 +256,7 @@ impl ScreenshotManager {
global_colors[i * 3 + 2] = rgb[2];
}
} else {
for i in (group.end..group.start - 1).rev() {
for i in (group.end..group.start).rev() {
let rgb = all_colors[color_index].get_rgb();
color_index += 1;

View File

@ -138,19 +138,6 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
}
};
const pixels = createMemo(() => {
const _colors = colors();
if (_colors) {
return <For each={_colors}>{(item) => <Pixel color={item} />}</For>;
} else if (localProps.config) {
return (
<For each={new Array(localProps.config.len).fill(undefined)}>
{() => <Pixel color="transparent" />}
</For>
);
}
});
return (
<section
{...rootProps}
@ -160,7 +147,7 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
}
onWheel={onWheel}
>
{pixels()}
<For each={colors()}>{(item) => <Pixel color={item} />}</For>
</section>
);
};

View File

@ -7,6 +7,7 @@ import {
For,
JSX,
onCleanup,
untrack,
} from 'solid-js';
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
import { ledStripStore } from '../stores/led-strip.store';
@ -17,32 +18,16 @@ const SorterItem: Component<{ mapper: LedStripPixelMapper; strip: LedStripConfig
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
createEffect(() => {
let stopped = false;
const frame = () => {
const strips = ledStripStore.strips;
const totalLedCount = strips.reduce((acc, strip) => acc + strip.len, 0);
const strips = ledStripStore.strips;
const totalLedCount = strips.reduce((acc, strip) => acc + strip.len, 0);
const fullLeds = new Array(totalLedCount).fill('rgba(255,255,255,0.5)');
const fullLeds = new Array(totalLedCount).fill('rgba(255,255,255,0.5)');
for (let i = props.mapper.start, j = 0; i < props.mapper.end; i++, j++) {
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${
ledStripStore.colors[i * 3 + 1]
}, ${ledStripStore.colors[i * 3 + 2]})`;
}
setFullLeds(fullLeds);
if (!stopped) {
requestAnimationFrame(frame);
}
};
frame();
onCleanup(() => {
stopped = true;
console.timeEnd('frame');
});
for (let i = props.mapper.start, j = 0; i < props.mapper.end; i++, j++) {
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${
ledStripStore.colors[i * 3 + 1]
}, ${ledStripStore.colors[i * 3 + 2]})`;
}
setFullLeds(fullLeds);
});
return (

View File

@ -1,5 +1,4 @@
import { invoke } from '@tauri-apps/api';
import { listen } from '@tauri-apps/api/event';
import { convertFileSrc } from '@tauri-apps/api/tauri';
import {
Component,
@ -81,56 +80,45 @@ export const ScreenView: Component<ScreenViewProps> = (props) => {
}
};
// get screenshot
createEffect(() => {
let pendingCount = 0;
const unlisten = listen<{
base64_image: string;
display_id: number;
height: number;
width: number;
}>('encoded-screenshot-updated', (event) => {
let stopped = false;
const frame = async () => {
const { drawWidth, drawHeight } = drawInfo();
if (event.payload.display_id === localProps.displayId) {
const url = convertFileSrc(
`displays/${localProps.displayId}?width=${drawWidth}&height=${drawHeight}`,
'ambient-light',
);
if (pendingCount >= 1) {
return;
}
pendingCount++;
fetch(url, {
mode: 'cors',
})
.then((res) => res.body?.getReader().read())
.then((buffer) => {
if (buffer?.value) {
setImageData({
buffer: new Uint8ClampedArray(buffer?.value),
width: drawWidth,
height: drawHeight,
});
} else {
setImageData(null);
}
draw();
})
.finally(() => {
pendingCount--;
});
}
const url = convertFileSrc(
`displays/${localProps.displayId}?width=${drawWidth}&height=${drawHeight}`,
'ambient-light',
);
await fetch(url, {
mode: 'cors',
})
.then((res) => res.body?.getReader().read())
.then((buffer) => {
if (buffer?.value) {
setImageData({
buffer: new Uint8ClampedArray(buffer?.value),
width: drawWidth,
height: drawHeight,
});
} else {
setImageData(null);
}
draw();
});
};
// console.log(event.payload.display_id, localProps.displayId);
});
subscribeScreenshotUpdate(localProps.displayId);
(async () => {
while (!stopped) {
await frame();
}
})();
onCleanup(() => {
unlisten.then((unlisten) => {
unlisten();
});
stopped = true;
});
});
// resize
createEffect(() => {
let resizeObserver: ResizeObserver;