提交 507a8563 作者: 方治民

feat: 新增移动磁盘(含 U 盘)插拔的监控示例

上级 ae7d6d61
...@@ -20,6 +20,8 @@ serde = { version = "1.0", features = ["derive"] } ...@@ -20,6 +20,8 @@ serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.2.0", features = [] } tauri = { version = "1.2.0", features = [] }
rusb = "0.9" rusb = "0.9"
sysinfo = "0.26.7" sysinfo = "0.26.7"
tokio = { version = "1.21", features = ["full"] }
chrono = { version = "0.4.23", features = ["serde", "rustc-serialize"] }
[features] [features]
# by default Tauri runs in production mode # by default Tauri runs in production mode
......
...@@ -3,15 +3,88 @@ ...@@ -3,15 +3,88 @@
windows_subsystem = "windows" windows_subsystem = "windows"
)] )]
// 标准库
use std::collections::BTreeMap;
use std::process::Command;
// 系统信息库
use sysinfo::{DiskExt, System, SystemExt}; use sysinfo::{DiskExt, System, SystemExt};
// 异步编程库: https://github.com/tokio-rs/tokio
use tokio::time::{self, Duration};
// 时间函数库: https://github.com/chronotope/chrono
// use chrono::prelude::*;
// JSON 序列化库
// use serde::{Deserialize, Serialize};
fn main() { fn find() -> BTreeMap<String, String> {
let s = System::new_all(); let system = System::new_all();
for disk in s.disks() { let mut devices: BTreeMap<String, String> = BTreeMap::new();
println!("{:?}: {:?}", disk.name(), disk.type_()); for disk in system.disks() {
let point = disk
.mount_point()
.to_str()
.map(str::to_string)
.clone()
.unwrap();
let name = disk.name().to_str().map(str::to_string).clone().unwrap();
devices.insert(point, name);
}
return devices;
}
async fn loop_find(mut devices: BTreeMap<String, String>) {
let mut interval = time::interval(Duration::from_millis(500));
println!("");
println!("===========================================");
println!("{:?}", devices);
println!("===========================================");
println!("");
loop {
interval.tick().await;
let latest_devices = find();
let size = devices.len();
let latest_size = latest_devices.len();
if size != latest_size {
for (k, v) in &latest_devices {
if !devices.contains_key(k) {
println!("attach: {:?}, {:?}", v, k);
// 打开文件夹
Command::new("EXPLORER").arg(k).spawn().unwrap();
}
}
for (k, v) in &devices {
if !latest_devices.contains_key(k) {
println!("detach: {:?}, {:?}", v, k);
}
}
devices = latest_devices;
}
} }
}
fn main() {
tauri::Builder::default() tauri::Builder::default()
.setup(|_app| {
// let app_handle = app.handle();
let devices = find();
tauri::async_runtime::spawn(async move {
// A loop that takes output from the async process and sends it
// to the webview via a Tauri Event
loop_find(devices).await
});
Ok(())
})
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论