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
+2
View File
@@ -15,6 +15,8 @@ backup/
# 刷机工具离线运行时(镜像、edl、Python,体积大,本机保留)
flasher/images/
flasher/devices/*/images/
flasher/devices/selected.txt
flasher/runtime/
flasher/target/
dist/
+32
View File
@@ -0,0 +1,32 @@
# UFI003_MB_V02 的刷机资料。镜像放在本目录 images/,不入库。
id=UFI003_MB_V02
hint=设备请按住复位键然后插入电脑,列表只显示9008设备。
chip=MSM8916
boot_host=ufi003
boot_model=UFI003 4G Modem Stick
devinfo=657408,2048
vid=05C6
pid=9008
driver=drivers
loader=runtime/edl/Loaders/cyanogen/007050e100000000_4614048173062ae4_fhprg_peek.bin
images=images
memory=eMMC
maxpayload=16384
partition=modemst1
partition=modemst2
partition=fsc
partition=fsg
backup=modemst1,267296,2097152
backup=modemst2,271392,2097152
backup=fsc,275488,1024
backup=fsg,393216,2097152
flash=gpt_primary.bin,0
flash=gpt_backup.bin,7471038
flash=cdt.bin,131072
flash=sbl1.mbn,262144
flash=rpm.mbn,263168
flash=tz.mbn,264192
flash=hyp.mbn,266240
flash=aboot.mbn,524288
flash=boot.img,526336
flash=rootfs.img,659456
+145 -52
View File
@@ -2,38 +2,20 @@
import logging
import os
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
EDL = os.path.join(HERE, "edl")
LOADER = os.path.join(
EDL, "Loaders", "cyanogen", "007050e100000000_4614048173062ae4_fhprg_peek.bin"
)
IMAGES = os.path.join(os.path.dirname(HERE), "images")
WRITES = [
("gpt_primary.bin", 0),
("gpt_backup.bin", 7471038),
("cdt.bin", 131072),
("sbl1.mbn", 262144),
("rpm.mbn", 263168),
("tz.mbn", 264192),
("hyp.mbn", 266240),
("aboot.mbn", 524288),
("boot.img", 526336),
("rootfs.img", 659456),
]
EFS = [
("modemst1.bin", "modemst1", 267296),
("modemst2.bin", "modemst2", 271392),
("fsc.bin", "fsc", 275488),
("fsg.bin", "fsg", 393216),
]
EFS_BYTES = {
"modemst1": 2 * 1024 * 1024,
"modemst2": 2 * 1024 * 1024,
"fsc": 1024,
"fsg": 2 * 1024 * 1024,
}
LOADER = ""
IMAGES = ""
MEMORY = "eMMC"
MAXPAYLOAD = "16384"
REQUIRED = []
BACKUPS = []
FLASHES = []
DEVINFO_LBA = 0
DEVINFO_SECTORS = 0
MODEL_ID = ""
def emit(key, value):
@@ -45,6 +27,64 @@ def fail(message):
sys.exit(1)
def load_profile(path):
# 型号资料是唯一的分区和镜像来源。images 相对资料目录,loader 相对程序目录。
global LOADER, IMAGES, MEMORY, MAXPAYLOAD, REQUIRED, BACKUPS, FLASHES
global DEVINFO_LBA, DEVINFO_SECTORS, MODEL_ID
profile_dir = os.path.dirname(os.path.abspath(path))
app_dir = os.path.dirname(os.path.dirname(profile_dir))
values = {"partition": [], "backup": [], "flash": []}
with open(path, encoding="utf-8") as handle:
for raw in handle:
line = raw.split("#", 1)[0].strip()
if not line or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if key in values:
values[key].append(value)
else:
values[key] = value
images = values.get("images") or ""
loader = values.get("loader") or ""
if not images or not loader:
fail("型号配置缺少镜像目录或引导文件")
IMAGES = images if os.path.isabs(images) else os.path.join(profile_dir, images)
LOADER = loader if os.path.isabs(loader) else os.path.join(app_dir, loader)
MEMORY = values.get("memory") or "eMMC"
MAXPAYLOAD = str(values.get("maxpayload") or "16384")
REQUIRED = values["partition"]
BACKUPS = []
for item in values["backup"]:
name, lba, size = [part.strip() for part in item.split(",")]
BACKUPS.append((name, int(lba), int(size)))
FLASHES = []
for item in values["flash"]:
filename, lba = [part.strip() for part in item.split(",")]
FLASHES.append((filename, int(lba)))
if not REQUIRED:
fail("型号配置没有用于核对的分区")
if not os.path.isfile(LOADER):
fail("找不到引导文件")
MODEL_ID = values.get("id") or ""
devinfo = values.get("devinfo") or ""
if devinfo:
lba, count = [part.strip() for part in devinfo.split(",")]
DEVINFO_LBA = int(lba)
DEVINFO_SECTORS = int(count)
def edl_argv():
return [
"edl.py",
"printgpt",
"--memory=" + MEMORY,
"--maxpayload=" + MAXPAYLOAD,
"--loader=" + LOADER,
]
def format_size(sectors):
size = int(sectors) * 512
gib = 1024 ** 3
@@ -76,13 +116,7 @@ def open_link():
os.chdir(EDL)
if EDL not in sys.path:
sys.path.insert(0, EDL)
sys.argv = [
"edl.py",
"printgpt",
"--memory=eMMC",
"--maxpayload=16384",
"--loader=" + LOADER,
]
sys.argv = edl_argv()
import edl
fill_edl_args(edl.args)
from edlclient.Config.usb_ids import default_ids
@@ -134,13 +168,7 @@ def connect():
os.chdir(EDL)
if EDL not in sys.path:
sys.path.insert(0, EDL)
sys.argv = [
"edl.py",
"printgpt",
"--memory=eMMC",
"--maxpayload=16384",
"--loader=" + LOADER,
]
sys.argv = edl_argv()
import edl
fill_edl_args(edl.args)
@@ -273,12 +301,33 @@ def chip_name(app):
return hwid
def gpt_names(app):
try:
_data, gpt = app.fh.firehose.get_gpt(0, 0, 0, 0)
except SystemExit:
raise
except Exception as exc:
fail(f"没有读到分区表:{exc}")
entries = getattr(gpt, "partentries", None) if gpt is not None else None
if not entries:
fail("没有读到分区表")
return {str(name).lower() for name in entries}
def ensure_layout(app):
# 已在本次 Firehose 会话中。不符合就退出,不写盘,也不发复位。
names = gpt_names(app)
missing = [name for name in REQUIRED if name.lower() not in names]
if missing:
fail("分区不符,已停止:" + "、".join(missing) + "。请拔出并按住复位键后重新插入")
def read_part(app, name, path):
options = {
"<partitionname>": name,
"<filename>": path,
"--lun": None,
"--memory": "eMMC",
"--memory": MEMORY,
}
if not app.fh.handle_firehose("r", options):
fail(f"读取 {name} 失败")
@@ -294,12 +343,37 @@ def fit_partition(path, size):
handle.write(b"\x00" * (size - len(data)))
def write_board_id(app, chip):
# 写在 devinfo 最后一个扇区,保留分区开头给引导程序。
if DEVINFO_LBA <= 0 or DEVINFO_SECTORS <= 0:
return
if not chip:
fail("没有芯片号,不能写入 devinfo")
text = f"FLASHER1\nchip_serial={chip}\nmodel={MODEL_ID}\n"
blob = text.encode("ascii")
if len(blob) > 512:
fail("devinfo 记录过长")
blob += b"\x00" * (512 - len(blob))
fd, path = tempfile.mkstemp(prefix="devinfo-", suffix=".bin")
try:
os.write(fd, blob)
os.close(fd)
fd = -1
emit("STATUS", "正在写入 devinfo")
write_file(app, DEVINFO_LBA + DEVINFO_SECTORS - 1, path)
finally:
if fd >= 0:
os.close(fd)
if os.path.isfile(path):
os.remove(path)
def write_file(app, start, path):
options = {
"<start_sector>": str(start),
"<filename>": path,
"--lun": None,
"--memory": "eMMC",
"--memory": MEMORY,
"--skipwrite": False,
}
if not app.fh.handle_firehose("ws", options):
@@ -314,6 +388,8 @@ def main():
dest = ""
full = False
skip_efs = False
profile = ""
chip_arg = ""
args = sys.argv[2:]
i = 0
while i < len(args):
@@ -325,6 +401,14 @@ def main():
dest = args[i + 1]
i += 2
continue
if args[i] == "--profile" and i + 1 < len(args):
profile = args[i + 1]
i += 2
continue
if args[i] == "--chip" and i + 1 < len(args):
chip_arg = args[i + 1]
i += 2
continue
if args[i] == "--full":
full = True
i += 1
@@ -334,6 +418,9 @@ def main():
i += 1
continue
i += 1
if not profile:
fail("没有型号配置")
load_profile(profile)
if port:
os.environ["EDL_USB_PORT"] = port
if command == "info":
@@ -354,6 +441,7 @@ def main():
sectors = storage_sectors(app)
emit("DISK", format_size(sectors))
emit("SECTORS", str(sectors))
ensure_layout(app)
if command == "info":
emit("DONE", "info")
return
@@ -362,11 +450,13 @@ def main():
fail("没有备份目录")
if skip_efs and not full:
fail("没有要备份的内容")
if not skip_efs and not BACKUPS:
fail("型号配置没有备份分区")
os.makedirs(dest, exist_ok=True)
if not skip_efs:
span = 60 if full else 80
for index, (_file, name, _lba) in enumerate(EFS):
emit("PROGRESS", str(int(index * span / len(EFS))))
for index, (name, _lba, _size) in enumerate(BACKUPS):
emit("PROGRESS", str(int(index * span / max(len(BACKUPS), 1))))
read_part(app, name, os.path.join(dest, name + ".bin"))
if full:
emit("STATUS", "正在备份整盘")
@@ -399,12 +489,14 @@ def main():
if command == "flash":
restore = bool(dest)
if restore:
for name in ("modemst1", "modemst2", "fsc", "fsg"):
for name, _lba, _size in BACKUPS:
if not os.path.isfile(os.path.join(dest, name + ".bin")):
fail(f"缺少 {name} 备份")
total = len(WRITES) + (len(EFS) if restore else 0)
total = len(FLASHES) + (len(BACKUPS) if restore else 0)
if total == 0:
fail("型号配置没有写入步骤")
step = 0
for filename, start in WRITES:
for filename, start in FLASHES:
path = os.path.join(IMAGES, filename)
if not os.path.isfile(path):
fail(f"镜像缺少 {filename}")
@@ -413,13 +505,14 @@ def main():
step += 1
emit("PROGRESS", str(int(step * 90 / total)))
if restore:
for filename, name, start in EFS:
for name, start, size in BACKUPS:
path = os.path.join(dest, name + ".bin")
fit_partition(path, EFS_BYTES[name])
fit_partition(path, size)
emit("STATUS", f"正在写回 {name}")
write_file(app, start, path)
step += 1
emit("PROGRESS", str(int(step * 90 / total)))
write_board_id(app, chip_arg)
try:
app.cdc.timeout = 1500
app.fh.firehose.cmd_reset("reset")
+275
View File
@@ -0,0 +1,275 @@
use std::io::Read;
use std::process::Stdio;
use std::time::Duration;
use super::command;
#[derive(Clone, Debug)]
pub struct AdbDevice {
pub serial: String,
pub transport: String,
pub chip: String,
pub port: String,
pub cores: String,
pub memory: String,
pub disk: String,
pub system: String,
pub marked: String,
pub host: String,
pub board_model: String,
pub mark_chip: String,
}
pub fn list_devices() -> Vec<AdbDevice> {
let text = match adb_output(&["devices", "-l"]) {
Ok(text) => text,
Err(_) => return Vec::new(),
};
let mut found = Vec::new();
for line in text.lines().skip(1) {
let line = line.trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(serial) = parts.next() else { continue };
let Some(state) = parts.next() else { continue };
if state == "device" || state == "unauthorized" || state == "offline" {
let transport = line
.split_whitespace()
.find_map(|part| part.strip_prefix("transport_id:"))
.unwrap_or("")
.to_string();
found.push((serial.to_string(), state.to_string(), transport));
}
}
found
.into_iter()
.map(|(serial, state, transport)| {
let mut device = if state == "device" {
probe(&serial, &transport).unwrap_or_else(|_| AdbDevice::bare(serial.clone(), transport.clone()))
} else {
let mut device = AdbDevice::bare(serial.clone(), transport.clone());
device.marked = match state.as_str() {
"unauthorized" => "未授权".into(),
_ => "离线".into(),
};
device
};
if device.port.is_empty() {
device.port = windows_port(&serial);
}
device
})
.collect()
}
impl AdbDevice {
fn bare(serial: String, transport: String) -> Self {
Self {
serial,
transport,
chip: String::new(),
port: String::new(),
cores: String::new(),
memory: String::new(),
disk: String::new(),
system: String::new(),
marked: "未标记".into(),
host: String::new(),
board_model: String::new(),
mark_chip: String::new(),
}
}
}
pub fn mark(device: &AdbDevice, _chip_serial: &str, _model_id: &str) -> Result<String, String> {
let text = shell(device, &devinfo_script())?;
let chip_serial = devinfo_chip(&text);
if chip_serial.is_empty() {
return Err("devinfo 里没有芯片号".into());
}
let script = format!(
"if [ -f /usr/sbin/openstick-gc-manager.sh ]; then sed -i 's|echo \"[^\"]*\" > ${{STRING_DIR}}/serialnumber|echo \"{chip_serial}\" > ${{STRING_DIR}}/serialnumber|' /usr/sbin/openstick-gc-manager.sh; fi\nif [ -f /sys/kernel/config/usb_gadget/g1/strings/0x409/serialnumber ]; then echo '{chip_serial}' > /sys/kernel/config/usb_gadget/g1/strings/0x409/serialnumber || true; fi\nprintf 'CHIP=%s\\n' '{chip_serial}'\n"
);
shell(device, &script)?;
Ok(chip_serial)
}
pub fn reboot(device: &AdbDevice) -> Result<(), String> {
shell(device, "reboot")?;
Ok(())
}
fn probe(serial: &str, transport: &str) -> Result<AdbDevice, String> {
let script = r#"
printf 'CHIP=%s\n' "$(cat /sys/bus/soc/devices/soc0/machine 2>/dev/null)"
printf 'CORES=%s\n' "$(grep -c ^processor /proc/cpuinfo 2>/dev/null)"
printf 'MEM=%s\n' "$(awk '/MemTotal/ {print $2}' /proc/meminfo 2>/dev/null)"
printf 'DISK=%s\n' "$(cat /sys/block/mmcblk0/size 2>/dev/null)"
printf 'OS=%s\n' "$(. /etc/os-release 2>/dev/null; printf '%s' "$PRETTY_NAME")"
part=/dev/disk/by-partlabel/devinfo
if [ -b "$part" ]; then
sz=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
if [ "$sz" -gt 0 ]; then
data=$(dd if="$part" bs=512 skip=$((sz-1)) count=1 status=none 2>/dev/null | tr -d '\000')
printf 'DEVINFO_CHIP=%s\n' "$(printf '%s\n' "$data" | sed -n 's/^chip_serial=//p' | head -n 1)"
fi
fi
printf 'HOST=%s\n' "$(hostname 2>/dev/null)"
printf 'MODEL=%s\n' "$(tr -d '\000' < /proc/device-tree/model 2>/dev/null)"
"#;
let text = shell_on(serial, transport, script)?;
let mut device = AdbDevice::bare(serial.to_string(), transport.to_string());
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else { continue };
let value = value.trim();
match key {
"CHIP" => device.chip = value.to_string(),
"CORES" => device.cores = value.to_string(),
"MEM" => device.memory = format_kb(value),
"DISK" => device.disk = format_sectors(value),
"OS" => device.system = value.to_string(),
"HOST" => device.host = value.to_string(),
"MODEL" => device.board_model = value.to_string(),
"DEVINFO_CHIP" => device.mark_chip = value.to_string(),
_ => {}
}
}
if device.mark_chip.is_empty() {
device.marked = "无记录".into();
} else if device.serial.eq_ignore_ascii_case(&device.mark_chip) {
device.marked = "已标记".into();
} else {
device.marked = "未标记".into();
}
Ok(device)
}
fn devinfo_script() -> String {
r#"
part=/dev/disk/by-partlabel/devinfo
if [ ! -b "$part" ]; then
printf 'DEVINFO_CHIP=\n'
exit 0
fi
sz=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
data=$(dd if="$part" bs=512 skip=$((sz-1)) count=1 status=none 2>/dev/null | tr -d '\000')
printf 'DEVINFO_CHIP=%s\n' "$(printf '%s\n' "$data" | sed -n 's/^chip_serial=//p' | head -n 1)"
"#
.into()
}
fn devinfo_chip(text: &str) -> String {
text.lines()
.find_map(|line| line.trim().strip_prefix("DEVINFO_CHIP="))
.unwrap_or("")
.trim()
.to_string()
}
fn shell(device: &AdbDevice, script: &str) -> Result<String, String> {
shell_on(&device.serial, &device.transport, script)
}
fn shell_on(serial: &str, transport: &str, script: &str) -> Result<String, String> {
// 把脚本作为 adb shell 的参数执行。用 stdin 喂给交互式 shell 时,命令跑完进程也不退出。
let mut cmd = command("adb");
if !transport.is_empty() {
cmd.arg("-t").arg(transport);
} else {
cmd.arg("-s").arg(serial);
}
let mut child = cmd
.arg("shell")
.arg(script)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|err| format!("无法启动 adb:{err}"))?;
let mut stdout = child.stdout.take();
let started = std::time::Instant::now();
loop {
if let Some(status) = child.try_wait().map_err(|err| err.to_string())? {
let mut text = String::new();
if let Some(out) = stdout.as_mut() {
let _ = out.read_to_string(&mut text);
}
if status.success() {
return Ok(text);
}
return Err(if text.trim().is_empty() { "adb 命令失败".into() } else { text });
}
if started.elapsed() > Duration::from_secs(12) {
let _ = child.kill();
return Err("adb 命令超时".into());
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn adb_output(args: &[&str]) -> Result<String, String> {
let output = command("adb").args(args).output().map_err(|err| err.to_string())?;
if !output.status.success() && output.stdout.is_empty() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn windows_port(serial: &str) -> String {
if serial.is_empty() || serial.contains(['\'', '"', ';', '&']) {
return String::new();
}
let script = r#"
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like ('*' + $env:FLASHER_ADB + '*') } | ForEach-Object {
try {
$p = Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LocationInfo
$loc = [string]$p.Data
if ($loc) { Write-Output $loc }
} catch {}
}
"#;
let output = command("powershell")
.args(["-NoProfile", "-Command", script])
.env("FLASHER_ADB", serial)
.output();
let Ok(output) = output else { return String::new() };
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("")
.to_string()
}
fn format_kb(text: &str) -> String {
let Ok(kb) = text.trim().parse::<u64>() else { return String::new() };
format_bytes(kb * 1024)
}
fn format_sectors(text: &str) -> String {
let Ok(sectors) = text.trim().parse::<u64>() else { return String::new() };
format_bytes(sectors * 512)
}
fn format_bytes(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let value = bytes as f64;
let (scaled, unit) = if value >= GB {
(value / GB, "GB")
} else if value >= MB {
(value / MB, "MB")
} else if value >= KB {
(value / KB, "KB")
} else {
return format!("{bytes}B");
};
if scaled >= 100.0 || (scaled - scaled.round()).abs() < 0.05 {
format!("{scaled:.0}{unit}")
} else {
format!("{scaled:.1}{unit}")
}
}
+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}");
}
+126
View File
@@ -0,0 +1,126 @@
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct Profile {
pub id: String,
pub chip: String,
pub vid: String,
pub pid: String,
pub driver_dir: PathBuf,
pub conf_path: PathBuf,
pub hint: String,
pub boot_host: String,
pub boot_model: String,
}
pub fn chip_matches(found: &str, expect: &str) -> bool {
let found = found.trim();
let expect = expect.trim();
!found.is_empty() && found.eq_ignore_ascii_case(expect)
}
pub fn display(profile: &Profile) -> String {
profile.id.clone()
}
pub fn load_all(app_dir: &Path) -> Result<Vec<Profile>, String> {
let root = app_dir.join("devices");
let entries = fs::read_dir(&root).map_err(|err| format!("没有型号目录:{err}"))?;
let mut profiles = Vec::new();
for entry in entries.filter_map(Result::ok) {
let conf = entry.path().join("device.conf");
if conf.is_file() {
profiles.push(load_file(&conf, app_dir)?);
}
}
profiles.sort_by(|left, right| left.id.to_lowercase().cmp(&right.id.to_lowercase()));
if profiles.is_empty() {
return Err("没有找到型号配置".into());
}
Ok(profiles)
}
pub fn remember(app_dir: &Path, id: &str) {
let path = app_dir.join("devices").join("selected.txt");
let _ = fs::write(path, id);
}
pub fn remembered(app_dir: &Path, profiles: &[Profile]) -> usize {
let path = app_dir.join("devices").join("selected.txt");
let saved = fs::read_to_string(path).unwrap_or_default();
let saved = saved.trim();
profiles
.iter()
.position(|profile| profile.id == saved)
.unwrap_or(0)
}
fn load_file(conf: &Path, app_dir: &Path) -> Result<Profile, String> {
let text = fs::read_to_string(conf).map_err(|err| format!("无法读取 {}:{err}", conf.display()))?;
let mut id = String::new();
let mut chip = String::new();
let mut vid = String::new();
let mut pid = String::new();
let mut driver = String::new();
let mut hint = String::new();
let mut boot_host = String::new();
let mut boot_model = String::new();
for raw in text.lines() {
let line = raw.split('#').next().unwrap_or("").trim();
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.trim();
match key.trim() {
"id" => id = value.to_string(),
"chip" => chip = value.to_string(),
"vid" => vid = value.to_string(),
"pid" => pid = value.to_string(),
"driver" => driver = value.to_string(),
"hint" => hint = value.to_string(),
"boot_host" => boot_host = value.to_string(),
"boot_model" => boot_model = value.to_string(),
_ => {}
}
}
if id.is_empty() || chip.is_empty() || !is_hex4(&vid) || !is_hex4(&pid) || driver.is_empty() || hint.is_empty() {
return Err(format!("{} 缺少型号、芯片、USB 号、驱动目录或底部说明", conf.display()));
}
Ok(Profile {
id,
chip,
vid: vid.to_uppercase(),
pid: pid.to_uppercase(),
driver_dir: app_dir.join(driver),
conf_path: conf.to_path_buf(),
hint,
boot_host,
boot_model,
})
}
fn is_hex4(text: &str) -> bool {
text.len() == 4 && text.chars().all(|ch| ch.is_ascii_hexdigit())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn loads_ufi003_profile() {
let app_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let profiles = load_all(&app_dir).expect("profile");
let profile = profiles.iter().find(|item| item.id == "UFI003_MB_V02").expect("ufi");
assert_eq!(profile.chip, "MSM8916");
assert_eq!(profile.vid, "05C6");
assert_eq!(profile.pid, "9008");
assert_eq!(profile.hint, "设备请按住复位键然后插入电脑,列表只显示9008设备。");
assert_eq!(profile.boot_host, "ufi003");
assert_eq!(profile.boot_model, "UFI003 4G Modem Stick");
assert!(chip_matches("msm8916", &profile.chip));
assert!(!chip_matches("MSM8994", &profile.chip));
assert!(!chip_matches("", &profile.chip));
}
}