feat: 支持收取来自板子要求的显示器亮度和电脑音量。

This commit is contained in:
Ivan Li 2023-05-06 20:14:31 +08:00
parent 9b863508e4
commit 091bcf33da

View File

@ -1,21 +1,23 @@
use std::time::Duration; use std::{sync::Arc, time::Duration};
use paris::{info, warn}; use paris::{info, warn, error};
use tokio::{net::UdpSocket, sync::RwLock, time::timeout}; use tokio::{net::UdpSocket, sync::RwLock, time::timeout, io};
use super::{BoardConnectStatus, BoardInfo}; use super::{BoardConnectStatus, BoardInfo};
#[derive(Debug)] #[derive(Debug)]
pub struct Board { pub struct Board {
pub info: RwLock<BoardInfo>, pub info: Arc<RwLock<BoardInfo>>,
socket: Option<UdpSocket>, socket: Option<Arc<UdpSocket>>,
listen_handler: Option<tokio::task::JoinHandle<()>>,
} }
impl Board { impl Board {
pub fn new(info: BoardInfo) -> Self { pub fn new(info: BoardInfo) -> Self {
Self { Self {
info: RwLock::new(info), info: Arc::new(RwLock::new(info)),
socket: None, socket: None,
listen_handler: None,
} }
} }
@ -24,7 +26,33 @@ impl Board {
let socket = UdpSocket::bind("0.0.0.0:0").await?; let socket = UdpSocket::bind("0.0.0.0:0").await?;
socket.connect((info.address, info.port)).await?; socket.connect((info.address, info.port)).await?;
self.socket = Some(socket); let socket = Arc::new(socket);
self.socket = Some(socket.clone());
let info = self.info.clone();
let handler=tokio::spawn(async move {
let mut buf = [0u8; 128];
if let Err(err) = socket.readable().await {
error!("socket read error: {:?}", err);
return;
}
loop {
match socket.try_recv(&mut buf) {
Ok(len) => {
log::info!("recv: {:?}", &buf[..len]);
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
error!("socket recv error: {:?}", e);
break;
}
}
}
});
self.listen_handler = Some(handler);
Ok(()) Ok(())
} }
@ -37,10 +65,7 @@ impl Board {
let socket = self.socket.as_ref().unwrap(); let socket = self.socket.as_ref().unwrap();
socket socket.send(buf).await.unwrap();
.send(buf)
.await
.unwrap();
} }
pub async fn check(&self) -> anyhow::Result<()> { pub async fn check(&self) -> anyhow::Result<()> {
@ -99,3 +124,16 @@ impl Board {
Ok(()) Ok(())
} }
} }
impl Drop for Board {
fn drop(&mut self) {
if let Some(handler) = self.listen_handler.take() {
info!("aborting listen handler");
tokio::task::block_in_place(move || {
handler.abort();
});
info!("listen handler aborted");
}
}
}