feat: 刷机程序按型号配置工作并在 devinfo 记录芯片号

This commit is contained in:
2026-11-27 18:16:11 +08:00
parent 981998b654
commit d94ddc36b1
6 changed files with 1209 additions and 102 deletions
+629 -50
View File
@@ -5,9 +5,16 @@ use fltk::button::{Button, CheckButton};
use fltk::enums::{Align, Color, Event, Font, FrameType, LabelType, Shortcut};
use fltk::table::{TableContext, TableRow, TableRowSelectFlag, TableRowSelectMode};
use fltk::frame::Frame;
use fltk::group::{Group, Tabs};
use fltk::menu::{CMenuItem, MenuFlag, MenuItem};
use fltk::misc::InputChoice;
use fltk::prelude::*;
use fltk::window::Window;
mod adb;
mod profile;
use profile::{chip_matches, display, load_all, remember, remembered, Profile};
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
@@ -19,10 +26,12 @@ use std::thread;
use std::time::{Duration, Instant};
const COLUMNS: [&str; 7] = ["", "序列号", "芯片型号", "端口", "硬盘", "状态", "进度"];
const ADB_COLUMNS: [&str; 8] = ["序列号", "芯片型号", "端口", "CPU", "内存", "硬盘", "系统版本", "标记"];
const DONE: &str = "写入完成,设备正在重启进入系统";
const WAIT: &str = "请拔出设备后重新按复位键接入电脑";
const INSTALLING_DRIVER: &str = "正在安装驱动,请稍后";
const UNPLUGGED: &str = "设备已拔出,操作失败";
const MISMATCH: &str = "不是所选型号";
const CREATE_NO_WINDOW: u32 = 0x08000000;
fn command(program: impl AsRef<std::ffi::OsStr>) -> Command {
@@ -56,6 +65,7 @@ struct Device {
present: bool,
checked: bool,
info_done: bool,
mismatch: bool,
missing_scans: u8,
}
@@ -75,6 +85,7 @@ enum EventMsg {
struct WorkerOut {
serial: String,
disk: String,
chip: String,
}
struct Job {
@@ -83,6 +94,26 @@ struct Job {
resume: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ClaimStage {
Wait,
Marking,
Confirm,
}
#[derive(Clone)]
struct Claim {
location: String,
chip_serial: String,
model_id: String,
boot_host: String,
boot_model: String,
seen: Vec<String>,
stage: ClaimStage,
since: Instant,
token: String,
}
fn app_dir() -> PathBuf {
if let Ok(exe) = std::env::current_exe() {
let mut dir = exe.parent().map(|path| path.to_path_buf());
@@ -152,9 +183,10 @@ fn task_running(dev: &Device) -> bool {
|| dev.status.starts_with("正在写回")
}
fn scan_9008() -> Result<Vec<(String, String, String, String)>, String> {
fn scan_ports(vid: &str, pid: &str) -> Result<Vec<(String, String, String, String)>, String> {
let script = r#"
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match 'VID_05C6&PID_9008' } | ForEach-Object {
$pattern = "VID_$($env:FLASHER_VID)&PID_$($env:FLASHER_PID)"
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match ([regex]::Escape($pattern)) } | ForEach-Object {
$loc = ''
$svc = ''
$usb = ''
@@ -181,6 +213,8 @@ Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match 'VID_05C6&PID_9
"#;
let output = command("powershell")
.args(["-NoProfile", "-Command", script])
.env("FLASHER_VID", vid)
.env("FLASHER_PID", pid)
.output()
.map_err(|err| err.to_string())?;
if !output.status.success() && output.stdout.is_empty() {
@@ -203,8 +237,8 @@ Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match 'VID_05C6&PID_9
.collect())
}
fn confirm_port(location: &str) -> Result<(), String> {
match scan_9008() {
fn confirm_port(location: &str, vid: &str, pid: &str) -> Result<(), String> {
match scan_ports(vid, pid) {
Ok(found) if found.iter().any(|(loc, _, _, _)| loc == location) => Ok(()),
Ok(_) => Err("设备已拔出".into()),
Err(_) => Ok(()),
@@ -231,8 +265,8 @@ fn run_powershell(args: &[String]) -> Result<Vec<String>, String> {
fn driver_message(kind: &str, extra: &str) -> String {
match kind {
"READY" => "驱动:9008 已就绪".into(),
"INSTALLED" => "驱动:9008 已安装".into(),
"READY" => "驱动:已就绪".into(),
"INSTALLED" => "驱动:已安装".into(),
"MISSING" => "驱动:未安装".into(),
"FAIL" if extra == "cancel" => "驱动:安装被取消".into(),
"FAIL" if extra.is_empty() => "驱动:安装失败".into(),
@@ -248,9 +282,9 @@ fn driver_text(lines: &[String]) -> Option<(String, String)> {
Some((parts.next().unwrap_or("").to_string(), parts.next().unwrap_or("").to_string()))
}
fn ensure_driver(tx: mpsc::Sender<EventMsg>) {
fn ensure_driver(tx: mpsc::Sender<EventMsg>, driver_dir: PathBuf) {
let _ = tx.send(EventMsg::Driver("驱动:正在检查".into()));
let script = app_dir().join("drivers").join("ensure-driver.ps1");
let script = driver_dir.join("ensure-driver.ps1");
let script = script.to_string_lossy().to_string();
let checked = run_powershell(&[
"-NoProfile".into(),
@@ -268,7 +302,7 @@ fn ensure_driver(tx: mpsc::Sender<EventMsg>) {
return;
};
if kind == "READY" {
let _ = tx.send(EventMsg::Driver("驱动:9008 已就绪".into()));
let _ = tx.send(EventMsg::Driver("驱动:已就绪".into()));
return;
}
if kind != "MISSING" {
@@ -334,6 +368,7 @@ fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender<EventMsg>, loca
let _ = tx.send(EventMsg::Serial(location.to_string(), value));
}
"CHIP" => {
out.chip = value.clone();
let _ = tx.send(EventMsg::Chip(location.to_string(), value));
}
"DISK" => {
@@ -365,7 +400,18 @@ fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender<EventMsg>, loca
Ok(())
}
fn run_worker(_port: &str, args: &[&str], tx: &mpsc::Sender<EventMsg>, location: &str) -> Result<WorkerOut, String> {
fn profile_args(profile: &Profile, args: &[&str]) -> Vec<String> {
let mut out = Vec::new();
if let Some(cmd) = args.first() {
out.push((*cmd).to_string());
out.push("--profile".into());
out.push(profile.conf_path.display().to_string());
out.extend(args.iter().skip(1).map(|arg| (*arg).to_string()));
}
out
}
fn run_worker(args: &[String], tx: &mpsc::Sender<EventMsg>, location: &str) -> Result<WorkerOut, String> {
let mut child = command(python())
.arg(worker_script())
.args(args)
@@ -385,14 +431,14 @@ fn run_worker(_port: &str, args: &[&str], tx: &mpsc::Sender<EventMsg>, location:
}
}
});
let limit = if args.iter().any(|arg| *arg == "--full") {
let limit = if args.iter().any(|arg| arg == "--full") {
Duration::from_secs(45 * 60)
} else if args.first() == Some(&"flash") {
} else if args.first().map(String::as_str) == Some("flash") {
Duration::from_secs(20 * 60)
} else {
Duration::from_secs(90)
};
let mut out = WorkerOut { serial: String::new(), disk: String::new() };
let mut out = WorkerOut { serial: String::new(), disk: String::new(), chip: String::new() };
let mut last = Instant::now();
loop {
match line_rx.recv_timeout(Duration::from_secs(1)) {
@@ -434,21 +480,29 @@ fn run_worker(_port: &str, args: &[&str], tx: &mpsc::Sender<EventMsg>, location:
}
}
fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full: bool, parts: bool, resume: bool, tx: &mpsc::Sender<EventMsg>) -> Result<&'static str, String> {
confirm_port(location)?;
fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full: bool, parts: bool, resume: bool, profile: &Profile, tx: &mpsc::Sender<EventMsg>) -> Result<&'static str, String> {
confirm_port(location, &profile.vid, &profile.pid)?;
let _ = tx.send(EventMsg::Status(location.to_string(), "正在识别".into()));
let info = run_worker(port, &["info", "--port", port], tx, location)?;
let info = run_worker(&profile_args(profile, &["info", "--port", port]), tx, location)?;
if resume && !known_serial.is_empty() && !info.serial.is_empty() && info.serial != known_serial {
return Err("插回的不是原来的芯片,已停止原来的任务".into());
}
if kind == JobKind::Info {
return Ok("info");
}
if !chip_matches(&info.chip, &profile.chip) {
return Err(if info.chip.is_empty() { "未能确认芯片型号".into() } else { MISMATCH.into() });
}
let chip_serial = if !info.serial.is_empty() {
info.serial.clone()
} else {
known_serial.to_string()
};
let backup_efs = kind == JobKind::Backup || parts;
let do_backup = backup_efs || full;
let mut restore_dir = String::new();
if do_backup {
confirm_port(location)?;
confirm_port(location, &profile.vid, &profile.pid)?;
let serial = if !info.serial.is_empty() {
info.serial
} else if !known_serial.is_empty() {
@@ -468,7 +522,7 @@ fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full:
}
let status = if full && !backup_efs { "正在备份整盘" } else { "备份中" };
let _ = tx.send(EventMsg::Status(location.to_string(), status.into()));
run_worker(port, &backup_args, tx, location)?;
run_worker(&profile_args(profile, &backup_args), tx, location)?;
if kind == JobKind::Backup {
return Ok("backup");
}
@@ -476,23 +530,61 @@ fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full:
restore_dir = dest;
}
}
confirm_port(location)?;
confirm_port(location, &profile.vid, &profile.pid)?;
let _ = tx.send(EventMsg::Status(location.to_string(), "写入中".into()));
let _ = tx.send(EventMsg::Progress(location.to_string(), 0));
if restore_dir.is_empty() {
run_worker(port, &["flash", "--port", port], tx, location)?;
} else {
run_worker(port, &["flash", "--port", port, "--dest", restore_dir.as_str()], tx, location)?;
let mut flash_args = vec!["flash", "--port", port, "--chip", chip_serial.as_str()];
if !restore_dir.is_empty() {
flash_args.push("--dest");
flash_args.push(restore_dir.as_str());
}
run_worker(&profile_args(profile, &flash_args), tx, location)?;
Ok("flash")
}
fn can_operate(dev: &Device) -> bool {
dev.info_done && !dev.mismatch && !dev.chip.is_empty() && !task_running(dev)
}
fn fill_models(choice: &mut InputChoice, profiles: &[Profile], query: &str) {
choice.clear();
let query = query.trim().to_lowercase();
for profile in profiles {
let line = display(profile);
if query.is_empty() || line.to_lowercase().contains(&query) {
choice.add(&line);
}
}
}
fn main() {
let root = app_dir();
let profiles = load_all(&root).unwrap_or_else(|err| {
eprintln!("{err}");
Vec::new()
});
if profiles.is_empty() {
let app = app::App::default();
let mut window = Window::default().with_size(480, 120).with_label("Flasher");
let mut frame = Frame::default().with_size(460, 80).with_pos(10, 20).with_label("没有找到型号配置");
frame.set_label_size(16);
window.end();
window.show();
app.run().unwrap();
return;
}
let selected_index = remembered(&root, &profiles);
let selected = Arc::new(Mutex::new(profiles[selected_index].clone()));
let devices = Arc::new(Mutex::new(Vec::<Device>::new()));
let adb_devices = Arc::new(Mutex::new(Vec::<adb::AdbDevice>::new()));
let adb_refresh = Arc::new(AtomicBool::new(true));
let claims = Arc::new(Mutex::new(Vec::<Claim>::new()));
let (adb_tx, adb_rx) = mpsc::channel::<Vec<adb::AdbDevice>>();
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::new(Mutex::new(VecDeque::new()));
let full_disk = Arc::new(Mutex::new(false));
let backup_parts = Arc::new(Mutex::new(true));
let refresh_now = Arc::new(AtomicBool::new(false));
let model_guard = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel::<EventMsg>();
let (scan_tx, scan_rx) = mpsc::channel::<(Option<Vec<(String, String, String, String)>>, bool)>();
@@ -502,6 +594,7 @@ fn main() {
let full_disk = Arc::clone(&full_disk);
let backup_parts = Arc::clone(&backup_parts);
let tx = tx.clone();
let selected = Arc::clone(&selected);
thread::spawn(move || loop {
let next = queue.lock().unwrap().pop_front();
let Some(Job { location, kind, resume }) = next else {
@@ -525,7 +618,8 @@ fn main() {
}
}
};
if confirm_port(&location).is_err() {
let profile = selected.lock().unwrap().clone();
if confirm_port(&location, &profile.vid, &profile.pid).is_err() {
let _ = tx.send(EventMsg::Failed(location, "设备已拔出".into()));
continue;
}
@@ -545,12 +639,12 @@ fn main() {
}
let full = *full_disk.lock().unwrap();
let parts = *backup_parts.lock().unwrap();
match execute(&location, &port, &serial, kind, full, parts, resume, &tx) {
match execute(&location, &port, &serial, kind, full, parts, resume, &profile, &tx) {
Ok(done) => {
let _ = tx.send(EventMsg::Finished(location, done));
}
Err(err) => {
let unplugged = err == "设备已拔出" || confirm_port(&location).is_err();
let unplugged = err == "设备已拔出" || confirm_port(&location, &profile.vid, &profile.pid).is_err();
let still_there = devices
.lock()
.unwrap()
@@ -576,10 +670,20 @@ fn main() {
if let Ok(font) = Font::load_font("C:/Windows/Fonts/msyh.ttc") {
Font::set_font(Font::Helvetica, &font);
}
let mut window = Window::default().with_size(980, 640).with_label("UFI003_MB_V02 Flasher");
let initial = selected.lock().unwrap().clone();
let mut window = Window::default()
.with_size(980, 640)
.with_label(&format!("{} Flasher", initial.id));
let mut model_label = Frame::default().with_pos(16, 14).with_size(48, 32).with_label("型号");
model_label.set_label_size(15);
model_label.set_align(Align::Left | Align::Inside);
let mut model_choice = InputChoice::new(64, 12, 340, 32, "");
model_choice.set_text_size(15);
fill_models(&mut model_choice, &profiles, "");
model_choice.set_value(&display(&initial));
let mut driver_label = Frame::default()
.with_pos(16, 16)
.with_size(800, 28)
.with_pos(416, 16)
.with_size(400, 28)
.with_label("驱动:正在检查");
driver_label.set_label_size(15);
driver_label.set_align(Align::Left | Align::Inside);
@@ -588,7 +692,16 @@ fn main() {
.with_size(128, 32)
.with_label("刷新设备");
refresh_btn.set_label_size(15);
let mut table = TableRow::new(16, 56, 948, 492, "");
let mut tabs = Tabs::new(8, 52, 964, 576, "");
let mut page_edl = Group::new(8, 52, 964, 576, "9008设备");
page_edl.set_label_size(15);
let mut hint = Frame::default()
.with_pos(16, 500)
.with_size(460, 56)
.with_label(&initial.hint);
hint.set_label_size(15);
hint.set_align(Align::Left | Align::Inside | Align::Wrap);
let mut table = TableRow::new(16, 88, 948, 400, "");
table.set_cols(COLUMNS.len() as i32);
table.set_rows(0);
table.set_col_header(true);
@@ -643,31 +756,151 @@ fn main() {
_ => {}
}
});
let mut hint = Frame::default()
.with_pos(16, 560)
.with_size(460, 60)
.with_label("设备请按住复位键然后插入电脑,列表只显示9008设备。");
hint.set_label_size(15);
hint.set_align(Align::Left | Align::Inside | Align::Wrap);
let mut parts = CheckButton::default()
.with_pos(490, 560)
.with_pos(490, 496)
.with_size(300, 28)
.with_label("刷机前备份基带四分区");
parts.set_label_size(15);
parts.set_value(true);
let mut full = CheckButton::default()
.with_pos(490, 592)
.with_pos(490, 528)
.with_size(300, 28)
.with_label("同时备份整盘 eMMC");
full.set_label_size(15);
let mut batch_btn = Button::default()
.with_pos(804, 560)
.with_pos(804, 496)
.with_size(160, 60)
.with_label("批量刷机");
batch_btn.set_label_size(15);
batch_btn.deactivate();
page_edl.end();
let mut page_adb = Group::new(8, 52, 964, 576, "ADB设备");
page_adb.set_label_size(15);
let mut adb_table = TableRow::new(16, 88, 948, 520, "");
adb_table.set_cols(ADB_COLUMNS.len() as i32);
adb_table.set_rows(0);
adb_table.set_col_header(true);
adb_table.set_col_header_height(28);
adb_table.set_row_header(false);
adb_table.set_row_height_all(28);
adb_table.set_col_resize(true);
adb_table.set_col_resize_min(48);
adb_table.set_type(TableRowSelectMode::Single);
for (index, width) in [130, 100, 180, 52, 80, 90, 196, 90].into_iter().enumerate() {
adb_table.set_col_width(index as i32, width);
}
adb_table.end();
let adb_draw = Arc::clone(&adb_devices);
adb_table.draw_cell(move |table, ctx, row, col, x, y, w, h| {
match ctx {
TableContext::ColHeader => {
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::ThinUpBox, x, y, w, h, Color::FrameDefault);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
fltk::draw::set_draw_color(Color::Foreground);
fltk::draw::set_font(Font::Helvetica, 15);
let title = ADB_COLUMNS.get(col as usize).copied().unwrap_or("");
fltk::draw::draw_text2(title, x, y, w, h, Align::Center);
fltk::draw::pop_clip();
}
TableContext::Cell => {
let selected = table.row_selected(row);
let background = if selected { Color::Selection } else { Color::White };
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::FlatBox, x, y, w, h, background);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
fltk::draw::set_draw_color(if selected { Color::White } else { Color::Foreground });
fltk::draw::set_font(Font::Helvetica, 15);
let text = adb_cell(&adb_draw, row, col);
fltk::draw::draw_text2(&text, x, y, w, h, Align::Center);
fltk::draw::pop_clip();
}
_ => {}
}
});
page_adb.end();
tabs.end();
// 分页标签画在容器顶部。不主动缩小子页面时,页面会盖住标签。
let (area_x, mut area_y, area_w, mut area_h) = tabs.client_area();
if area_y <= 52 {
area_y = 84;
area_h = 544;
}
page_edl.resize(area_x, area_y, area_w, area_h);
page_adb.resize(area_x, area_y, area_w, area_h);
window.end();
window.show();
{
let mut model_label = model_label.clone();
let mut model_choice = model_choice.clone();
tabs.set_callback(move |tabs| {
let on_adb = tabs.value().is_some_and(|group| group.label() == "ADB设备");
if on_adb {
model_label.hide();
model_choice.hide();
} else {
model_label.show();
model_choice.show();
}
});
}
{
let profiles = profiles.clone();
let selected = Arc::clone(&selected);
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
let refresh_now = Arc::clone(&refresh_now);
let model_guard = Arc::clone(&model_guard);
let mut window = window.clone();
let mut hint = hint.clone();
let tx = tx.clone();
let root = root.clone();
model_choice.set_callback(move |choice| {
if model_guard.load(Ordering::SeqCst) {
return;
}
let text = choice.value().unwrap_or_default();
if let Some(profile) = profiles.iter().find(|item| display(item) == text || item.id.eq_ignore_ascii_case(text.trim())).cloned() {
if profile.id == selected.lock().unwrap().id {
return;
}
if devices.lock().unwrap().iter().any(task_running) {
let current = selected.lock().unwrap().clone();
model_guard.store(true, Ordering::SeqCst);
choice.set_value(&display(&current));
model_guard.store(false, Ordering::SeqCst);
return;
}
remember(&root, &profile.id);
window.set_label(&format!("{} Flasher", profile.id));
hint.set_label(&profile.hint);
hint.redraw();
*selected.lock().unwrap() = profile.clone();
devices.lock().unwrap().clear();
queue.lock().unwrap().clear();
refresh_now.store(true, Ordering::SeqCst);
let tx = tx.clone();
let driver_dir = profile.driver_dir.clone();
thread::spawn(move || ensure_driver(tx, driver_dir));
return;
}
let query = text.trim().to_string();
if query.is_empty() {
let current = selected.lock().unwrap().clone();
model_guard.store(true, Ordering::SeqCst);
fill_models(choice, &profiles, "");
choice.set_value(&display(&current));
model_guard.store(false, Ordering::SeqCst);
return;
}
model_guard.store(true, Ordering::SeqCst);
fill_models(choice, &profiles, &query);
choice.set_value(&query);
model_guard.store(false, Ordering::SeqCst);
});
}
{
let full_disk = Arc::clone(&full_disk);
@@ -679,9 +912,11 @@ fn main() {
}
{
let refresh_now = Arc::clone(&refresh_now);
let adb_refresh = Arc::clone(&adb_refresh);
refresh_btn.set_callback(move |button| {
button.deactivate();
refresh_now.store(true, Ordering::SeqCst);
adb_refresh.store(true, Ordering::SeqCst);
});
}
{
@@ -691,9 +926,14 @@ fn main() {
}
{
let refresh_now = Arc::clone(&refresh_now);
let selected = Arc::clone(&selected);
thread::spawn(move || loop {
let manual = refresh_now.swap(false, Ordering::SeqCst);
let found = scan_9008().ok();
let (vid, pid) = {
let profile = selected.lock().unwrap();
(profile.vid.clone(), profile.pid.clone())
};
let found = scan_ports(&vid, &pid).ok();
if scan_tx.send((found, manual)).is_err() {
break;
}
@@ -707,10 +947,32 @@ fn main() {
}
});
}
{
let adb_refresh = Arc::clone(&adb_refresh);
let claims = Arc::clone(&claims);
let tx = tx.clone();
thread::spawn(move || loop {
let _manual = adb_refresh.swap(false, Ordering::SeqCst);
let found = adb::list_devices();
advance_claims(&found, &claims, &tx);
if adb_tx.send(found).is_err() {
break;
}
let mut waited = 0;
while waited < 2000 {
if adb_refresh.load(Ordering::SeqCst) {
break;
}
thread::sleep(Duration::from_millis(100));
waited += 100;
}
});
}
{
let tx = tx.clone();
thread::spawn(move || ensure_driver(tx));
let driver_dir = selected.lock().unwrap().driver_dir.clone();
thread::spawn(move || ensure_driver(tx, driver_dir));
}
table.handle({
@@ -749,11 +1011,37 @@ fn main() {
let _ = table.select_row(row, TableRowSelectFlag::Select);
let location = devices.lock().unwrap().get(row as usize).map(|dev| dev.location.clone());
let Some(location) = location else { return true };
let is_busy = devices.lock().unwrap().iter().find(|dev| dev.location == location).is_some_and(task_running);
let is_busy = devices.lock().unwrap().iter().find(|dev| dev.location == location).is_some_and(|dev| {
task_running(dev) || dev.mismatch || !dev.info_done || dev.chip.is_empty()
});
popup_menu(&queue, &devices, &location, is_busy, pointer_x, pointer_y);
true
}
});
adb_table.handle({
let adb_devices = Arc::clone(&adb_devices);
let devices = Arc::clone(&devices);
let selected = Arc::clone(&selected);
let adb_refresh = Arc::clone(&adb_refresh);
move |table, ev| {
if ev != Event::Released || app::event_button() != MouseButton::Right as i32 {
return false;
}
let (pointer_x, pointer_y) = (app::event_x(), app::event_y());
let Some((ctx, row, _, _)) = table.cursor2rowcol() else {
return false;
};
if ctx != TableContext::Cell || row < 0 {
return false;
}
let _ = table.select_row(row, TableRowSelectFlag::Select);
let Some(device) = adb_devices.lock().unwrap().get(row as usize).cloned() else {
return true;
};
adb_popup(&device, &devices, &selected, &adb_refresh, pointer_x, pointer_y);
true
}
});
app::add_timeout3(0.5, {
let devices = Arc::clone(&devices);
@@ -762,6 +1050,11 @@ fn main() {
let mut driver_label = driver_label.clone();
let mut refresh_btn = refresh_btn.clone();
let mut batch_btn = batch_btn.clone();
let mut model_choice = model_choice.clone();
let mut adb_table = adb_table.clone();
let adb_devices = Arc::clone(&adb_devices);
let claims = Arc::clone(&claims);
let selected = Arc::clone(&selected);
move |handle| {
while let Ok((found, manual)) = scan_rx.try_recv() {
let Some(found) = found else {
@@ -774,7 +1067,8 @@ fn main() {
if manual {
let alive = {
let mut list = devices.lock().unwrap();
list.retain(|dev| dev.present);
let claimed = claims.lock().unwrap().iter().map(|claim| claim.location.clone()).collect::<Vec<_>>();
list.retain(|dev| dev.present || claimed.iter().any(|location| location == &dev.location));
for dev in list.iter_mut() {
let retry = dev.serial.is_empty()
&& (dev.status.starts_with("失败")
@@ -791,17 +1085,36 @@ fn main() {
refresh_btn.activate();
}
}
while let Ok(found) = adb_rx.try_recv() {
*adb_devices.lock().unwrap() = found;
refresh_adb_table(&mut adb_table, &adb_devices);
refresh_btn.activate();
}
while let Ok(msg) = rx.try_recv() {
if let EventMsg::Driver(text) = msg {
driver_label.set_label(&text);
driver_label.redraw();
} else {
apply(&devices, msg);
let flashed = match &msg {
EventMsg::Finished(location, "flash") => Some(location.clone()),
_ => None,
};
let chip = selected.lock().unwrap().chip.clone();
apply(&devices, msg, &chip);
if let Some(location) = flashed {
begin_claim(&location, &devices, &adb_devices, &claims, &selected);
}
}
}
refresh_table(&mut table, &devices);
ensure_identify(&queue, &devices);
let can_batch = devices.lock().unwrap().iter().any(|dev| dev.checked && !task_running(dev));
let busy = devices.lock().unwrap().iter().any(task_running);
if busy {
model_choice.deactivate();
} else {
model_choice.activate();
}
let can_batch = devices.lock().unwrap().iter().any(|dev| dev.checked && can_operate(dev));
if can_batch {
batch_btn.activate();
} else {
@@ -817,15 +1130,20 @@ fn main() {
fn toggle_row(devices: &Arc<Mutex<Vec<Device>>>, row: i32) {
let mut list = devices.lock().unwrap();
if let Some(dev) = list.get_mut(row as usize) {
if dev.mismatch {
return;
}
dev.checked = !dev.checked;
}
}
fn toggle_all(devices: &Arc<Mutex<Vec<Device>>>) {
let mut list = devices.lock().unwrap();
let check = list.iter().any(|dev| !dev.checked);
let check = list.iter().any(|dev| can_operate(dev) && !dev.checked);
for dev in list.iter_mut() {
dev.checked = check;
if can_operate(dev) || !check {
dev.checked = check && can_operate(dev);
}
}
}
@@ -834,7 +1152,7 @@ fn enqueue_checked(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<De
.lock()
.unwrap()
.iter()
.filter(|dev| dev.checked && !task_running(dev))
.filter(|dev| dev.checked && can_operate(dev))
.map(|dev| dev.location.clone())
.collect();
for location in locations {
@@ -876,6 +1194,9 @@ fn enqueue(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>,
if task_running(dev) {
return;
}
if kind != JobKind::Info && (dev.mismatch || !dev.info_done || dev.chip.is_empty()) {
return;
}
dev.queued = true;
dev.pending = Some(kind);
dev.progress = 0;
@@ -950,6 +1271,7 @@ fn apply_found(found: &[(String, String, String, String)], devices: &Arc<Mutex<V
present: true,
checked: false,
info_done: false,
mismatch: false,
missing_scans: 0,
});
}
@@ -973,6 +1295,248 @@ fn apply_found(found: &[(String, String, String, String)], devices: &Arc<Mutex<V
}
}
fn adb_key(device: &adb::AdbDevice) -> String {
format!("{}:{}", device.transport, device.serial)
}
fn same_port(left: &str, right: &str) -> bool {
if left.is_empty() || right.is_empty() {
return false;
}
if left.eq_ignore_ascii_case(right) {
return true;
}
let left_bits = port_bits(left);
let right_bits = port_bits(right);
!left_bits.is_empty() && left_bits == right_bits
}
fn port_bits(text: &str) -> Vec<String> {
let mut bits = Vec::new();
for token in ["Port_#", "Hub_#"] {
if let Some(rest) = text.split(token).nth(1) {
let number: String = rest.chars().take_while(|ch| ch.is_ascii_digit()).collect();
if !number.is_empty() {
bits.push(format!("{token}{number}"));
}
}
}
bits
}
fn begin_claim(
location: &str,
devices: &Arc<Mutex<Vec<Device>>>,
adb_devices: &Arc<Mutex<Vec<adb::AdbDevice>>>,
claims: &Arc<Mutex<Vec<Claim>>>,
selected: &Arc<Mutex<Profile>>,
) {
let profile = selected.lock().unwrap().clone();
let mut list = devices.lock().unwrap();
let Some(dev) = list.iter_mut().find(|dev| dev.location == location) else {
return;
};
if dev.serial.is_empty() {
return;
}
if profile.boot_host.is_empty() || profile.boot_model.is_empty() {
dev.status = "配置没有开机特征,未自动标记".into();
return;
}
let seen = adb_devices.lock().unwrap().iter().map(adb_key).collect();
let chip_serial = dev.serial.clone();
let location = dev.location.clone();
dev.status = "等待开机后的 ADB".into();
let mut claims = claims.lock().unwrap();
claims.retain(|claim| claim.location != location);
claims.push(Claim {
location,
chip_serial,
model_id: profile.id,
boot_host: profile.boot_host,
boot_model: profile.boot_model,
seen,
stage: ClaimStage::Wait,
since: Instant::now(),
token: String::new(),
});
}
fn advance_claims(found: &[adb::AdbDevice], claims: &Arc<Mutex<Vec<Claim>>>, tx: &mpsc::Sender<EventMsg>) {
let jobs = {
let mut list = claims.lock().unwrap();
let mut jobs = Vec::new();
let mut index = 0;
while index < list.len() {
if list[index].stage == ClaimStage::Marking {
index += 1;
continue;
}
if list[index].stage == ClaimStage::Confirm {
let linked = found.iter().any(|device| {
device.serial.eq_ignore_ascii_case(&list[index].chip_serial)
&& device.mark_chip.eq_ignore_ascii_case(&list[index].chip_serial)
});
if linked {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "已接上 ADB".into()));
list.remove(index);
continue;
}
if list[index].since.elapsed() > Duration::from_secs(180) {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "未重新识别到新序列号".into()));
list.remove(index);
continue;
}
index += 1;
continue;
}
if list[index].since.elapsed() > Duration::from_secs(180) {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "开机后未对上同一USB口".into()));
list.remove(index);
continue;
}
let hits: Vec<adb::AdbDevice> = found
.iter()
.filter(|device| {
same_port(&device.port, &list[index].location)
&& !list[index].seen.iter().any(|key| key == &adb_key(device))
})
.cloned()
.collect();
if hits.len() > 1 {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "同一USB口对应多台ADB,已停止".into()));
list.remove(index);
continue;
}
if hits.is_empty() {
index += 1;
continue;
}
let device = &hits[0];
if device.host.is_empty() || device.board_model.is_empty() {
index += 1;
continue;
}
if !device.host.eq_ignore_ascii_case(&list[index].boot_host)
|| device.board_model.trim() != list[index].boot_model.trim()
{
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "开机特征不符,未写标记".into()));
list.remove(index);
continue;
}
list[index].stage = ClaimStage::Marking;
jobs.push((list[index].clone(), device.clone()));
index += 1;
}
jobs
};
for (claim, device) in jobs {
let _ = tx.send(EventMsg::Status(claim.location.clone(), "正在写入标记".into()));
match adb::mark(&device, &claim.chip_serial, &claim.model_id) {
Ok(token) => {
let _ = tx.send(EventMsg::Status(claim.location.clone(), "正在重启以应用新序列号".into()));
let _ = adb::reboot(&device);
if let Some(slot) = claims.lock().unwrap().iter_mut().find(|item| item.location == claim.location) {
slot.token = token;
slot.stage = ClaimStage::Confirm;
slot.since = Instant::now();
}
}
Err(err) => {
let _ = tx.send(EventMsg::Status(claim.location.clone(), format!("标记失败:{err}")));
claims.lock().unwrap().retain(|item| item.location != claim.location);
}
}
}
}
fn adb_cell(devices: &Mutex<Vec<adb::AdbDevice>>, row: i32, col: i32) -> String {
let list = devices.lock().unwrap();
let Some(dev) = list.get(row as usize) else {
return String::new();
};
let text = match col {
0 => dev.serial.clone(),
1 => dev.chip.clone(),
2 => dev.port.clone(),
3 => dev.cores.clone(),
4 => dev.memory.clone(),
5 => dev.disk.clone(),
6 => dev.system.clone(),
7 => dev.marked.clone(),
_ => String::new(),
};
if text.is_empty() { "-".into() } else { text }
}
fn refresh_adb_table(table: &mut TableRow, devices: &Arc<Mutex<Vec<adb::AdbDevice>>>) {
let count = devices.lock().unwrap().len() as i32;
if table.rows() != count {
table.set_rows(count);
}
table.redraw();
}
fn chip_serial_for_port(devices: &Arc<Mutex<Vec<Device>>>, port: &str) -> String {
if port.is_empty() {
return String::new();
}
let list = devices.lock().unwrap();
let matched: Vec<_> = list
.iter()
.filter(|dev| dev.location == port && !dev.serial.is_empty())
.map(|dev| dev.serial.clone())
.collect();
if matched.len() == 1 {
matched[0].clone()
} else {
String::new()
}
}
fn adb_popup(
device: &adb::AdbDevice,
devices: &Arc<Mutex<Vec<Device>>>,
selected: &Arc<Mutex<Profile>>,
adb_refresh: &Arc<AtomicBool>,
x: i32,
y: i32,
) {
let item = |text| CMenuItem {
text: Some(text),
flags: MenuFlag::Normal,
shortcut: Shortcut::None,
cb: None,
labeltype: LabelType::Normal,
labelfont: Font::Helvetica,
labelsize: 15,
labelcolor: Color::Foreground,
};
let menu = MenuItem::new_from_cmenu(&[item("校准标记"), item("重启系统")]);
let Some(item) = menu.popup(x, y) else { return };
match item.label().unwrap_or_default().as_str() {
"校准标记" => {
let chip = chip_serial_for_port(devices, &device.port);
let model = selected.lock().unwrap().id.clone();
let device = device.clone();
let adb_refresh = Arc::clone(adb_refresh);
thread::spawn(move || {
let _ = adb::mark(&device, &chip, &model);
adb_refresh.store(true, Ordering::SeqCst);
});
}
"重启系统" => {
let device = device.clone();
let adb_refresh = Arc::clone(adb_refresh);
thread::spawn(move || {
let _ = adb::reboot(&device);
adb_refresh.store(true, Ordering::SeqCst);
});
}
_ => {}
}
}
fn cell_text(devices: &Mutex<Vec<Device>>, row: i32, col: i32) -> String {
let list = devices.lock().unwrap();
let Some(dev) = list.get(row as usize) else {
@@ -1035,7 +1599,7 @@ fn refresh_table(table: &mut TableRow, devices: &Arc<Mutex<Vec<Device>>>) {
table.redraw();
}
fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg, expected_chip: &str) {
let mut list = devices.lock().unwrap();
match msg {
EventMsg::Serial(location, serial) => {
@@ -1090,9 +1654,16 @@ fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
if kind == "info" {
dev.info_done = true;
dev.progress = 0;
if dev.serial.is_empty() && dev.chip.is_empty() {
if dev.chip.is_empty() {
dev.mismatch = true;
dev.checked = false;
dev.status = "重新进入9008后可读序列号".into();
} else if !chip_matches(&dev.chip, expected_chip) {
dev.mismatch = true;
dev.checked = false;
dev.status = MISMATCH.into();
} else {
dev.mismatch = false;
dev.status = "9008".into();
}
} else {
@@ -1112,6 +1683,14 @@ fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
if err == "设备已拔出" {
dev.present = false;
dev.status = UNPLUGGED.into();
} else if err == MISMATCH {
dev.mismatch = true;
dev.checked = false;
dev.status = MISMATCH.into();
} else if err == "未能确认芯片型号" {
dev.mismatch = true;
dev.checked = false;
dev.status = "重新进入9008后可读序列号".into();
} else {
dev.status = format!("失败:{err}");
}