chore: 更新 .gitignore 文件以排除交叉编译产物和刷机工具相关目录
This commit is contained in:
@@ -4,12 +4,21 @@ Temp/
|
||||
temp/
|
||||
*.tmp
|
||||
|
||||
# 交叉编译产物
|
||||
tools/imei/imeitool
|
||||
|
||||
# modemst / EFS 备份(含 IMEI 与 RF 校准,禁止提交)
|
||||
backup/
|
||||
**/modemst*.bin
|
||||
**/fsg*.bin
|
||||
**/fsc*.bin
|
||||
|
||||
# 刷机工具离线运行时(镜像、edl、Python,体积大,本机保留)
|
||||
flasher/images/
|
||||
flasher/runtime/
|
||||
flasher/target/
|
||||
dist/
|
||||
|
||||
# 设备侧配置与敏感产物
|
||||
etc/imei.conf
|
||||
**/imei.conf
|
||||
|
||||
Generated
+121
@@ -0,0 +1,121 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmk"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd5de2a10e31b3ec3e8d75e7ccf8281ab3ee55de68f7ab6ffa9e21be8d82f22"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "flasher"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"fltk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fltk"
|
||||
version = "1.5.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6acfa51a6d98065984e5f6f21fca6d421791b7b8b6a1351d1966c9799d2c7c60"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossbeam-channel",
|
||||
"fltk-sys",
|
||||
"minipaste",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fltk-sys"
|
||||
version = "1.5.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c4875e000369874f50a6c09abf99f08ff45b867daa340ffe5965122a849c83b"
|
||||
dependencies = [
|
||||
"cmake",
|
||||
"cmk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minipaste"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1bbcafc6544efab7decec8e8e63d6e7cbaac0a699a4adead308a80f9c302d6ae"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "flasher"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "9008 离线刷机工具"
|
||||
|
||||
[dependencies]
|
||||
fltk = { version = "1.5", features = ["fltk-bundled"] }
|
||||
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
param([switch]$Install)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$inf = Join-Path $PSScriptRoot 'qhsusb.inf'
|
||||
$cer = Join-Path $PSScriptRoot 'qhsusb.cer'
|
||||
|
||||
function Test-QhsusbInstalled {
|
||||
$files = @(Get-ChildItem 'C:\Windows\INF\oem*.inf' -ErrorAction SilentlyContinue)
|
||||
foreach ($file in $files) {
|
||||
try {
|
||||
$text = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if ($text -match 'QHSUSB__BULK' -and $text -match 'VID_05C6&PID_9008') {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function Test-Admin {
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
|
||||
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||
}
|
||||
|
||||
if (-not $Install) {
|
||||
if (Test-QhsusbInstalled) {
|
||||
Write-Output "DRIVER`tREADY"
|
||||
} else {
|
||||
Write-Output "DRIVER`tMISSING"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not (Test-Admin)) {
|
||||
$arg = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Install"
|
||||
try {
|
||||
Start-Process -FilePath powershell.exe -ArgumentList $arg -Verb RunAs -Wait | Out-Null
|
||||
} catch {
|
||||
Write-Output "DRIVER`tFAIL`tcancel"
|
||||
exit 1
|
||||
}
|
||||
if (Test-QhsusbInstalled) {
|
||||
Write-Output "DRIVER`tINSTALLED"
|
||||
exit 0
|
||||
}
|
||||
Write-Output "DRIVER`tFAIL"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $cer) {
|
||||
& certutil.exe -addstore -f TrustedPublisher $cer | Out-Null
|
||||
}
|
||||
$proc = Start-Process -FilePath "$env:SystemRoot\System32\pnputil.exe" -ArgumentList @('/add-driver', $inf, '/install') -Wait -PassThru -NoNewWindow
|
||||
if (Test-QhsusbInstalled) {
|
||||
Write-Output "DRIVER`tINSTALLED"
|
||||
exit 0
|
||||
}
|
||||
Write-Output ("DRIVER`tFAIL`t" + $proc.ExitCode)
|
||||
exit 1
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,107 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$InstanceId
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$inf = (Resolve-Path (Join-Path $PSScriptRoot 'qhsusb.inf')).Path
|
||||
if (-not (Test-Path -LiteralPath $inf)) {
|
||||
throw '找不到 WinUSB 驱动描述'
|
||||
}
|
||||
|
||||
Add-Type -TypeDefinition @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public static class QhsusbOne {
|
||||
public const uint DIGCF_PRESENT = 0x2;
|
||||
public const uint DIGCF_ALLCLASSES = 0x4;
|
||||
public const uint DI_ENUMSINGLEINF = 0x00010000;
|
||||
public const uint DIF_SELECTBESTCOMPATDRV = 0x17;
|
||||
public const uint DIF_INSTALLDEVICE = 0x2;
|
||||
public const uint SPDIT_COMPATDRIVER = 2;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct SP_DEVINFO_DATA {
|
||||
public int cbSize;
|
||||
public Guid ClassGuid;
|
||||
public uint DevInst;
|
||||
public IntPtr Reserved;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct SP_DEVINSTALL_PARAMS {
|
||||
public int cbSize;
|
||||
public int Flags;
|
||||
public int FlagsEx;
|
||||
public IntPtr hwndParent;
|
||||
public IntPtr InstallMsgHandler;
|
||||
public IntPtr InstallMsgHandlerContext;
|
||||
public IntPtr FileQueue;
|
||||
public IntPtr ClassInstallReserved;
|
||||
public int Reserved;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
|
||||
public string DriverPath;
|
||||
}
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern IntPtr SetupDiGetClassDevs(IntPtr classGuid, string enumerator, IntPtr hwnd, uint flags);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool SetupDiOpenDeviceInfo(IntPtr deviceInfoSet, string deviceInstanceId, IntPtr hwnd, uint flags, ref SP_DEVINFO_DATA data);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool SetupDiGetDeviceInstallParams(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, ref SP_DEVINSTALL_PARAMS parms);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool SetupDiSetDeviceInstallParams(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, ref SP_DEVINSTALL_PARAMS parms);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool SetupDiBuildDriverInfoList(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, uint type);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool SetupDiCallClassInstaller(uint installFunction, IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data);
|
||||
|
||||
[DllImport("setupapi.dll", SetLastError = true)]
|
||||
public static extern bool SetupDiDestroyDriverInfoList(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, uint type);
|
||||
|
||||
[DllImport("setupapi.dll", SetLastError = true)]
|
||||
public static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
|
||||
}
|
||||
|
||||
"@
|
||||
|
||||
function Throw-IfFailed([bool]$ok, [string]$step) {
|
||||
if ($ok) { return }
|
||||
$code = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
||||
throw ($step + ' 失败,Win32 错误 ' + $code)
|
||||
}
|
||||
|
||||
$set = [QhsusbOne]::SetupDiGetClassDevs([IntPtr]::Zero, 'USB', [IntPtr]::Zero, [QhsusbOne]::DIGCF_PRESENT -bor [QhsusbOne]::DIGCF_ALLCLASSES)
|
||||
Throw-IfFailed (-not ($set -eq [IntPtr]::Zero -or $set -eq [IntPtr]-1)) '打开设备列表'
|
||||
$dev = New-Object QhsusbOne+SP_DEVINFO_DATA
|
||||
$dev.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($dev)
|
||||
try {
|
||||
$ok = [QhsusbOne]::SetupDiOpenDeviceInfo($set, $InstanceId, [IntPtr]::Zero, 0, [ref]$dev)
|
||||
Throw-IfFailed $ok '定位这一台设备'
|
||||
$parms = New-Object QhsusbOne+SP_DEVINSTALL_PARAMS
|
||||
$parms.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($parms)
|
||||
$ok = [QhsusbOne]::SetupDiGetDeviceInstallParams($set, [ref]$dev, [ref]$parms)
|
||||
Throw-IfFailed $ok '读取安装参数'
|
||||
$parms.Flags = $parms.Flags -bor [QhsusbOne]::DI_ENUMSINGLEINF
|
||||
$parms.DriverPath = $inf
|
||||
$ok = [QhsusbOne]::SetupDiSetDeviceInstallParams($set, [ref]$dev, [ref]$parms)
|
||||
Throw-IfFailed $ok '指定驱动文件'
|
||||
$ok = [QhsusbOne]::SetupDiBuildDriverInfoList($set, [ref]$dev, [QhsusbOne]::SPDIT_COMPATDRIVER)
|
||||
Throw-IfFailed $ok '建立驱动列表'
|
||||
try {
|
||||
$ok = [QhsusbOne]::SetupDiCallClassInstaller([QhsusbOne]::DIF_SELECTBESTCOMPATDRV, $set, [ref]$dev)
|
||||
Throw-IfFailed $ok '选择驱动'
|
||||
$ok = [QhsusbOne]::SetupDiCallClassInstaller([QhsusbOne]::DIF_INSTALLDEVICE, $set, [ref]$dev)
|
||||
Throw-IfFailed $ok '安装驱动'
|
||||
} finally {
|
||||
[void][QhsusbOne]::SetupDiDestroyDriverInfoList($set, [ref]$dev, [QhsusbOne]::SPDIT_COMPATDRIVER)
|
||||
}
|
||||
} finally {
|
||||
[void][QhsusbOne]::SetupDiDestroyDeviceInfoList($set)
|
||||
}
|
||||
Write-Output 'OK'
|
||||
+1067
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
module ltedongle/imei
|
||||
|
||||
go 1.22
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# 开机时按 /etc/imei.conf 重写基带 IMEI。此固件只保留在内存里。
|
||||
START=65
|
||||
STOP=10
|
||||
|
||||
start() {
|
||||
[ -s /etc/imei.conf ] || return 0
|
||||
sleep 8
|
||||
/usr/bin/imeitool save
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
rpmsgCtrl = "/dev/rpmsg_ctrl2"
|
||||
rpmsgCreateEpt = 0x4028b501
|
||||
imeiConf = "/etc/imei.conf"
|
||||
nvItemIMEI = 550
|
||||
diagNvRead = 0x26
|
||||
diagNvWrite = 0x27
|
||||
diagSpc = 0x41
|
||||
)
|
||||
|
||||
type rpmsgEptInfo struct {
|
||||
Name [32]byte
|
||||
Src uint32
|
||||
Dst uint32
|
||||
}
|
||||
|
||||
func main() {
|
||||
cmd := ""
|
||||
if len(os.Args) > 1 {
|
||||
cmd = os.Args[1]
|
||||
}
|
||||
switch cmd {
|
||||
case "ftm-test":
|
||||
if err := ftmWriteSame(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
case "persist":
|
||||
if err := persistIMEI(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
case "read":
|
||||
imei, err := readIMEI()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(imei)
|
||||
case "save":
|
||||
imei := ""
|
||||
if len(os.Args) > 2 {
|
||||
imei = strings.TrimSpace(os.Args[2])
|
||||
} else if b, err := os.ReadFile(imeiConf); err == nil {
|
||||
imei = strings.TrimSpace(string(b))
|
||||
}
|
||||
if len(imei) != 15 || strings.IndexFunc(imei, func(r rune) bool { return r < '0' || r > '9' }) >= 0 {
|
||||
fmt.Fprintf(os.Stderr, "用法: imeitool save <15位IMEI>\n 或把 IMEI 写入 %s 后执行 imeitool save\n", imeiConf)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := saveIMEI(imei); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(imei)
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "imeitool - 读取或写入基带 IMEI\n\n用法:\n imeitool read\n imeitool save <15位IMEI>\n")
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func persistIMEI() error {
|
||||
fd, err := openDiag()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fd.Close()
|
||||
spcUnlock(fd)
|
||||
data, err := nvRead(fd, nvItemIMEI)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
imei, _ := nv550ToIMEI(data)
|
||||
fmt.Fprintf(os.Stderr, "当前 RAM IMEI: %s\n", orNA(imei))
|
||||
payload := data[:9]
|
||||
if err := efsHello(fd); err != nil {
|
||||
return err
|
||||
}
|
||||
paths := []string{"/nvm/num/550", "/nvm/num/00550", "/nv/item_files/modem/uim/imei"}
|
||||
for _, path := range paths {
|
||||
st, err := efsStat(fd, path)
|
||||
if err != nil {
|
||||
fmt.Printf("STAT %s %v\n", path, err)
|
||||
} else {
|
||||
fmt.Printf("STAT %s %s\n", path, hexBytes(st))
|
||||
}
|
||||
for _, oflag := range []uint32{2, 0x41, 0x301} {
|
||||
err := efsPut(fd, path, payload, oflag)
|
||||
fmt.Printf("PUT %s oflag=0x%x %v\n", path, oflag, err)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := efsSync(fd); err != nil {
|
||||
fmt.Printf("SYNC %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ftmWriteSame() error {
|
||||
fd, err := openDiag()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fd.Close()
|
||||
imei, err := readIMEIFrom(fd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "当前 IMEI: %s\n", imei)
|
||||
resp, err := diagCmd(fd, []byte{0x29, 0x03}, 3*time.Second)
|
||||
fmt.Printf("FTM %s %v\n", hexBytes(resp), err)
|
||||
spcUnlock(fd)
|
||||
if err := nvWrite(fd, nvItemIMEI, imeiToNV550(imei)); err != nil {
|
||||
fmt.Printf("NV写 %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("NV写 完成\n")
|
||||
}
|
||||
if err := efsSync(fd); err != nil {
|
||||
fmt.Printf("SYNC %v\n", err)
|
||||
}
|
||||
resp, err = diagCmd(fd, []byte{0x29, 0x04}, 3*time.Second)
|
||||
fmt.Printf("ONLINE %s %v\n", hexBytes(resp), err)
|
||||
return nil
|
||||
}
|
||||
|
||||
func readIMEIFrom(fd *os.File) (string, error) {
|
||||
data, err := nvRead(fd, nvItemIMEI)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
imei, ok := nv550ToIMEI(data)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("无法解析 NV 550")
|
||||
}
|
||||
return imei, nil
|
||||
}
|
||||
|
||||
func readIMEI() (string, error) {
|
||||
fd, err := openDiag()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer fd.Close()
|
||||
data, err := nvRead(fd, nvItemIMEI)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
imei, ok := nv550ToIMEI(data)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("无法解析 NV 550")
|
||||
}
|
||||
return imei, nil
|
||||
}
|
||||
|
||||
func saveIMEI(imei string) error {
|
||||
fd, err := openDiag()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
curData, err := nvRead(fd, nvItemIMEI)
|
||||
if err != nil {
|
||||
fd.Close()
|
||||
return err
|
||||
}
|
||||
cur, _ := nv550ToIMEI(curData)
|
||||
fmt.Fprintf(os.Stderr, "当前 IMEI: %s\n", orNA(cur))
|
||||
wrote := false
|
||||
if cur == imei && os.Getenv("IMEITOOL_FORCE") != "1" {
|
||||
fmt.Fprintf(os.Stderr, "IMEI 已一致,不重复写入。\n")
|
||||
} else {
|
||||
spcUnlock(fd)
|
||||
fmt.Fprintf(os.Stderr, "正在写入 IMEI %s ...\n", imei)
|
||||
if err := nvWrite(fd, nvItemIMEI, imeiToNV550(imei)); err != nil {
|
||||
fd.Close()
|
||||
return err
|
||||
}
|
||||
gotData, err := nvRead(fd, nvItemIMEI)
|
||||
if err != nil {
|
||||
fd.Close()
|
||||
return err
|
||||
}
|
||||
got, _ := nv550ToIMEI(gotData)
|
||||
if got != imei {
|
||||
fd.Close()
|
||||
return fmt.Errorf("写后校验失败,读回 %s", orNA(got))
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "NV 写入已校验。\n")
|
||||
wrote = true
|
||||
}
|
||||
fd.Close()
|
||||
if err := os.WriteFile(imeiConf, []byte(imei+"\n"), 0644); err != nil {
|
||||
return fmt.Errorf("写入 %s: %w", imeiConf, err)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "已保存到 %s,开机后会重新写入。\n", imeiConf)
|
||||
if wrote {
|
||||
restartModemManager()
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "完成。当前 IMEI 为 %s\n", imei)
|
||||
return nil
|
||||
}
|
||||
|
||||
func orNA(s string) string {
|
||||
if s == "" {
|
||||
return "N/A"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func openDiag() (*os.File, error) {
|
||||
before := rpmsgNodes()
|
||||
ctrl, err := os.OpenFile(rpmsgCtrl, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("打开 %s: %w", rpmsgCtrl, err)
|
||||
}
|
||||
info := rpmsgEptInfo{Src: 0xFFFFFFFF, Dst: 0xFFFFFFFF}
|
||||
copy(info.Name[:], "DIAG")
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, ctrl.Fd(), uintptr(rpmsgCreateEpt), uintptr(unsafe.Pointer(&info)))
|
||||
ctrl.Close()
|
||||
if errno != 0 {
|
||||
return nil, fmt.Errorf("创建 DIAG 端点: %w", errno)
|
||||
}
|
||||
var dev string
|
||||
for i := 0; i < 20; i++ {
|
||||
for n := range rpmsgNodes() {
|
||||
if !before[n] {
|
||||
dev = n
|
||||
}
|
||||
}
|
||||
if dev != "" {
|
||||
break
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
if dev == "" {
|
||||
return nil, fmt.Errorf("未出现新的 rpmsg 端点")
|
||||
}
|
||||
fd, err := os.OpenFile(dev, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("打开 %s: %w", dev, err)
|
||||
}
|
||||
_ = fd.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
if _, err := fd.Read(buf); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return fd, nil
|
||||
}
|
||||
|
||||
func rpmsgNodes() map[string]bool {
|
||||
matches, _ := filepath.Glob("/dev/rpmsg[0-9]*")
|
||||
sort.Slice(matches, func(i, j int) bool {
|
||||
return rpmsgNum(matches[i]) < rpmsgNum(matches[j])
|
||||
})
|
||||
out := make(map[string]bool, len(matches))
|
||||
for _, m := range matches {
|
||||
base := filepath.Base(m)
|
||||
if strings.Contains(base, "ctrl") {
|
||||
continue
|
||||
}
|
||||
out[m] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func rpmsgNum(path string) int {
|
||||
base := filepath.Base(path)
|
||||
n, _ := strconv.Atoi(strings.TrimPrefix(base, "rpmsg"))
|
||||
return n
|
||||
}
|
||||
|
||||
func diagCmd(fd *os.File, pkt []byte, timeout time.Duration) ([]byte, error) {
|
||||
if _, err := fd.Write(pkt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
buf := make([]byte, 8192)
|
||||
for {
|
||||
left := time.Until(deadline)
|
||||
if left <= 0 {
|
||||
return nil, fmt.Errorf("超时")
|
||||
}
|
||||
_ = fd.SetReadDeadline(time.Now().Add(left))
|
||||
n, err := fd.Read(buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp := append([]byte(nil), buf[:n]...)
|
||||
if len(resp) > 1 && resp[0] != pkt[0] && resp[1] == pkt[0] {
|
||||
resp = resp[1:]
|
||||
}
|
||||
if len(resp) == 0 || resp[0] != pkt[0] {
|
||||
continue
|
||||
}
|
||||
if pkt[0] == 0x4B && len(pkt) >= 4 && len(resp) >= 4 {
|
||||
want := int(pkt[2]) | int(pkt[3])<<8
|
||||
got := int(resp[2]) | int(resp[3])<<8
|
||||
if got != want {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// rpmsg 有时会把刚写出去的请求原样读回,继续等基带的真正应答。
|
||||
if len(resp) <= len(pkt) && bytes.Equal(resp, pkt[:len(resp)]) {
|
||||
continue
|
||||
}
|
||||
if len(resp) >= 4 && resp[len(resp)-1] == 0x7e {
|
||||
resp = resp[:len(resp)-3]
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func putU16(b []byte, v int) {
|
||||
b[0] = byte(v)
|
||||
b[1] = byte(v >> 8)
|
||||
}
|
||||
|
||||
func putU32(b []byte, v uint32) {
|
||||
b[0] = byte(v)
|
||||
b[1] = byte(v >> 8)
|
||||
b[2] = byte(v >> 16)
|
||||
b[3] = byte(v >> 24)
|
||||
}
|
||||
|
||||
func u32(b []byte) uint32 {
|
||||
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
|
||||
}
|
||||
|
||||
func efsHeader(subcmd int) []byte {
|
||||
b := []byte{0x4B, 0x13, 0, 0}
|
||||
putU16(b[2:], subcmd)
|
||||
return b
|
||||
}
|
||||
|
||||
func efsHello(fd *os.File) error {
|
||||
pkt := append(efsHeader(0), make([]byte, 28)...)
|
||||
putU32(pkt[4:], 0x100)
|
||||
putU32(pkt[8:], 0x10)
|
||||
putU32(pkt[12:], 0x100)
|
||||
putU32(pkt[16:], 0x10)
|
||||
putU32(pkt[20:], 1)
|
||||
putU32(pkt[24:], 1)
|
||||
putU32(pkt[28:], 0xFFFFFFFF)
|
||||
resp, err := diagCmd(fd, pkt, 3*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("EFS HELLO: %w", err)
|
||||
}
|
||||
fmt.Printf("HELLO %s\n", hexBytes(resp))
|
||||
return nil
|
||||
}
|
||||
|
||||
func efsSync(fd *os.File) error {
|
||||
pkt := append(efsHeader(26), 0, 0, 0, 0)
|
||||
resp, err := diagCmd(fd, pkt, 3*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("SYNC %s\n", hexBytes(resp))
|
||||
return nil
|
||||
}
|
||||
|
||||
func efsStat(fd *os.File, path string) ([]byte, error) {
|
||||
pkt := append(efsHeader(15), path...)
|
||||
pkt = append(pkt, 0)
|
||||
return diagCmd(fd, pkt, 3*time.Second)
|
||||
}
|
||||
|
||||
func efsPut(fd *os.File, path string, data []byte, oflag uint32) error {
|
||||
pkt := append(efsHeader(2), 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
putU32(pkt[4:], oflag)
|
||||
putU32(pkt[8:], 0644)
|
||||
pkt = append(pkt, path...)
|
||||
pkt = append(pkt, 0)
|
||||
resp, err := diagCmd(fd, pkt, 3*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("打开超时: %w", err)
|
||||
}
|
||||
if len(resp) < 12 {
|
||||
return fmt.Errorf("打开响应过短 %s", hexBytes(resp))
|
||||
}
|
||||
fdnum := u32(resp[4:8])
|
||||
errno := u32(resp[8:12])
|
||||
if errno != 0 || fdnum > 64 {
|
||||
return fmt.Errorf("打开失败 fd=%d err=%d len=%d %s", fdnum, errno, len(resp), hexBytes(resp))
|
||||
}
|
||||
wp := append(efsHeader(5), 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
putU32(wp[4:], fdnum)
|
||||
putU32(wp[8:], 0)
|
||||
wp = append(wp, data...)
|
||||
wr, err := diagCmd(fd, wp, 3*time.Second)
|
||||
cp := append(efsHeader(3), 0, 0, 0, 0)
|
||||
putU32(cp[4:], fdnum)
|
||||
_, _ = diagCmd(fd, cp, 2*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("写入超时: %w", err)
|
||||
}
|
||||
if len(wr) >= 12 && u32(wr[8:12]) != 0 && u32(wr[4:8]) == 0 {
|
||||
return fmt.Errorf("写入失败 %s", hexBytes(wr[:16]))
|
||||
}
|
||||
fmt.Printf("WRITE %s\n", hexBytes(wr))
|
||||
return nil
|
||||
}
|
||||
|
||||
func hexBytes(b []byte) string {
|
||||
if len(b) > 48 {
|
||||
b = b[:48]
|
||||
}
|
||||
s := make([]byte, 0, len(b)*2)
|
||||
const hexd = "0123456789abcdef"
|
||||
for _, c := range b {
|
||||
s = append(s, hexd[c>>4], hexd[c&0x0f])
|
||||
}
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func nvRead(fd *os.File, item int) ([]byte, error) {
|
||||
pkt := make([]byte, 133)
|
||||
pkt[0] = diagNvRead
|
||||
pkt[1] = byte(item)
|
||||
pkt[2] = byte(item >> 8)
|
||||
resp, err := diagCmd(fd, pkt, 5*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读 NV %d: %w", item, err)
|
||||
}
|
||||
if len(resp) >= 2 && resp[0] != diagNvRead && resp[1] == diagNvRead {
|
||||
resp = resp[1:]
|
||||
}
|
||||
if len(resp) < 133 {
|
||||
return nil, fmt.Errorf("读 NV %d: 响应过短 (%d)", item, len(resp))
|
||||
}
|
||||
status := int(resp[131]) | int(resp[132])<<8
|
||||
if resp[0] != diagNvRead || status != 0 {
|
||||
return nil, fmt.Errorf("读 NV %d 失败: cmd=0x%02x status=%d", item, resp[0], status)
|
||||
}
|
||||
out := make([]byte, 128)
|
||||
copy(out, resp[3:131])
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func nvWrite(fd *os.File, item int, data []byte) error {
|
||||
pkt := make([]byte, 133)
|
||||
pkt[0] = diagNvWrite
|
||||
pkt[1] = byte(item)
|
||||
pkt[2] = byte(item >> 8)
|
||||
copy(pkt[3:131], data)
|
||||
resp, err := diagCmd(fd, pkt, 5*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("写 NV %d: %w", item, err)
|
||||
}
|
||||
if len(resp) >= 2 && resp[0] != diagNvWrite && resp[1] == diagNvWrite {
|
||||
resp = resp[1:]
|
||||
}
|
||||
if len(resp) < 133 {
|
||||
return fmt.Errorf("写 NV %d: 响应过短 (%d)", item, len(resp))
|
||||
}
|
||||
status := int(resp[131]) | int(resp[132])<<8
|
||||
if resp[0] != diagNvWrite || status != 0 {
|
||||
return fmt.Errorf("写 NV %d 失败: cmd=0x%02x status=%d", item, resp[0], status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func spcUnlock(fd *os.File) {
|
||||
pkt := make([]byte, 8)
|
||||
pkt[0] = diagSpc
|
||||
copy(pkt[1:], "000000")
|
||||
resp, err := diagCmd(fd, pkt, 5*time.Second)
|
||||
if err != nil || len(resp) < 2 || resp[1] != 1 {
|
||||
fmt.Fprintf(os.Stderr, "SPC 解锁未确认,继续尝试写入。\n")
|
||||
}
|
||||
}
|
||||
|
||||
func imeiToNV550(imei string) []byte {
|
||||
d := imei
|
||||
nv := []byte{0x08, byte((d[0]-'0')<<4) | 0x0A}
|
||||
for i := 0; i < 7; i++ {
|
||||
nv = append(nv, byte((d[2+i*2]-'0')<<4)|byte(d[1+i*2]-'0'))
|
||||
}
|
||||
return nv
|
||||
}
|
||||
|
||||
func nv550ToIMEI(nv []byte) (string, bool) {
|
||||
if len(nv) < 9 || nv[0] != 0x08 {
|
||||
return "", false
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteByte('0' + (nv[1] >> 4))
|
||||
for i := 2; i <= 8; i++ {
|
||||
b.WriteByte('0' + (nv[i] & 0x0F))
|
||||
b.WriteByte('0' + (nv[i] >> 4))
|
||||
}
|
||||
s := b.String()
|
||||
if len(s) < 15 {
|
||||
return "", false
|
||||
}
|
||||
return s[:15], true
|
||||
}
|
||||
|
||||
func restartModemManager() {
|
||||
script := "/etc/init.d/modemmanager"
|
||||
if _, err := os.Stat(script); err == nil {
|
||||
fmt.Fprintf(os.Stderr, "正在重启 ModemManager...\n")
|
||||
_ = exec.Command(script, "restart").Run()
|
||||
return
|
||||
}
|
||||
if exec.Command("systemctl", "is-active", "--quiet", "ModemManager").Run() == nil {
|
||||
fmt.Fprintf(os.Stderr, "正在重启 ModemManager...\n")
|
||||
_ = exec.Command("systemctl", "restart", "ModemManager").Run()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user