use std::fs;
use std::sync::mpsc::Sender;
pub enum Msg {
SetAlpha(u8),
SetR(u8),
SetG(u8),
SetB(u8),
Fade { target: u8, duration_ms: u64 },
}
pub fn run(dir: &str, tx: Sender<Msg>) {
use inotify::{Inotify, WatchMask};
if let Ok(c) = fs::read_to_string(format!("{}/alpha", dir)) {
if let Ok(v) = c.trim().parse::<u8>() {
tx.send(Msg::SetAlpha(v)).ok();
}
}
if let Ok(c) = fs::read_to_string(format!("{}/r", dir)) {
if let Ok(v) = c.trim().parse::<u8>() {
tx.send(Msg::SetR(v)).ok();
}
}
if let Ok(c) = fs::read_to_string(format!("{}/g", dir)) {
if let Ok(v) = c.trim().parse::<u8>() {
tx.send(Msg::SetG(v)).ok();
}
}
if let Ok(c) = fs::read_to_string(format!("{}/b", dir)) {
if let Ok(v) = c.trim().parse::<u8>() {
tx.send(Msg::SetB(v)).ok();
}
}
let mut inotify = Inotify::init().expect("inotify init");
match inotify.watches().add(dir, WatchMask::CLOSE_WRITE) {
Ok(_) => {}
Err(e) => {
eprintln!("[scrim] inotify 失败: {}", e);
return;
}
}
let mut buf = [0u8; 4096];
loop {
let events = match inotify.read_events_blocking(&mut buf) {
Ok(e) => e,
Err(_) => continue,
};
for event in events {
let name = match &event.name {
Some(n) => n.to_string_lossy().to_string(),
None => continue,
};
let path = format!("{}/{}", dir, name);
let content = match fs::read_to_string(&path) {
Ok(c) => c.trim().to_string(),
Err(_) => continue,
};
match name.as_str() {
"alpha" => {
if let Ok(v) = content.parse::<u8>() {
tx.send(Msg::SetAlpha(v)).ok();
}
}
"r" => {
if let Ok(v) = content.parse::<u8>() {
tx.send(Msg::SetR(v)).ok();
}
}
"g" => {
if let Ok(v) = content.parse::<u8>() {
tx.send(Msg::SetG(v)).ok();
}
}
"b" => {
if let Ok(v) = content.parse::<u8>() {
tx.send(Msg::SetB(v)).ok();
}
}
"fade" => {
let parts: Vec<&str> = content.split_whitespace().collect();
if parts.len() >= 2 {
if let (Ok(target), Ok(dur)) =
(parts[0].parse::<u8>(), parts[1].parse::<u64>())
{
tx.send(Msg::Fade { target, duration_ms: dur }).ok();
}
}
}
_ => {}
}
}
}
}