feat: 后端发布未映射排序的色彩。

This commit is contained in:
Ivan Li 2023-04-02 14:52:08 +08:00
parent 9ec030488a
commit 535f731770
6 changed files with 102 additions and 43 deletions

View File

@ -1,6 +1,6 @@
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use paris::warn; use paris::{info, warn};
use tauri::async_runtime::{Mutex, RwLock}; use tauri::async_runtime::{Mutex, RwLock};
use tokio::{sync::watch, time::sleep}; use tokio::{sync::watch, time::sleep};
@ -8,7 +8,7 @@ use crate::{
ambient_light::{config, ConfigManager}, ambient_light::{config, ConfigManager},
rpc::MqttRpc, rpc::MqttRpc,
screenshot::Screenshot, screenshot::Screenshot,
screenshot_manager::ScreenshotManager, screenshot_manager::ScreenshotManager, led_color::LedColor,
}; };
use itertools::Itertools; use itertools::Itertools;
@ -16,8 +16,10 @@ use itertools::Itertools;
use super::{LedStripConfigGroup, SamplePointConfig}; use super::{LedStripConfigGroup, SamplePointConfig};
pub struct LedColorsPublisher { pub struct LedColorsPublisher {
rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>, sorted_colors_rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
tx: Arc<RwLock<watch::Sender<Vec<u8>>>>, sorted_colors_tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
colors_rx: Arc<RwLock<watch::Receiver<Vec<LedColor>>>>,
colors_tx: Arc<RwLock<watch::Sender<Vec<LedColor>>>>,
} }
impl LedColorsPublisher { impl LedColorsPublisher {
@ -25,26 +27,29 @@ impl LedColorsPublisher {
static LED_COLORS_PUBLISHER_GLOBAL: tokio::sync::OnceCell<LedColorsPublisher> = static LED_COLORS_PUBLISHER_GLOBAL: tokio::sync::OnceCell<LedColorsPublisher> =
tokio::sync::OnceCell::const_new(); tokio::sync::OnceCell::const_new();
let (sorted_tx, sorted_rx) = watch::channel(Vec::new());
let (tx, rx) = watch::channel(Vec::new()); let (tx, rx) = watch::channel(Vec::new());
LED_COLORS_PUBLISHER_GLOBAL LED_COLORS_PUBLISHER_GLOBAL
.get_or_init(|| async { .get_or_init(|| async {
LedColorsPublisher { LedColorsPublisher {
rx: Arc::new(RwLock::new(rx)), sorted_colors_rx: Arc::new(RwLock::new(sorted_rx)),
tx: Arc::new(RwLock::new(tx)), sorted_colors_tx: Arc::new(RwLock::new(sorted_tx)),
colors_rx: Arc::new(RwLock::new(rx)),
colors_tx: Arc::new(RwLock::new(tx)),
} }
}) })
.await .await
} }
pub fn start(&self) { pub fn start(&self) {
let tx = self.tx.clone(); let sorted_colors_tx = self.sorted_colors_tx.clone();
let colors_tx = self.colors_tx.clone();
tokio::spawn(async move { tokio::spawn(async move {
loop { loop {
log::info!("colors update loop AAA"); let sorted_colors_tx = sorted_colors_tx.write().await;
let colors_tx = colors_tx.write().await;
let tx = tx.write().await;
let screenshot_manager = ScreenshotManager::global().await; let screenshot_manager = ScreenshotManager::global().await;
let config_manager = ConfigManager::global().await; let config_manager = ConfigManager::global().await;
@ -79,13 +84,13 @@ impl LedColorsPublisher {
} }
let colors = screenshot_manager let colors = screenshot_manager
.get_all_colors( .get_all_colors(&configs.sample_point_groups, &screenshots)
&configs.sample_point_groups,
&configs.mappers,
&screenshots,
)
.await; .await;
match tx.send(colors) {
let sorted_colors =
ScreenshotManager::get_sorted_colors(&colors, &configs.mappers).await;
match colors_tx.send(colors) {
Ok(_) => { Ok(_) => {
// log::info!("colors updated"); // log::info!("colors updated");
} }
@ -94,17 +99,31 @@ impl LedColorsPublisher {
} }
} }
if some_screenshot_receiver_is_none match sorted_colors_tx.send(sorted_colors) {
|| config_receiver.has_changed().unwrap_or(true) Ok(_) => {
{ // log::info!("colors updated");
}
Err(_) => {
warn!("colors update failed");
}
}
if some_screenshot_receiver_is_none {
info!("some screenshot receiver is none. reload.");
sleep(Duration::from_millis(1000)).await; sleep(Duration::from_millis(1000)).await;
break; break;
} }
if config_receiver.has_changed().unwrap_or(true) {
info!("config changed. reload.");
sleep(Duration::from_millis(100)).await;
break;
}
} }
} }
}); });
let rx = self.rx.clone(); let rx = self.sorted_colors_rx.clone();
tokio::spawn(async move { tokio::spawn(async move {
let mut rx = rx.read().await.clone(); let mut rx = rx.read().await.clone();
loop { loop {
@ -136,8 +155,8 @@ impl LedColorsPublisher {
mqtt.publish_led_sub_pixels(payload).await mqtt.publish_led_sub_pixels(payload).await
} }
pub async fn clone_receiver(&self) -> watch::Receiver<Vec<u8>> { pub async fn clone_sorted_colors_receiver(&self) -> watch::Receiver<Vec<u8>> {
self.rx.read().await.clone() self.sorted_colors_rx.read().await.clone()
} }
pub async fn get_colors_configs(configs: &LedStripConfigGroup) -> AllColorConfig { pub async fn get_colors_configs(configs: &LedStripConfigGroup) -> AllColorConfig {
@ -207,6 +226,10 @@ impl LedColorsPublisher {
screenshot_receivers: local_rx_list, screenshot_receivers: local_rx_list,
}; };
} }
pub async fn clone_colors_receiver(&self) -> watch::Receiver<Vec<LedColor>> {
self.colors_rx.read().await.clone()
}
} }
pub struct AllColorConfig { pub struct AllColorConfig {

View File

@ -348,7 +348,24 @@ async fn main() {
let app_handle = app.handle().clone(); let app_handle = app.handle().clone();
tokio::spawn(async move { tokio::spawn(async move {
let publisher = ambient_light::LedColorsPublisher::global().await; let publisher = ambient_light::LedColorsPublisher::global().await;
let mut publisher_update_receiver = publisher.clone_receiver().await; let mut publisher_update_receiver = publisher.clone_sorted_colors_receiver().await;
loop {
if let Err(err) = publisher_update_receiver.changed().await {
error!("publisher update receiver changed error: {}", err);
return;
}
let publisher = publisher_update_receiver.borrow().clone();
app_handle
.emit_all("led_sorted_colors_changed", publisher)
.unwrap();
}
});
let app_handle = app.handle().clone();
tokio::spawn(async move {
let publisher = ambient_light::LedColorsPublisher::global().await;
let mut publisher_update_receiver = publisher.clone_colors_receiver().await;
loop { loop {
if let Err(err) = publisher_update_receiver.changed().await { if let Err(err) = publisher_update_receiver.changed().await {
error!("publisher update receiver changed error: {}", err); error!("publisher update receiver changed error: {}", err);

View File

@ -10,7 +10,7 @@ use tokio::sync::{watch, OnceCell};
use crate::{ use crate::{
ambient_light::{SamplePointConfig, SamplePointMapper}, ambient_light::{SamplePointConfig, SamplePointMapper},
screenshot::{LedSamplePoints, ScreenSamplePoints, Screenshot, ScreenshotPayload}, screenshot::{LedSamplePoints, ScreenSamplePoints, Screenshot, ScreenshotPayload}, led_color::LedColor,
}; };
pub fn take_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> { pub fn take_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> {
@ -218,14 +218,9 @@ impl ScreenshotManager {
pub async fn get_all_colors( pub async fn get_all_colors(
&self, &self,
configs: &Vec<SamplePointConfig>, configs: &Vec<SamplePointConfig>,
mappers: &Vec<SamplePointMapper>,
screenshots: &Vec<Screenshot>, screenshots: &Vec<Screenshot>,
) -> Vec<u8> { ) -> Vec<LedColor> {
let total_leds = configs
.iter()
.fold(0, |acc, config| acc + config.points.len());
let mut global_colors = vec![0u8; total_leds * 3];
let mut all_colors = vec![]; let mut all_colors = vec![];
for (index, screenshot) in screenshots.iter().enumerate() { for (index, screenshot) in screenshots.iter().enumerate() {
@ -235,20 +230,31 @@ impl ScreenshotManager {
all_colors.append(&mut colors); all_colors.append(&mut colors);
} }
all_colors
}
pub async fn get_sorted_colors(colors: &Vec<LedColor>, mappers: &Vec<SamplePointMapper>) -> Vec<u8> {
let total_leds = mappers
.iter()
.map(|mapper| mapper.end)
.max()
.unwrap_or(0) as usize;
let mut global_colors = vec![0u8; total_leds * 3];
let mut color_index = 0; let mut color_index = 0;
mappers.iter().for_each(|group| { mappers.iter().for_each(|group| {
if group.end > all_colors.len() || group.start > all_colors.len() { if group.end > colors.len() || group.start > colors.len() {
warn!( warn!(
"get_all_colors: group out of range. start: {}, end: {}, all_colors.len(): {}", "get_sorted_colors: group out of range. start: {}, end: {}, colors.len(): {}",
group.start, group.start,
group.end, group.end,
all_colors.len() colors.len()
); );
return; return;
} }
if group.end > group.start { if group.end > group.start {
for i in group.start..group.end { for i in group.start..group.end {
let rgb = all_colors[color_index].get_rgb(); let rgb = colors[color_index].get_rgb();
color_index += 1; color_index += 1;
global_colors[i * 3] = rgb[0]; global_colors[i * 3] = rgb[0];
@ -257,7 +263,7 @@ impl ScreenshotManager {
} }
} else { } else {
for i in (group.end..group.start).rev() { for i in (group.end..group.start).rev() {
let rgb = all_colors[color_index].get_rgb(); let rgb = colors[color_index].get_rgb();
color_index += 1; color_index += 1;
global_colors[i * 3] = rgb[0]; global_colors[i * 3] = rgb[0];

View File

@ -57,6 +57,21 @@ function App() {
}); });
}); });
// listen to led_sorted_colors_changed event
createEffect(() => {
const unlisten = listen<Array<string>>('led_sorted_colors_changed', (event) => {
const sortedColors = event.payload;
setLedStripStore({
sortedColors,
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
const [ledStripConfiguration, setLedStripConfiguration] = createStore< const [ledStripConfiguration, setLedStripConfiguration] = createStore<
LedStripConfigurationContextType[0] LedStripConfigurationContextType[0]
>({ >({

View File

@ -88,9 +88,7 @@ const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper
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++) { for (let i = props.mapper.start, j = 0; i < props.mapper.end; i++, j++) {
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${ fullLeds[i] = ledStripStore.colors[j];
ledStripStore.colors[i * 3 + 1]
}, ${ledStripStore.colors[i * 3 + 2]})`;
} }
setFullLeds(fullLeds); setFullLeds(fullLeds);
}); });
@ -131,15 +129,14 @@ const SorterResult: Component = () => {
const [fullLeds, setFullLeds] = createSignal<string[]>([]); const [fullLeds, setFullLeds] = createSignal<string[]>([]);
createEffect(() => { createEffect(() => {
const strips = ledStripStore.strips; const totalLedCount = Math.max(0, ...ledStripStore.mappers.map((m) => m.end));
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)');
ledStripStore.mappers.forEach((mapper) => { ledStripStore.mappers.forEach((mapper) => {
for (let i = mapper.start, j = 0; i < mapper.end; i++, j++) { for (let i = mapper.start, j = 0; i < mapper.end; i++, j++) {
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${ fullLeds[i] = `rgb(${ledStripStore.sortedColors[i * 3]}, ${
ledStripStore.colors[i * 3 + 1] ledStripStore.sortedColors[i * 3 + 1]
}, ${ledStripStore.colors[i * 3 + 2]})`; }, ${ledStripStore.sortedColors[i * 3 + 2]})`;
} }
}); });
setFullLeds(fullLeds); setFullLeds(fullLeds);

View File

@ -7,4 +7,5 @@ export const [ledStripStore, setLedStripStore] = createStore({
strips: new Array<LedStripConfig>(), strips: new Array<LedStripConfig>(),
mappers: new Array<LedStripPixelMapper>(), mappers: new Array<LedStripPixelMapper>(),
colors: new Uint8ClampedArray(), colors: new Uint8ClampedArray(),
sortedColors: new Array<string>(),
}); });