From 7e577d27937340a91b858ff2d4fca3e38b56b308 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 13:27:22 +0800 Subject: [PATCH 01/39] feat(modem): support ML307C discovery and AT runtime --- internal/api/device_mgmt.go | 11 +- internal/device/at_port_resolver.go | 20 ++++ internal/device/backend_init.go | 4 +- internal/device/discovery_compat.go | 33 +++++- internal/device/discovery_enrichment.go | 40 +++++-- internal/device/mbim_bootstrap_test.go | 3 +- internal/device/ml307c_discovery_test.go | 84 ++++++++++++++ internal/device/pool.go | 71 ++++++++++-- internal/device/pool_at_identity.go | 5 + internal/device/pool_bootstrap.go | 30 +++-- internal/device/pool_health_ip.go | 6 +- internal/device/pool_reboot_recovery.go | 5 + internal/device/pool_rescan_collect_test.go | 4 +- internal/device/pool_rescan_guard.go | 3 + internal/device/pool_rescan_identity_test.go | 2 +- internal/device/pool_rescan_nonqmi_test.go | 2 +- internal/device/pool_state.go | 4 + internal/device/sim_removal.go | 26 +++++ internal/device/sim_removal_test.go | 77 ++++++++++++ internal/device/sms_identity.go | 3 + internal/device/usb_at_port_rules.go | 19 +++ internal/modem/at_parse.go | 12 +- internal/modem/at_profile.go | 116 +++++++++++++++++++ internal/modem/at_profile_test.go | 97 ++++++++++++++++ internal/modem/commands.go | 49 ++++++-- internal/modem/imei_cache_test.go | 10 +- internal/modem/imei_probe.go | 43 ++++--- internal/modem/manager.go | 46 ++++++-- internal/modem/runtime_role.go | 2 +- 29 files changed, 745 insertions(+), 82 deletions(-) create mode 100644 internal/device/ml307c_discovery_test.go create mode 100644 internal/modem/at_profile.go create mode 100644 internal/modem/at_profile_test.go diff --git a/internal/api/device_mgmt.go b/internal/api/device_mgmt.go index 7d4eb054..96cbbc7c 100644 --- a/internal/api/device_mgmt.go +++ b/internal/api/device_mgmt.go @@ -1220,7 +1220,16 @@ func (s *Server) useDeviceMgmtDiscovered(c businessContext) { resolvedATPort := strings.TrimSpace(dev.ATPort) imei := strings.TrimSpace(dev.IMEI) - if withIMEI { + if withIMEI && dev.ATProfile() == modem.ATProfileML307C { + var owned bool + dev, owned = managedIndex.ReadOwnedATIdentity(dev) + if !owned { + dev, _ = enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{ + EnableATProbe: true, ATProbeTimeout: 900 * time.Millisecond, + }) + } + resolvedATPort, imei = dev.ATPort, dev.IMEI + } else if withIMEI { managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface)) if hasManaged { if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) { diff --git a/internal/device/at_port_resolver.go b/internal/device/at_port_resolver.go index d63f33dc..84953f49 100644 --- a/internal/device/at_port_resolver.go +++ b/internal/device/at_port_resolver.go @@ -11,6 +11,7 @@ import ( // probeIMEICachedFn 允许测试替换底层 IMEI 探测实现。 var probeIMEICachedFn = modem.ProbeIMEICached var probeIMEICachedContextFn = modem.ProbeIMEICachedContext +var probeProfileIMEICachedFn = modem.ATProfile.ProbeIMEICached // orderedATPortCandidates 按“单设备定界”规则生成探测顺序。 // 只允许在当前设备自己的 ATPorts 集合内排序和前置候选口; @@ -94,6 +95,9 @@ func ResolveQMIDeviceATPort(dev QMIDevice, timeout time.Duration) (QMIDevice, st // ResolveCompatibleModemATPort 为兼容发现结果解析真实可用的主 AT 口。 // 行为与 QMI 设备一致,同样只允许在该设备自己的 ATPorts 范围内探测。 func ResolveCompatibleModemATPort(dev CompatibleModem, timeout time.Duration) (CompatibleModem, string) { + if dev.ATProfile() == modem.ATProfileML307C { + return ResolveCompatibleModemATPortContext(context.Background(), dev, timeout) + } atPort, imei := ResolveATPortForDevice(dev.ATPort, dev.ATPorts, timeout) dev.ATPort = atPort if imei != "" { @@ -108,6 +112,22 @@ func ResolveCompatibleModemATPortContext( dev CompatibleModem, timeout time.Duration, ) (CompatibleModem, string) { + profile := dev.ATProfile() + if profile == modem.ATProfileML307C { + preferred := dev.ATPort + dev.ATPort, dev.IMEI = "", "" + for _, port := range orderedATPortCandidates(preferred, dev.ATPorts) { + imei, err := probeProfileIMEICachedFn(profile, ctx, port, timeout) + if err == nil && imei != "" { + dev.ATPort, dev.IMEI = port, imei + return dev, imei + } + if ctx.Err() != nil { + break + } + } + return dev, "" + } atPort, imei := ResolveATPortForDeviceContext(ctx, dev.ATPort, dev.ATPorts, timeout) dev.ATPort = atPort if imei != "" { diff --git a/internal/device/backend_init.go b/internal/device/backend_init.go index e45e5801..e2b11085 100644 --- a/internal/device/backend_init.go +++ b/internal/device/backend_init.go @@ -9,11 +9,11 @@ import ( "github.com/yibaiba/hideck/internal/modem" ) -func newWorkerModem(cfg config.DeviceConfig, backendMode string) (*modem.Manager, error) { +func newWorkerModem(cfg config.DeviceConfig, backendMode string, profile modem.ATProfile) (*modem.Manager, error) { if backend.NormalizeBackendMode(backendMode) == backend.BackendMBIM { return modem.NewSMSAuxiliary(cfg) } - return modem.New(cfg) + return modem.NewWithATProfile(cfg, profile) } func newWorkerBackendStrict(deviceID, backendMode, controlDevice string, m *modem.Manager, source backend.QMISource, mbimSource backend.MBIMSource) (backend.DeviceBackend, error) { diff --git a/internal/device/discovery_compat.go b/internal/device/discovery_compat.go index 7694493c..d0d63f79 100644 --- a/internal/device/discovery_compat.go +++ b/internal/device/discovery_compat.go @@ -10,6 +10,7 @@ import ( "time" "github.com/iniwex5/quectel-qmi-go/pkg/qmi" + "github.com/yibaiba/hideck/internal/modem" qmicore "github.com/yibaiba/hideck/internal/qmi" "github.com/yibaiba/hideck/pkg/logger" ) @@ -31,6 +32,13 @@ type CompatibleModem struct { NetworkCapable bool } +func (m CompatibleModem) ATProfile() modem.ATProfile { + if (usbDeviceIdentity{vendorID: m.VendorID, productID: m.ProductID}).isML307C() { + return modem.ATProfileML307C + } + return modem.ATProfileDefault +} + var discoverFallbackModemsFn = discoverFallbackModems // DiscoveryKey 用于去重 (USBPath + ATPort)。 @@ -144,10 +152,18 @@ func compatibleModemFromQMIStaticDevice(d QMIDevice) CompatibleModem { func discoverFallbackOne(usbPath string) (CompatibleModem, bool) { scanUSBPath := resolveUSBPathForScan(usbPath) - - vid := readHexFile16(filepath.Join(scanUSBPath, "idVendor")) - pid := readHexFile16(filepath.Join(scanUSBPath, "idProduct")) - identity := usbDeviceIdentity{vendorID: vid, productID: pid} + identity := readUSBDeviceIdentity(scanUSBPath) + vid, pid := identity.vendorID, identity.productID + if identity.isML307C() { + ports, port, _ := discoverATPortsForUSBDevice(scanUSBPath, identity, "at") + if port == "" { + return CompatibleModem{}, false + } + return CompatibleModem{ + USBPath: usbPath, VendorID: vid, ProductID: pid, + ATPorts: ports, ATPort: port, Mode: "at", TransportType: "at", + }, true + } if capability, ok := detectQMIUSBCapability(scanUSBPath); ok { mode := classifyMode(capability.ControlPath, capability.DriverName) atPorts, atPort, imei := discoverATPortsForUSBDevice(scanUSBPath, identity, mode) @@ -187,7 +203,7 @@ func discoverFallbackOne(usbPath string) (CompatibleModem, bool) { }, true } - if vid != 0x2c7c && vid != 0x05c6 { + if vid != quectelVendorID && vid != qualcommVendorID { return CompatibleModem{}, false } @@ -281,6 +297,13 @@ func resolveUSBPathForScan(usbPath string) string { return resolved } +func readUSBDeviceIdentity(usbPath string) usbDeviceIdentity { + return usbDeviceIdentity{ + vendorID: readHexFile16(filepath.Join(usbPath, "idVendor")), + productID: readHexFile16(filepath.Join(usbPath, "idProduct")), + } +} + func readHexFile16(path string) uint16 { b, err := os.ReadFile(path) if err != nil { diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index 493002d2..3cc98a4e 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -6,6 +6,7 @@ import ( qmiq "github.com/iniwex5/quectel-qmi-go/pkg/qmi" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -186,16 +187,18 @@ type WorkerDiscoveryInfo struct { } type WorkerDiscoveryIndex struct { - byControl map[string]WorkerDiscoveryInfo - byUSB map[string]WorkerDiscoveryInfo - byIface map[string]WorkerDiscoveryInfo + byControl map[string]WorkerDiscoveryInfo + byUSB map[string]WorkerDiscoveryInfo + byIface map[string]WorkerDiscoveryInfo + atIdentityByPort map[string]func() (string, error) } func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) WorkerDiscoveryIndex { idx := WorkerDiscoveryIndex{ - byControl: map[string]WorkerDiscoveryInfo{}, - byUSB: map[string]WorkerDiscoveryInfo{}, - byIface: map[string]WorkerDiscoveryInfo{}, + byControl: map[string]WorkerDiscoveryInfo{}, + byUSB: map[string]WorkerDiscoveryInfo{}, + byIface: map[string]WorkerDiscoveryInfo{}, + atIdentityByPort: map[string]func() (string, error){}, } for _, worker := range workers { @@ -211,7 +214,10 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor ATPort: strings.TrimSpace(cfg.ATPort), IMEI: strings.TrimSpace(cfg.ModemIMEI), } - if includeRuntimeStatus { + if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" { + idx.atIdentityByPort[worker.ResolvedATPort()] = worker.Modem.QueryIMEI + } + if includeRuntimeStatus && (worker.Modem == nil || worker.Modem.ATProfile() != modem.ATProfileML307C) { status := worker.GetDeviceStatus() if imei := strings.TrimSpace(status.IMEI); imei != "" { info.IMEI = imei @@ -261,6 +267,26 @@ func (idx WorkerDiscoveryIndex) Lookup(controlPath, usbPath, iface string) (Work return WorkerDiscoveryInfo{}, false } +// ReadOwnedATIdentity queries the manager already holding a candidate port. +// A failed query still counts as owned until the old worker is retired. +func (idx WorkerDiscoveryIndex) ReadOwnedATIdentity(dev CompatibleModem) (CompatibleModem, bool) { + if dev.ATProfile() != modem.ATProfileML307C { + return dev, false + } + for _, port := range dev.ATPorts { + query := idx.atIdentityByPort[port] + if query == nil { + continue + } + dev.ATPort, dev.IMEI = port, "" + if imei, err := query(); err == nil { + dev.IMEI = imei + } + return dev, true + } + return dev, false +} + type ConfiguredDeviceIndex struct { byControl map[string]string byUSB map[string]string diff --git a/internal/device/mbim_bootstrap_test.go b/internal/device/mbim_bootstrap_test.go index a102bb06..a1974475 100644 --- a/internal/device/mbim_bootstrap_test.go +++ b/internal/device/mbim_bootstrap_test.go @@ -6,6 +6,7 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" ) func TestRequiresMBIMCore(t *testing.T) { @@ -48,7 +49,7 @@ func TestNewWorkerModemUsesSMSAuxiliaryForMBIM(t *testing.T) { ID: "dev-mbim", DeviceBackend: backend.BackendMBIM, ATPort: "/dev/ttyUSB2", - }, backend.BackendMBIM) + }, backend.BackendMBIM, modem.ATProfileDefault) if err != nil { t.Fatalf("newWorkerModem() error = %v", err) } diff --git a/internal/device/ml307c_discovery_test.go b/internal/device/ml307c_discovery_test.go new file mode 100644 index 00000000..1fec16e5 --- /dev/null +++ b/internal/device/ml307c_discovery_test.go @@ -0,0 +1,84 @@ +package device + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" +) + +func TestML307CDiscoveryAndRebind(t *testing.T) { + usbPath := filepath.Join(t.TempDir(), "1-1") + for _, node := range []string{"1-1:1.2/ttyUSB8", "1-1:1.3/ttyUSB2", "1-1:1.4/ttyUSB3"} { + if err := os.MkdirAll(filepath.Join(usbPath, node), 0o700); err != nil { + t.Fatal(err) + } + } + for name, value := range map[string]string{"idVendor": "2ecc\n", "idProduct": "3012\n"} { + if err := os.WriteFile(filepath.Join(usbPath, name), []byte(value), 0o600); err != nil { + t.Fatal(err) + } + } + + dev, ok := discoverFallbackOne(usbPath) + if !ok || dev.Mode != "at" || dev.NetworkCapable || dev.ControlPath != "" || dev.ATProfile() != modem.ATProfileML307C { + t.Fatalf("discovery = %+v, %v", dev, ok) + } + if dev.ATPort != "/dev/ttyUSB8" || !slices.Equal(dev.ATPorts, []string{"/dev/ttyUSB8", "/dev/ttyUSB2"}) { + t.Fatalf("ATPort=%q ATPorts=%v", dev.ATPort, dev.ATPorts) + } + + const imei = "490154203237518" + owned := WorkerDiscoveryIndex{atIdentityByPort: map[string]func() (string, error){ + "/dev/ttyUSB8": func() (string, error) { return imei, nil }, + }} + active, ok := owned.ReadOwnedATIdentity(dev) + if !ok || active.IMEI != imei { + t.Fatalf("owned IMEI = %q, %v", active.IMEI, ok) + } + owned.atIdentityByPort["/dev/ttyUSB8"] = func() (string, error) { return "", errors.New("old tty closed") } + dev.IMEI = imei + active, ok = owned.ReadOwnedATIdentity(dev) + if !ok || active.IMEI != "" { + t.Fatalf("stale owned tty = %q, %v", active.IMEI, ok) + } + + origProbe := probeProfileIMEICachedFn + t.Cleanup(func() { probeProfileIMEICachedFn = origProbe }) + var probed []string + probeProfileIMEICachedFn = func(profile modem.ATProfile, _ context.Context, port string, _ time.Duration) (string, error) { + if profile != modem.ATProfileML307C { + t.Fatalf("IMEI probe profile = %v", profile) + } + probed = append(probed, port) + if port == "/dev/ttyUSB2" { + return imei, nil + } + return "", errors.New("no IMEI") + } + + rebound, readIMEI := ResolveCompatibleModemATPort(dev, time.Second) + if readIMEI != imei || !slices.Equal(probed, dev.ATPorts) { + t.Fatalf("rebind IMEI = %q, ports = %v", readIMEI, probed) + } + cfg := rescanWorkerConfig(config.DeviceConfig{ID: "c", DeviceBackend: "at", ModemIMEI: imei, ATPort: "/dev/ttyUSB0"}, rebound) + if cfg.USBPath != usbPath || cfg.ATPort != "/dev/ttyUSB2" || cfg.ManagePort != cfg.ATPort { + t.Fatalf("rebind USBPath=%q ATPort=%q ManagePort=%q", cfg.USBPath, cfg.ATPort, cfg.ManagePort) + } + + if err := os.RemoveAll(filepath.Join(usbPath, "1-1:1.2")); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(filepath.Join(usbPath, "1-1:1.3")); err != nil { + t.Fatal(err) + } + if _, ok := discoverFallbackOne(usbPath); ok { + t.Fatal("Diag alone must not be discovered as an ML307C AT port") + } +} diff --git a/internal/device/pool.go b/internal/device/pool.go index 43522a03..cbc1529e 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -679,6 +679,19 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI defer cancel() } + if w.isML307C() { + inserted, err := w.Backend.IsSimInserted(ctx) + if err != nil { + if errors.Is(err, modem.ErrSIMPINRequired) && (w.Pool == nil || !w.Pool.IsESIMSwitching(w.ID)) { + w.markSIMPINRequired() + } + return liveSIMIdentityRefreshResult{}, err + } + if !inserted { + return liveSIMIdentityRefreshResult{}, errATNoSIM + } + } + iccid, imsi, nativeSPN := "", "", "" var simMetadata *backend.SIMMetadata spnReadOK, metadataReadOK := false, false @@ -725,6 +738,9 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI } } } + if w.isML307C() && (iccid == "" || imsi == "") { + return liveSIMIdentityRefreshResult{}, errors.New("live_identity_incomplete") + } _, snapshotSupported := w.Backend.(liveSIMIdentitySnapshotReader) if !snapshotSupported && (simMetadata == nil || strings.TrimSpace(simMetadata.NativeMCC) == "" || @@ -745,7 +761,7 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI } } imei := "" - if iccid == "" || imsi == "" { + if (iccid == "" || imsi == "") && !w.isML307C() { if ident, atErr := probeWorkerATIdentity(ctx, w); atErr == nil { if iccid == "" { iccid = strings.TrimSpace(ident.ICCID) @@ -1022,10 +1038,28 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s if p == nil || owner.worker == nil || !p.workerLifecycleOwnerCurrent(owner) { return } - if insertedHint != nil && *insertedHint { - return - } - if strings.EqualFold(strings.TrimSpace(state), "READY") { + state = strings.ToUpper(strings.TrimSpace(state)) + if owner.worker.isML307C() { + if modem.IsSIMPINRequiredState(state) { + p.handleSIMPINRequired(owner) + return + } + if insertedHint != nil { + if *insertedHint && !owner.worker.SIMIdentityConvergenceMatches("", 0) { + return + } + if !*insertedHint { + owner.worker.cacheMu.RLock() + confirmedAbsent := owner.worker.state.Identity.LastError == "sim_removed" + owner.worker.cacheMu.RUnlock() + if confirmedAbsent { + return + } + } + } else if state != "READY" && state != "SIM REMOVED" && state != "SIM NOT INSERTED" { + return + } + } else if (insertedHint != nil && *insertedHint) || state == "READY" { return } deviceID := owner.worker.ID @@ -1186,6 +1220,10 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { transition.Unlock() + if w.isML307C() && errors.Is(err, modem.ErrSIMPINRequired) { + p.handleSIMPINRequired(owner) + return + } logger.Warn("SIM 拔卡确认失败,跳过 VoWiFi 自动停止", "device", deviceID, "source", source, "err", err) return } @@ -1234,6 +1272,10 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st } p.broadcastVoWiFiStateChange(w.ID) if result.err != nil { + if w.isML307C() && errors.Is(result.err, modem.ErrSIMPINRequired) { + p.handleSIMPINRequired(owner) + return + } logger.Warn("SIM 插入后刷新身份失败", "device", w.ID, "source", source, "err", result.err) return } @@ -1908,7 +1950,7 @@ func (p *Pool) RescanAndReconnect() error { return p.rescanAndReconnect(rescanReconnectOptions{}) } -func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex) []CompatibleModem { +func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scanCompatibleAT bool) []CompatibleModem { var hardware []CompatibleModem for i := range discovered { raw := discovered[i] @@ -1935,8 +1977,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor }) } - managed := config.ListDevices() - if configuredDevicesNeedCompatibleATDiscovery(managed) { + if scanCompatibleAT { if compatList, err := DiscoverCompatibleModemsFromQMI(discovered); err == nil { seen := map[string]bool{} for _, hw := range hardware { @@ -1945,7 +1986,11 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor } } for _, raw := range compatList { - m, imei := resolveDiscoveredCompatibleModemFn(raw, 1200*time.Millisecond) + m, owned := liveWorkerIndex.ReadOwnedATIdentity(raw) + imei := m.IMEI + if !owned { + m, imei = resolveDiscoveredCompatibleModemFn(raw, 1200*time.Millisecond) + } if config.NormalizeIMEI(imei) == "" { continue } @@ -1971,7 +2016,7 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { } liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex) + hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) managed := p.managedDevices() modemDevices, pcscDevices := partitionManagedDevices(managed) resolved := ResolveDeviceIdentities(hardware, modemDevices) @@ -2673,7 +2718,11 @@ func (p *Pool) PersistRuntimeState(worker *Worker) { } // 更新 Device 表 - if err := db.UpsertDevice(imei, worker.ID, "EC20", worker.Config.ATPort); err != nil { + model := "EC20" + if worker.isML307C() { + model = "ML307C" + } + if err := db.UpsertDevice(imei, worker.ID, model, worker.Config.ATPort); err != nil { logger.Warn(fmt.Sprintf("[%s] 更新设备信息失败", worker.ID), "err", err) } } diff --git a/internal/device/pool_at_identity.go b/internal/device/pool_at_identity.go index 981fed5c..baad0615 100644 --- a/internal/device/pool_at_identity.go +++ b/internal/device/pool_at_identity.go @@ -10,6 +10,11 @@ import ( ) var errATIdentityUnavailable = errors.New("at identity unavailable") +var errATNoSIM = errors.New("AT modem has no SIM") + +func (w *Worker) isML307C() bool { + return w != nil && w.Modem != nil && w.Modem.ATProfile() == modem.ATProfileML307C +} var probeATIdentityFn = modem.ProbeATIdentity diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index a9dcc1a8..0b44ca75 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -13,6 +13,7 @@ import ( "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/esim" mbimcore "github.com/yibaiba/hideck/internal/mbim" + "github.com/yibaiba/hideck/internal/modem" qmicore "github.com/yibaiba/hideck/internal/qmi" "github.com/yibaiba/hideck/pkg/logger" "github.com/yibaiba/hideck/pkg/smscodec" @@ -270,16 +271,24 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) } var matched *QMIDevice + var atProfile modem.ATProfile discoveryCache := &qmiBootstrapDiscoveryCache{} liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) configuredIndex := BuildConfiguredDeviceIndex(config.ListDevices()) if !needsQMICore { - liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), true) - hardware := p.collectRescanHardware(nil, liveWorkerIndex) + scanAT := configuredDevicesNeedCompatibleATDiscovery(config.ListDevices()) || + (resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "") + hardware := p.collectRescanHardware(nil, liveWorkerIndex, scanAT) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware + atProfile = hw.ATProfile() + if atProfile == modem.ATProfileML307C { + devCfg.USBPath = hw.USBPath + devCfg.ATPort = hw.ATPort + devCfg.ManagePort = hw.ATPort + } if devCfg.Interface == "" { devCfg.Interface = hw.NetInterface } @@ -298,10 +307,10 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) devCfg.ModemIMEI = resolved.Matched[0].BackfillIMEI logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI) } - } else { - if strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "" { - return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") - } + } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || + (resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "" && + strings.TrimSpace(devCfg.USBPath) != "" && readUSBDeviceIdentity(resolveUSBPathForScan(devCfg.USBPath)).isML307C()) { + return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") } } else if hasManagedQMINetwork(devCfg) { configuredStatic := QMIDevice{ @@ -317,7 +326,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) if qmiErr != nil { logger.Debug("QMI 静态路径启动前发现失败", "device", devCfg.ID, "err", qmiErr) } else { - hardware := p.collectRescanHardware(qmiList, liveWorkerIndex) + hardware := p.collectRescanHardware(qmiList, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware @@ -370,7 +379,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) } backendMode := resolvedBackendMode(devCfg) - m, err := newWorkerModem(devCfg, backendMode) + m, err := newWorkerModem(devCfg, backendMode, atProfile) if err != nil { return nil, fmt.Errorf("初始化 Modem 失败: %w", err) } @@ -571,6 +580,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) p.scheduleATDisconnectRecovery(owner, reason) }) p.bindModemReadyIndications(w) + if atProfile == modem.ATProfileML307C { + m.SetSIMStatusHandler(func(inserted *bool, state string) { + p.handleSIMStatusEventForOwner(owner, "ml307c_sim_status", inserted, state) + }) + } } if backendMode == backend.BackendQMI { diff --git a/internal/device/pool_health_ip.go b/internal/device/pool_health_ip.go index 8afab5c8..d57150f1 100644 --- a/internal/device/pool_health_ip.go +++ b/internal/device/pool_health_ip.go @@ -2,6 +2,7 @@ package device import ( "context" + "errors" "fmt" "os" "strings" @@ -510,8 +511,11 @@ func (w *Worker) PreWarmCache() { return } _ = w.RefreshRuntime(nil, "prewarm") - _ = w.RefreshIdentityLive(nil, "prewarm") + identityErr := w.RefreshIdentityLive(nil, "prewarm") if w.Pool != nil { + if errors.Is(identityErr, errATNoSIM) { + w.Pool.confirmSIMRemovedForOwner(w.Pool.captureWorkerLifecycleOwner(w.ID), "ml307c_startup", nil) + } w.Pool.PersistRuntimeState(w) w.Pool.PersistIdentityState(w) } diff --git a/internal/device/pool_reboot_recovery.go b/internal/device/pool_reboot_recovery.go index 401077dd..1de0b0bc 100644 --- a/internal/device/pool_reboot_recovery.go +++ b/internal/device/pool_reboot_recovery.go @@ -1,6 +1,7 @@ package device import ( + "errors" "fmt" "os" "strings" @@ -8,6 +9,7 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -42,6 +44,9 @@ func (p *Pool) refreshModemRebootRecoveredIdentity(w *Worker, reason string) err } result, err := p.refreshIdentityAndApplyCardPolicy(w, reason) + if errors.Is(err, errATNoSIM) || errors.Is(err, modem.ErrSIMPINRequired) { + return nil + } if err != nil { return fmt.Errorf("refresh_identity: %w", err) } diff --git a/internal/device/pool_rescan_collect_test.go b/internal/device/pool_rescan_collect_test.go index f851d3f6..860ed033 100644 --- a/internal/device/pool_rescan_collect_test.go +++ b/internal/device/pool_rescan_collect_test.go @@ -31,7 +31,7 @@ func TestCollectRescanHardwarePopulatesIMEIAndPaths(t *testing.T) { discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex) + hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) if len(hardware) != 1 { t.Fatalf("expected 1 hardware, got %d", len(hardware)) @@ -101,7 +101,7 @@ func TestCollectRescanHardwarePopulatesNonQMIIMEIAndPaths(t *testing.T) { discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex) + hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) if len(hardware) != 1 { t.Fatalf("expected 1 hardware, got %d", len(hardware)) diff --git a/internal/device/pool_rescan_guard.go b/internal/device/pool_rescan_guard.go index e842aa91..52ad0fa9 100644 --- a/internal/device/pool_rescan_guard.go +++ b/internal/device/pool_rescan_guard.go @@ -108,6 +108,9 @@ func rescanWorkerConfig(cfg config.DeviceConfig, hw CompatibleModem) config.Devi if hw.NetInterface != "" { cfg.Interface = hw.NetInterface } + if hw.USBPath != "" { + cfg.USBPath = hw.USBPath + } cfg.ControlDevice = strings.TrimSpace(hw.ControlPath) cfg.QMIDevice = strings.TrimSpace(hw.ControlPath) cfg.ATPort = hw.ATPort diff --git a/internal/device/pool_rescan_identity_test.go b/internal/device/pool_rescan_identity_test.go index 888fb73a..306bdc8c 100644 --- a/internal/device/pool_rescan_identity_test.go +++ b/internal/device/pool_rescan_identity_test.go @@ -22,7 +22,7 @@ func TestRescanReusedPathsDoNotInheritOldWorkerIMEI(t *testing.T) { {ControlPath: "/dev/cdc-wdm0", USBPath: "/sys/usb/1-1", NetInterface: "wwan0"}, {ControlPath: "/dev/cdc-wdm1", USBPath: "/sys/usb/1-2", NetInterface: "wwan1"}, } - hardware := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false)) + hardware := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false), false) if len(hardware) != 2 || hardware[0].IMEI != "222222222222222" || hardware[1].IMEI != "111111111111111" { t.Fatalf("identities = %+v", hardware) } diff --git a/internal/device/pool_rescan_nonqmi_test.go b/internal/device/pool_rescan_nonqmi_test.go index 5f030ed1..81b99c58 100644 --- a/internal/device/pool_rescan_nonqmi_test.go +++ b/internal/device/pool_rescan_nonqmi_test.go @@ -75,7 +75,7 @@ func TestRescanReconnectsNonQMIDeviceByIMEI(t *testing.T) { // 验证 resolver 把它放进 Matched 而非 Offline discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex) + hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) managed := config.ListDevices() resolved := ResolveDeviceIdentities(hardware, managed) diff --git a/internal/device/pool_state.go b/internal/device/pool_state.go index 1869a6c5..bba31020 100644 --- a/internal/device/pool_state.go +++ b/internal/device/pool_state.go @@ -204,6 +204,10 @@ func (w *Worker) MarkSIMIdentityDegraded(reason string, err error) { now := time.Now() w.cacheMu.Lock() defer w.cacheMu.Unlock() + w.markSIMIdentityDegradedLocked(reason, err, now) +} + +func (w *Worker) markSIMIdentityDegradedLocked(reason string, err error, now time.Time) { w.state.Identity.Ready = false w.state.Identity.Phase = simIdentityPhaseDegraded w.state.Identity.LastReason = strings.TrimSpace(reason) diff --git a/internal/device/sim_removal.go b/internal/device/sim_removal.go index 5100d1e0..5c5cba92 100644 --- a/internal/device/sim_removal.go +++ b/internal/device/sim_removal.go @@ -7,6 +7,7 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -37,6 +38,31 @@ func (w *Worker) markSIMRemoved(reason string) { w.cacheMu.Unlock() } +func (w *Worker) markSIMPINRequired() { + now := time.Now() + w.cacheMu.Lock() + defer w.cacheMu.Unlock() + if w.state.Identity.LastError == modem.ErrSIMPINRequired.Error() && !w.state.Identity.Ready { + return + } + w.markSIMIdentityDegradedLocked("sim_pin_required", modem.ErrSIMPINRequired, now) + w.state.Identity.Generation++ + w.state.Runtime.SimInserted = false + w.state.Meta.RuntimeUpdatedAt = now +} + +func (p *Pool) handleSIMPINRequired(owner workerLifecycleOwner) { + if !p.workerLifecycleOwnerCurrent(owner) || p.IsESIMSwitching(owner.worker.ID) { + return + } + w := owner.worker + w.markSIMPINRequired() + if err := p.retirePhoneRuntimesForSIMChange(owner); err != nil { + logger.Warn("SIM PIN 锁定后停止电话业务失败", "device", w.ID, "err", err) + } + p.broadcastVoWiFiStateChange(w.ID) +} + func (p *Pool) retirePhoneRuntimesForSIMChange(owner workerLifecycleOwner) error { if p == nil || owner.worker == nil { return errPolicyOwnerChanged diff --git a/internal/device/sim_removal_test.go b/internal/device/sim_removal_test.go index 44deca55..5fd1d247 100644 --- a/internal/device/sim_removal_test.go +++ b/internal/device/sim_removal_test.go @@ -8,6 +8,7 @@ import ( "github.com/yibaiba/hideck/internal/cardpolicy" "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/internal/vowifihost" ) @@ -137,6 +138,82 @@ func TestConfirmedSIMRemovalCancelsStartingVoWiFi(t *testing.T) { } } +type ml307cSIMBackendStub struct { + workerStartupIdentityBackendStub + simErr error +} + +func (s *ml307cSIMBackendStub) IsSimInserted(context.Context) (bool, error) { + return s.simErr == nil, s.simErr +} + +func TestML307CPINRecoveryRetriesIdentityOnRepeatedReady(t *testing.T) { + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"} + m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + be := &ml307cSIMBackendStub{simErr: modem.ErrSIMPINRequired} + w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be} + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"}) + p.AttachWorkerForTest(w) + owner := p.captureWorkerLifecycleOwner(w.ID) + t.Cleanup(func() { p.cancelWorkerLifecycleTimers(w.ID) }) + + p.voWiFiRuntimeStore().SetInstance(w.ID, &runtimehost.Instance{}) + t.Cleanup(func() { p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil) }) + commands := make(chan vowifihost.LifecycleCommand, 1) + p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, command vowifihost.LifecycleCommand) error { + commands <- command + return nil + } + + p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PUK") + select { + case command := <-commands: + if command.Kind != vowifihost.LifecycleCommandDisable { + t.Fatalf("PIN lock lifecycle command = %s", command.Kind) + } + default: + t.Fatal("PIN lock left the old VoWiFi runtime active") + } + p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil) + if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" { + t.Fatal("PIN lock must block the old identity and preserve its binding") + } + if err := p.refreshModemRebootRecoveredIdentity(w, "manual_reboot"); err != nil { + t.Fatalf("PIN lock must allow control-plane recovery: %v", err) + } + + be.simErr = nil + ready := true + confirmPoll := func() { + t.Helper() + p.handleSIMStatusEventForOwner(owner, "test", &ready, "") + p.simEventMu.Lock() + timer := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if timer == nil { + t.Fatal("READY did not schedule SIM identity convergence") + } + timer.Stop() + p.confirmSIMRemovedForOwner(owner, "test", timer) + } + + confirmPoll() // CPIN says READY, but the first live ICCID/IMSI read is empty. + if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" { + t.Fatal("failed identity refresh must leave SIM convergence pending") + } + + be.liveICCID, be.liveIMSI = "card-new", "imsi-new" + confirmPoll() + if w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-new" { + t.Fatalf("repeated READY did not converge to the fresh ICCID: %q", w.CurrentICCID()) + } +} + func TestConfirmedSIMInsertionWaitsForActiveMBNPolicy(t *testing.T) { p := NewPool(&config.Config{}) t.Cleanup(func() { _ = p.Shutdown() }) diff --git a/internal/device/sms_identity.go b/internal/device/sms_identity.go index 501c1cbc..4c6e821e 100644 --- a/internal/device/sms_identity.go +++ b/internal/device/sms_identity.go @@ -108,6 +108,9 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error) } worker.cacheMu.RLock() defer worker.cacheMu.RUnlock() + if worker.isML307C() && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) { + return smsIdentityCandidate{}, ErrSMSIdentityUnknown + } phase := worker.state.Identity.Phase if phase == simIdentityPhaseTransitioning || phase == simIdentityPhaseDegraded { return smsIdentityCandidate{}, fmt.Errorf("%w: device=%s phase=%s", ErrSMSIdentityTransitioning, deviceID, phase) diff --git a/internal/device/usb_at_port_rules.go b/internal/device/usb_at_port_rules.go index 737789ba..7ee8af22 100644 --- a/internal/device/usb_at_port_rules.go +++ b/internal/device/usb_at_port_rules.go @@ -3,6 +3,8 @@ package device import "strings" const ( + cmIoTVendorID = 0x2ecc + ml307cProductID = 0x3012 quectelVendorID = 0x2c7c qualcommVendorID = 0x05c6 quectel0125ProductID = 0x0125 @@ -27,6 +29,10 @@ type usbDeviceIdentity struct { productID uint16 } +func (id usbDeviceIdentity) isML307C() bool { + return id.vendorID == cmIoTVendorID && id.productID == ml307cProductID +} + type usbATPortRule struct { interfaceNumber int serialPortCount int @@ -34,6 +40,9 @@ type usbATPortRule struct { } func usbATPortRuleFor(identity usbDeviceIdentity, mode string) (usbATPortRule, bool) { + if identity.isML307C() { + return usbInterfaceATPortRule(2), true + } mode = strings.ToLower(strings.TrimSpace(mode)) if identity.vendorID == qualcommVendorID && mode == "qmi" { return usbInterfaceATPortRule(2), true @@ -109,6 +118,16 @@ func supportsStaticQuectelATInterface(mode string) bool { func discoverATPortsForUSBDevice(usbPath string, identity usbDeviceIdentity, mode string) (ports []string, bestPort, imei string) { portScan := scanATPortsForUSBDevice(usbPath) + if identity.isML307C() { + var atOnly usbATPortScan + for _, port := range portScan.interfaceOrdered { + if port.interfaceNumber == 2 || port.interfaceNumber == 3 { + atOnly.interfaceOrdered = append(atOnly.interfaceOrdered, port) + atOnly.candidates = append(atOnly.candidates, port.path) + } + } + portScan = atOnly + } bestPort, imei = selectBestATPortForUSBDevice(identity, mode, portScan) return portScan.candidates, bestPort, imei } diff --git a/internal/modem/at_parse.go b/internal/modem/at_parse.go index 351d3401..226f7b7b 100644 --- a/internal/modem/at_parse.go +++ b/internal/modem/at_parse.go @@ -114,7 +114,11 @@ func parseIMSI(resp string) string { } func parseQCCID(resp string) string { - line, ok := findLineWithPrefix(resp, "+QCCID:") + return parseICCID(resp, "+QCCID:") +} + +func parseICCID(resp, prefix string) string { + line, ok := findLineWithPrefix(resp, prefix) if !ok { return "" } @@ -165,7 +169,11 @@ func parseCOPSAct(resp string) (string, bool) { } func parseCREG(resp string) (int, string, string, bool) { - line, ok := findLineWithPrefix(resp, "+CREG:") + return parseRegistration(resp, "+CREG:") +} + +func parseRegistration(resp, prefix string) (int, string, string, bool) { + line, ok := findLineWithPrefix(resp, prefix) if !ok { return 0, "", "", false } diff --git a/internal/modem/at_profile.go b/internal/modem/at_profile.go new file mode 100644 index 00000000..dd8f5220 --- /dev/null +++ b/internal/modem/at_profile.go @@ -0,0 +1,116 @@ +package modem + +import ( + "errors" + "strings" + "time" +) + +type ATProfile uint8 + +const ( + ATProfileDefault ATProfile = iota + ATProfileML307C +) + +func (p ATProfile) imeiCommand() string { + if p == ATProfileML307C { + return "AT+CGSN=1" + } + return "AT+CGSN" +} + +func (p ATProfile) parseIMEI(resp string) string { + if p == ATProfileML307C { + if line, ok := findLineWithPrefix(resp, "+CGSN:"); ok { + return parseIMEI(strings.TrimPrefix(line, "+CGSN:")) + } + } + return parseIMEI(resp) +} + +func (p ATProfile) iccidCommand() string { + if p == ATProfileML307C { + return "AT+MCCID" + } + return "AT+QCCID" +} + +func (p ATProfile) parseICCID(resp string) string { + if p == ATProfileML307C { + return parseICCID(resp, "+MCCID:") + } + return parseQCCID(resp) +} + +var ( + errSIMNotInserted = errors.New("SIM not inserted") + ErrSIMPINRequired = errors.New("SIM PIN or PUK required") +) + +func parseML307CCPIN(resp string) (bool, error) { + line, ok := findLineWithPrefix(resp, "+CPIN:") + if !ok { + return false, errors.New("unrecognized CPIN response") + } + state := strings.TrimSpace(strings.TrimPrefix(line, "+CPIN:")) + if IsSIMPINRequiredState(state) { + return false, ErrSIMPINRequired + } + switch strings.ToUpper(state) { + case "READY": + return true, nil + case "SIM REMOVED", "SIM NOT INSERTED", "NOT INSERTED": + return false, nil + default: + return false, errors.New("unrecognized CPIN state") + } +} + +// IsSIMPINRequiredState recognizes CPIN states where the SIM is present and locked. +func IsSIMPINRequiredState(state string) bool { + switch strings.ToUpper(strings.TrimSpace(state)) { + case "SIM PIN", "SIM PUK", "SIM PIN2", "SIM PUK2": + return true + default: + return false + } +} + +func (m *Manager) queryML307CSIMInserted() (bool, error) { + resp, err := m.ExecuteATSilent("AT+CPIN?", 2*time.Second) + if errors.Is(err, errSIMNotInserted) { + m.cacheML307CSIMState(false, nil) + return false, nil + } + if err != nil { + return false, err + } + inserted, err := parseML307CCPIN(resp) + if err == nil || errors.Is(err, ErrSIMPINRequired) { + m.cacheML307CSIMState(inserted, err) + } + if errors.Is(err, ErrSIMPINRequired) { + m.dispatchSIMStatusURC(nil, "SIM PIN") + } + return inserted, err +} + +func (m *Manager) cacheML307CSIMState(inserted bool, err error) { + m.infoMu.Lock() + defer m.infoMu.Unlock() + m.simInserted = inserted + if !inserted && err == nil { + m.iccid = "" + m.imsi = "" + } +} + +func isML307CNoSIMError(line string) bool { + value, ok := strings.CutPrefix(line, "+CME ERROR:") + if !ok { + return false + } + value = strings.TrimSpace(value) + return value == "10" || strings.EqualFold(value, "SIM not inserted") +} diff --git a/internal/modem/at_profile_test.go b/internal/modem/at_profile_test.go new file mode 100644 index 00000000..142a24c8 --- /dev/null +++ b/internal/modem/at_profile_test.go @@ -0,0 +1,97 @@ +package modem + +import ( + "errors" + "slices" + "testing" + + "github.com/yibaiba/hideck/internal/config" +) + +func TestML307CATQueries(t *testing.T) { + m, err := NewWithATProfile(config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}, ATProfileML307C) + if err != nil { + t.Fatal(err) + } + if got := m.initializationCommands(); !slices.Equal(got, []string{"ATE0", "AT+CMGF=0", "AT+CNMI=2,1,0,0,0"}) { + t.Fatalf("init commands = %v", got) + } + + fixtures := map[string][]string{ + "AT+CGSN=1": {"+CGSN: 490154203237518", "OK"}, + "AT+MCCID": {"+MCCID: 8988110000000000001F", "OK"}, + "AT+CEREG?": {"+CEREG: 0,5", "OK"}, + "AT+COPS?": {"+COPS: 0,0,\"CHN-UNICOM\",7", "OK"}, + "AT+CSQ": {"+CSQ: 24,99", "OK"}, + } + var pinResponses = [][]string{ + {"+CPIN: READY", "OK"}, {"+CPIN: SIM PIN", "OK"}, {"+CME ERROR: SIM not inserted"}, {"ERROR"}, + } + m.port = &timeoutSerialPort{} + m.setRunning(true) + t.Cleanup(m.Stop) + go func() { + for { + select { + case <-m.stop: + return + case req := <-m.cmdChan: + lines := fixtures[req.cmd] + if req.cmd == "AT+CPIN?" && len(pinResponses) > 0 { + lines, pinResponses = pinResponses[0], pinResponses[1:] + } + if len(lines) == 0 { + req.errChan <- errors.New("unexpected AT command: " + req.cmd) + continue + } + for _, line := range lines { + m.rxChan <- rxMsg{Data: line} + } + m.handleCommand(req) + } + } + }() + + if imei, err := m.QueryIMEI(); err != nil || imei != "490154203237518" { + t.Fatalf("QueryIMEI() = %q, %v", imei, err) + } + if iccid, err := m.QueryICCID(); err != nil || iccid != "8988110000000000001" { + t.Fatalf("QueryICCID() = %q, %v", iccid, err) + } + if status, _, _, _, err := m.QueryRegistration(); err != nil || status != 5 { + t.Fatalf("QueryRegistration() = %d, %v", status, err) + } + if operator, err := m.QueryOperator(); err != nil || operator != "CHN-UNICOM" { + t.Fatalf("QueryOperator() = %q, %v", operator, err) + } + if rat, _, _, _, err := m.QueryNetworkRadio(); err != nil || rat != "LTE" { + t.Fatalf("QueryNetworkRadio() = %q, %v", rat, err) + } + if _, rssi, err := m.QueryCSQ(); err != nil || rssi != -65 { + t.Fatalf("QueryCSQ() RSSI = %d, %v", rssi, err) + } + if ready, err := m.QuerySIMInserted(); !ready || err != nil || !m.IsSimInserted() { + t.Fatalf("ready CPIN = %v, %v", ready, err) + } + if ready, err := m.QuerySIMInserted(); ready || !errors.Is(err, ErrSIMPINRequired) || m.IsSimInserted() { + t.Fatalf("locked CPIN = %v, %v", ready, err) + } + if ready, err := m.QuerySIMInserted(); ready || err != nil { + t.Fatalf("absent CPIN = %v, %v", ready, err) + } + if ready, err := m.QuerySIMInserted(); ready || err == nil || !m.IsHealthy() { + t.Fatalf("failed CPIN = %v, %v, healthy=%v", ready, err, m.IsHealthy()) + } +} + +func TestML307CIMEIParsing(t *testing.T) { + profile := ATProfileML307C + for _, invalid := range []string{"20200X000000000000", "+CGSN: 4901542032375180", "+CGSN: 490154203237518,0"} { + if imei := profile.parseIMEI(invalid); imei != "" { + t.Fatalf("invalid CGSN response %q parsed as %q", invalid, imei) + } + } + if imei := profile.parseIMEI("490154203237518"); imei != "490154203237518" { + t.Fatalf("bare IMEI parsed as %q", imei) + } +} diff --git a/internal/modem/commands.go b/internal/modem/commands.go index fcd30df9..cc8ed1e8 100644 --- a/internal/modem/commands.go +++ b/internal/modem/commands.go @@ -2,6 +2,7 @@ package modem import ( "encoding/hex" + "errors" "fmt" "strings" "time" @@ -11,11 +12,15 @@ import ( ) func (m *Manager) QueryIMEI() (string, error) { - resp, err := m.ExecuteATSilent("AT+CGSN", 2*time.Second) + resp, err := m.ExecuteATSilent(m.atProfile.imeiCommand(), 2*time.Second) if err != nil { return "", err } - return parseIMEI(resp), nil + imei := m.atProfile.parseIMEI(resp) + if imei == "" && m.atProfile == ATProfileML307C { + return "", errors.New("invalid IMEI response") + } + return imei, nil } func (m *Manager) QueryFirmware() (string, error) { @@ -27,6 +32,9 @@ func (m *Manager) QueryFirmware() (string, error) { } func (m *Manager) QuerySIMInserted() (bool, error) { + if m.atProfile == ATProfileML307C { + return m.queryML307CSIMInserted() + } if resp, err := m.ExecuteATSilent("AT+QSIMSTAT?", 2*time.Second); err == nil { if inserted, ok := parseQSIMSTATInserted(resp); ok { return inserted, nil @@ -51,15 +59,17 @@ func (m *Manager) QueryIMSI() (string, error) { } func (m *Manager) QueryICCID() (string, error) { - resp, err := m.ExecuteATSilent("AT+QCCID", 2*time.Second) + resp, err := m.ExecuteATSilent(m.atProfile.iccidCommand(), 2*time.Second) if err != nil { return "", err } - return parseQCCID(resp), nil + return m.atProfile.parseICCID(resp), nil } func (m *Manager) QueryOperator() (string, error) { - _, _ = m.ExecuteATSilent("AT+COPS=3,2", 2*time.Second) + if m.atProfile != ATProfileML307C { + _, _ = m.ExecuteATSilent("AT+COPS=3,2", 2*time.Second) + } resp, err := m.ExecuteATSilent("AT+COPS?", 2*time.Second) if err != nil { return "", err @@ -68,11 +78,15 @@ func (m *Manager) QueryOperator() (string, error) { } func (m *Manager) QueryRegistration() (int, string, string, string, error) { - resp, err := m.ExecuteATSilent("AT+CREG?", 2*time.Second) + command, prefix := "AT+CREG?", "+CREG:" + if m.atProfile == ATProfileML307C { + command, prefix = "AT+CEREG?", "+CEREG:" + } + resp, err := m.ExecuteATSilent(command, 2*time.Second) if err != nil { return 0, "", "", "", err } - regStatus, lac, cellID, ok := parseCREG(resp) + regStatus, lac, cellID, ok := parseRegistration(resp, prefix) if !ok { return 0, "", "", "", nil } @@ -100,6 +114,9 @@ func (m *Manager) QueryServingCellLTE() (int, int, error) { } func (m *Manager) QueryServingCellLTEInfo() (ServingCellLTEInfo, error) { + if m.atProfile == ATProfileML307C { + return ServingCellLTEInfo{}, nil + } resp, err := m.ExecuteATSilent("AT+QENG=\"servingcell\"", 3*time.Second) if err != nil { return ServingCellLTEInfo{}, err @@ -120,6 +137,9 @@ func (m *Manager) QueryAPN() (string, error) { } func (m *Manager) QueryIMSStatus() (int, error) { + if m.atProfile == ATProfileML307C { + return 0, nil + } resp, err := m.ExecuteATSilent("AT+QIMS?", 2*time.Second) if err != nil { return 0, err @@ -134,6 +154,14 @@ func (m *Manager) QueryNetworkModeAndDuplex() (string, string, error) { } func (m *Manager) QueryNetworkRadio() (string, string, string, uint32, error) { + if m.atProfile == ATProfileML307C { + resp, err := m.ExecuteATSilent("AT+COPS?", 2*time.Second) + if err != nil { + return "", "", "", 0, err + } + mode, _ := parseCOPSAct(resp) + return mode, "", "", 0, nil + } resp, err := m.ExecuteATSilent("AT+QNWINFO", 2*time.Second) if err != nil { return "", "", "", 0, err @@ -149,8 +177,8 @@ func (m *Manager) QueryNetworkMode() (string, error) { func (m *Manager) QueryNetworkModeFallbackAndDuplex() (string, string, error) { networkMode, networkDuplex, err := m.QueryNetworkModeAndDuplex() - if err == nil && networkMode != "" { - return networkMode, networkDuplex, nil + if m.atProfile == ATProfileML307C || (err == nil && networkMode != "") { + return networkMode, networkDuplex, err } resp, err2 := m.ExecuteATSilent("AT+COPS?", 2*time.Second) if err2 != nil { @@ -263,6 +291,9 @@ func (m *Manager) QueryMSISDN() (string, error) { // QueryUSBNetMode 查询 USBNET 模式 func (m *Manager) QueryUSBNetMode() (int, error) { + if m.atProfile == ATProfileML307C { + return -1, nil + } resp, err := m.ExecuteATSilent("AT+QCFG=\"usbnet\"?", 2*time.Second) if err != nil { return -1, err diff --git a/internal/modem/imei_cache_test.go b/internal/modem/imei_cache_test.go index e250eb43..b97ea61c 100644 --- a/internal/modem/imei_cache_test.go +++ b/internal/modem/imei_cache_test.go @@ -15,8 +15,8 @@ func TestIMEICacheRejectsReusedSerialNode(t *testing.T) { if err != nil { t.Fatal(err) } - storeCachedIMEI(path, "111111111111111", node) - if got := loadCachedIMEI(path); got != "111111111111111" { + storeCachedIMEIForProfile(path, "111111111111111", node, ATProfileDefault) + if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "111111111111111" { t.Fatalf("cache = %q", got) } // Keep the old inode alive so this models replacement rather than inode reuse. @@ -26,11 +26,11 @@ func TestIMEICacheRejectsReusedSerialNode(t *testing.T) { if err := os.WriteFile(path, nil, 0600); err != nil { t.Fatal(err) } - if got := loadCachedIMEI(path); got != "" { + if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "" { t.Fatalf("reused port retained identity %q", got) } - storeCachedIMEI(path, "111111111111111", node) - if got := loadCachedIMEI(path); got != "" { + storeCachedIMEIForProfile(path, "111111111111111", node, ATProfileDefault) + if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "" { t.Fatalf("late probe poisoned new node: %q", got) } } diff --git a/internal/modem/imei_probe.go b/internal/modem/imei_probe.go index 205211a9..6cdb1cbf 100644 --- a/internal/modem/imei_probe.go +++ b/internal/modem/imei_probe.go @@ -13,9 +13,10 @@ import ( // imeiCacheItem 存储 IMEI 缓存条目及对应的获取时间戳 type imeiCacheItem struct { - IMEI string - TS time.Time - Node os.FileInfo + IMEI string + TS time.Time + Node os.FileInfo + Profile ATProfile } // imeiCache 提供线程安全的内存 IMEI 映射缓存,避免频繁通过串口发起硬件查询 @@ -31,6 +32,10 @@ func ProbeIMEICached(atPort string, timeout time.Duration) (string, error) { // ProbeIMEICachedContext 提供可取消的缓存 IMEI 探测。 func ProbeIMEICachedContext(ctx context.Context, atPort string, timeout time.Duration) (string, error) { + return ATProfileDefault.ProbeIMEICached(ctx, atPort, timeout) +} + +func (profile ATProfile) ProbeIMEICached(ctx context.Context, atPort string, timeout time.Duration) (string, error) { atPort = strings.TrimSpace(atPort) if atPort == "" { return "", errors.New("empty at port") @@ -39,30 +44,30 @@ func ProbeIMEICachedContext(ctx context.Context, atPort string, timeout time.Dur ctx = context.Background() } - if imei := loadCachedIMEI(atPort); imei != "" { + if imei := loadCachedIMEIForProfile(atPort, profile); imei != "" { return imei, nil } node, _ := os.Stat(atPort) - imei, err := ProbeIMEIContext(ctx, atPort, timeout) + imei, err := profile.probeIMEI(ctx, atPort, timeout) if err == nil && imei != "" { - storeCachedIMEI(atPort, imei, node) + storeCachedIMEIForProfile(atPort, imei, node, profile) } return imei, err } -func loadCachedIMEI(atPort string) string { +func loadCachedIMEIForProfile(atPort string, profile ATProfile) string { imeiCache.mu.RLock() defer imeiCache.mu.RUnlock() item, ok := imeiCache.m[atPort] node, err := os.Stat(atPort) - if !ok || item.IMEI == "" || time.Since(item.TS) >= 10*time.Minute || err != nil || item.Node == nil || !os.SameFile(item.Node, node) || !item.Node.ModTime().Equal(node.ModTime()) { + if !ok || item.Profile != profile || item.IMEI == "" || time.Since(item.TS) >= 10*time.Minute || err != nil || item.Node == nil || !os.SameFile(item.Node, node) || !item.Node.ModTime().Equal(node.ModTime()) { return "" } return item.IMEI } -func storeCachedIMEI(atPort, imei string, node os.FileInfo) { +func storeCachedIMEIForProfile(atPort, imei string, node os.FileInfo, profile ATProfile) { current, err := os.Stat(atPort) if err != nil || node == nil || !os.SameFile(node, current) || !node.ModTime().Equal(current.ModTime()) { return @@ -72,7 +77,7 @@ func storeCachedIMEI(atPort, imei string, node os.FileInfo) { if imeiCache.m == nil { imeiCache.m = make(map[string]imeiCacheItem) } - imeiCache.m[atPort] = imeiCacheItem{IMEI: imei, TS: time.Now(), Node: node} + imeiCache.m[atPort] = imeiCacheItem{IMEI: imei, TS: time.Now(), Node: node, Profile: profile} } // ProbeIMEI 通过打开底层 TTY 串口设备并执行 `AT+CGSN` 指令来实时探测模组的 IMEI 串号 @@ -82,6 +87,10 @@ func ProbeIMEI(atPort string, timeout time.Duration) (string, error) { // ProbeIMEIContext 在取消时主动关闭串口,避免 USB 重枚举期间阻塞设备恢复。 func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) (string, error) { + return ATProfileDefault.probeIMEI(ctx, atPort, timeout) +} + +func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout time.Duration) (string, error) { atPort = strings.TrimSpace(atPort) if atPort == "" { return "", errors.New("empty at port") @@ -116,6 +125,14 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) buf := make([]byte, 1024) var acc strings.Builder + readIMEI := func() string { + reply := acc.String() + if profile == ATProfileML307C { + // A serial read can end in the middle of an identifier. + reply = reply[:strings.LastIndexAny(reply, "\r\n")+1] + } + return profile.parseIMEI(reply) + } write := func(s string) { _, _ = p.Write([]byte(s)) @@ -124,14 +141,14 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) // 写入 AT 测试命令与查询 IMEI 的 AT+CGSN 命令 write("AT\r\n") time.Sleep(40 * time.Millisecond) - write("AT+CGSN\r\n") + write(profile.imeiCommand() + "\r\n") // 在指定的截止时间内轮询并解析串口输出内容 for probeCtx.Err() == nil { n, rerr := p.Read(buf) if n > 0 { acc.Write(buf[:n]) - if imei := parseIMEI(acc.String()); imei != "" { + if imei := readIMEI(); imei != "" { return imei, nil } } @@ -146,7 +163,7 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) } // 最终尝试解析一次累积的串口缓冲区 - if imei := parseIMEI(acc.String()); imei != "" { + if imei := readIMEI(); imei != "" { return imei, nil } if err := probeCtx.Err(); err != nil && !errors.Is(err, context.DeadlineExceeded) { diff --git a/internal/modem/manager.go b/internal/modem/manager.go index da3c68c9..ec606a18 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -57,11 +57,12 @@ type commandRequest struct { // Manager 管理单个 EC20 模块的 AT 指令通信 type Manager struct { - cfg config.DeviceConfig - atPort string - port serial.Port - portMode *serial.Mode - role runtimeRole + atProfile ATProfile + cfg config.DeviceConfig + atPort string + port serial.Port + portMode *serial.Mode + role runtimeRole // 通道驱动的异步架构 stop chan struct{} @@ -176,19 +177,26 @@ func (m *Manager) pureQMIBackend() bool { } func New(cfg config.DeviceConfig) (*Manager, error) { - return newManager(cfg, runtimeRoleDefault) + return NewWithATProfile(cfg, ATProfileDefault) } +func NewWithATProfile(cfg config.DeviceConfig, profile ATProfile) (*Manager, error) { + return newManager(cfg, runtimeRoleDefault, profile) +} + +func (m *Manager) ATProfile() ATProfile { return m.atProfile } + // NewSMSAuxiliary creates the single AT runtime used by an MBIM worker for // SMS, SMSC, URCs, and manual AT commands. Network, identity, and APDU remain // owned by the MBIM backend. func NewSMSAuxiliary(cfg config.DeviceConfig) (*Manager, error) { - return newManager(cfg, runtimeRoleSMSAuxiliary) + return newManager(cfg, runtimeRoleSMSAuxiliary, ATProfileDefault) } -func newManager(cfg config.DeviceConfig, role runtimeRole) (*Manager, error) { +func newManager(cfg config.DeviceConfig, role runtimeRole, profile ATProfile) (*Manager, error) { m := &Manager{ cfg: cfg, + atProfile: profile, atPort: cfg.ATPort, role: role, stop: make(chan struct{}), @@ -769,7 +777,9 @@ RespLoop: "resp", logATResponse(req.cmd, strings.Join(fullResponse, " | ")), "cost", time.Since(startTime).Truncate(time.Millisecond).String()) } - if req.cmd == "AT+CLCC" { + if m.atProfile == ATProfileML307C && req.cmd == "AT+CPIN?" && isML307CNoSIMError(line) { + req.errChan <- errSIMNotInserted + } else if req.cmd == "AT+CLCC" { req.errChan <- &clccResponseError{response: strings.Join(fullResponse, "\n"), terminal: line} } else { req.errChan <- fmt.Errorf("设备返回错误: %s", logATResponse(req.cmd, strings.Join(fullResponse, "\n"))) @@ -796,6 +806,8 @@ RespLoop: req.respChan <- "> " break RespLoop + } else if m.atProfile == ATProfileML307C && req.cmd == "AT+CPIN?" && strings.HasPrefix(line, "+CPIN:") { + fullResponse = append(fullResponse, line) } else if m.isURC(line) { // 对于确认为 URC 的行,始终分发出去 m.handleURC(line) @@ -1010,8 +1022,10 @@ func (m *Manager) collectDeviceInfo() { imsi = v } } - if v, err := m.QueryICCID(); err == nil { - iccid = v + if simInserted || m.atProfile != ATProfileML307C { + if v, err := m.QueryICCID(); err == nil { + iccid = v + } } if v, err := m.QueryOperator(); err == nil { operator = v @@ -1062,7 +1076,9 @@ func (m *Manager) collectDeviceInfo() { if operator != "" { m.operator = operator } - m.simInserted = simInserted + if m.atProfile != ATProfileML307C { + m.simInserted = simInserted + } if signalDBM != -999 { m.signalDBM = signalDBM } @@ -1279,6 +1295,9 @@ func (m *Manager) RefreshStatus(onAlert func(msg string), onRecover func(msg str // 检查 SIM 卡是否存活 simInserted, simErr := m.QuerySIMInserted() + if m.atProfile == ATProfileML307C && simErr == nil { + m.dispatchSIMStatusURC(&simInserted, "") + } if v, err := m.QueryOperator(); err == nil { operator = v @@ -1426,6 +1445,9 @@ func (m *Manager) handleURC(line string) { break } } + if m.atProfile == ATProfileML307C && IsSIMPINRequiredState(state) { + m.cacheML307CSIMState(false, ErrSIMPINRequired) + } m.dispatchSIMStatusURC(nil, state) } diff --git a/internal/modem/runtime_role.go b/internal/modem/runtime_role.go index 409232dc..62d33826 100644 --- a/internal/modem/runtime_role.go +++ b/internal/modem/runtime_role.go @@ -25,7 +25,7 @@ func (m *Manager) initializationCommands() []string { "AT+CMGF=0", "AT+CNMI=2,1,0,0,0", } - if m.role == runtimeRoleSMSAuxiliary { + if m.role == runtimeRoleSMSAuxiliary || m.atProfile == ATProfileML307C { return commands } return append(commands, From 41a78ae1db8a32ebfef01e1a3a3561ef9480f64f Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 13:30:37 +0800 Subject: [PATCH 02/39] fix(esim): accept ML307C bare logical channel responses --- internal/modem/at_parse.go | 22 ++++++++++++++++++++-- internal/modem/at_parse_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/internal/modem/at_parse.go b/internal/modem/at_parse.go index 226f7b7b..1dda7a9a 100644 --- a/internal/modem/at_parse.go +++ b/internal/modem/at_parse.go @@ -548,11 +548,11 @@ func ParseUSBNetMode(resp string) (int, error) { } // parseCCHO 解析 AT+CCHO 响应,提取逻辑通道号 -// 响应格式: +CCHO: +// 响应格式: +CCHO: 。ML307C 返回单行裸通道号。 func parseCCHO(resp string) (int, bool) { line, ok := findLineWithPrefix(resp, "+CCHO:") if !ok { - return -1, false + return parseBareCCHO(resp) } parts := strings.Split(line, ":") if len(parts) < 2 { @@ -566,6 +566,24 @@ func parseCCHO(resp string) (int, bool) { return -1, false } +func parseBareCCHO(resp string) (int, bool) { + var channel int + for _, line := range splitLines(resp) { + if line == "" || line == "OK" { + continue + } + value, err := strconv.ParseUint(line, 10, 8) + if channel != 0 || err != nil || value == 0 { + return -1, false + } + channel = int(value) + } + if channel == 0 { + return -1, false + } + return channel, true +} + // parseCGLA 解析 AT+CGLA 响应,提取 APDU 响应 // 响应格式: +CGLA: ,"" func parseCGLA(resp string) (string, bool) { diff --git a/internal/modem/at_parse_test.go b/internal/modem/at_parse_test.go index eb2f397d..87c3694a 100644 --- a/internal/modem/at_parse_test.go +++ b/internal/modem/at_parse_test.go @@ -214,3 +214,30 @@ func TestParseCOPSOperator(t *testing.T) { }) } } + +func TestParseCCHO(t *testing.T) { + tests := []struct { + name string + resp string + channel int + }{ + {name: "prefixed", resp: "\r\n+CCHO: 2\r\nOK\r\n", channel: 2}, + {name: "ML307C", resp: "\r\n2\r\nOK\r\n", channel: 2}, + {name: "terminal stripped", resp: "2", channel: 2}, + {name: "only OK", resp: "OK", channel: -1}, + {name: "bare followed by ERROR", resp: "2\nERROR", channel: -1}, + {name: "command rejected", resp: "+CME ERROR: 3", channel: -1}, + {name: "multiple numbers", resp: "2\n3\nOK", channel: -1}, + {name: "number with suffix", resp: "2,3\nOK", channel: -1}, + {name: "basic channel", resp: "0\nOK", channel: -1}, + {name: "out of range", resp: "258\nOK", channel: -1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + channel, ok := parseCCHO(tt.resp) + if channel != tt.channel || ok != (tt.channel > 0) { + t.Fatalf("parseCCHO(%q) = (%d, %t), want (%d, %t)", tt.resp, channel, ok, tt.channel, tt.channel > 0) + } + }) + } +} From 30c055bedd26eb3a5eb5a0ab06a2478c02638de8 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 13:52:25 +0800 Subject: [PATCH 03/39] fix(sms): persist ML307C stored messages before clearing slots --- internal/db/sms_fragment_reconcile.go | 15 + internal/db/sms_inbound_fragment.go | 2 + internal/device/pool_bootstrap.go | 2 + internal/device/sms_ml307c.go | 367 +++++++++++++++++++++ internal/device/sms_ml307c_test.go | 104 ++++++ internal/device/sms_mode_at.go | 4 + internal/device/vowifi_delivery_store.go | 4 + internal/modem/at_parse.go | 8 +- internal/modem/commands.go | 43 ++- internal/modem/manager.go | 14 + internal/modem/manager_sms_storage_test.go | 56 ++++ internal/modem/sms_inbox.go | 143 ++++++++ pkg/smscodec/pdu.go | 29 ++ 13 files changed, 786 insertions(+), 5 deletions(-) create mode 100644 internal/device/sms_ml307c.go create mode 100644 internal/device/sms_ml307c_test.go create mode 100644 internal/modem/sms_inbox.go diff --git a/internal/db/sms_fragment_reconcile.go b/internal/db/sms_fragment_reconcile.go index 1f2a3c14..8e8c4f66 100644 --- a/internal/db/sms_fragment_reconcile.go +++ b/internal/db/sms_fragment_reconcile.go @@ -60,6 +60,21 @@ func compactSQLiteDefinition(definition string) string { return strings.ToLower(strings.Join(strings.Fields(definition), "")) } +// LookupCompletedReceivedSMS finds an already committed receive session without +// creating history for a storage slot with unknown provenance. +func LookupCompletedReceivedSMS(iccid, imsi, sessionKey string) (SMS, bool, error) { + if DB == nil { + return SMS{}, false, errors.New("database not initialized") + } + var row SMS + err := DB.Where("iccid = ? AND imsi = ? AND fragment_session_key = ? AND incomplete = ?", CanonicalICCID(iccid), imsi, sessionKey, false). + First(&row).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return SMS{}, false, nil + } + return row, err == nil, err +} + func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSResult, error) { if DB == nil { return ReceivedMultipartSMSResult{}, errors.New("database not initialized") diff --git a/internal/db/sms_inbound_fragment.go b/internal/db/sms_inbound_fragment.go index ad780327..f645f5d3 100644 --- a/internal/db/sms_inbound_fragment.go +++ b/internal/db/sms_inbound_fragment.go @@ -8,6 +8,8 @@ import ( "gorm.io/gorm" ) +const ATSMSInboundPrefix = "at:" + var ErrSMSInboundFragmentCollision = errors.New("SMS inbound fragment collision") type SMSInboundFragmentScope struct { diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 0b44ca75..baf45d7d 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -720,6 +720,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) default: } worker.PreWarmCache() + worker.scanML307CSMS() // 缓存预热完成后,触发一次状态广播,强制前端 SSE 推流更新最新设备数据 p.broadcastVoWiFiStateChange(worker.ID) }(w) @@ -763,6 +764,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) case <-ticker.C: switch worker.smsMode { case smsModeAT: + worker.scanML307CSMS() case smsModeQMI: if worker.QMICore != nil { if err := worker.CheckAllSMSQMI(); err != nil { diff --git a/internal/device/sms_ml307c.go b/internal/device/sms_ml307c.go new file mode 100644 index 00000000..72fa730d --- /dev/null +++ b/internal/device/sms_ml307c.go @@ -0,0 +1,367 @@ +package device + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/smsnotify" + "github.com/yibaiba/hideck/pkg/logger" + "github.com/yibaiba/hideck/pkg/smscodec" +) + +var ml307cSMSStores = [...]string{"ME", "SM"} + +type ml307cSMSOwner struct { + workerLifecycleOwner + SMSIdentity + simGeneration uint64 +} + +func (w *Worker) ml307cSMSOwner() (ml307cSMSOwner, error) { + w.cacheMu.RLock() + id := w.state.Identity + w.cacheMu.RUnlock() + identity := normalizeSMSIdentity(SMSIdentity{ICCID: id.ICCID, IMSI: id.IMSI}) + if !id.Ready || id.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" { + return ml307cSMSOwner{}, ErrSMSIdentityUnknown + } + return ml307cSMSOwner{ + workerLifecycleOwner: workerLifecycleOwner{worker: w, generation: w.generation}, + SMSIdentity: identity, simGeneration: id.Generation, + }, nil +} + +func (owner ml307cSMSOwner) check() error { + w := owner.worker + if !w.Pool.workerLifecycleOwnerCurrent(owner.workerLifecycleOwner) || + w.Pool.IsESIMSwitching(w.ID) || !w.Modem.StoredSMSReceiving() { + return ErrSMSIdentityTransitioning + } + current, err := w.ml307cSMSOwner() + if err != nil || current != owner { + return ErrSMSIdentityTransitioning + } + return nil +} + +func (owner ml307cSMSOwner) verifyLive() error { + if err := owner.check(); err != nil { + return err + } + w := owner.worker + inserted, err := w.Modem.QuerySIMInserted() + if err != nil { + return err + } + if !inserted { + return ErrSMSIdentityUnknown + } + iccid, err := w.Modem.QueryICCID() + if err != nil { + return err + } + imsi, err := w.Modem.QueryIMSI() + if err != nil { + return err + } + if normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi}) != owner.SMSIdentity { + return ErrSMSIdentityConflict + } + return owner.check() +} + +func (w *Worker) handleML307CStoredSMS(storage, index string) { + slot, err := strconv.Atoi(index) + if err != nil || slot < 0 || (storage != "ME" && storage != "SM") { + return + } + // Capture before queuing the work. A delayed URC must keep its original + // worker and SIM generation across eSIM and physical card changes. + owner, err := w.ml307cSMSOwner() + if err != nil { + return + } + go w.runML307CSMS(owner, storage, slot) +} + +func (w *Worker) scanML307CSMS() { + if !w.isML307C() || !w.Modem.StoredSMSReceiving() { + return + } + owner, err := w.ml307cSMSOwner() + if err != nil { + return + } + w.runML307CSMS(owner, "", 0) +} + +func (w *Worker) runML307CSMS(owner ml307cSMSOwner, storage string, index int) { + var notifications []InboundSMS + err := w.readML307CSMSInbox(owner, storage, index, ¬ifications) + if err != nil { + logger.Warn("ML307C 短信收件未完成", "device", w.ID, "storage", storage, "err", err) + } + for _, inbound := range notifications { + w.Pool.notifyInboundSMS(inbound) + if notifier := w.Pool.getNotifier(); notifier != nil { + notifySMS(notifier, inbound, "") + } + } +} + +func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, storage string, index int, notifications *[]InboundSMS) error { + // The eSIM manager uses the same transition lock. Take it before the + // serial inbox lock, matching the lock order used for sending. + release, err := w.Pool.AcquireDeviceOperation(w.ID) + if err != nil { + return err + } + defer release() + transition := w.Pool.policyTransitionFor(w.ID) + transition.Lock() + defer transition.Unlock() + gateCtx, cancelGate := context.WithTimeout(w.Pool.Context(), 5*time.Second) + defer cancelGate() + releaseAT, err := w.Pool.acquireDeviceAT(gateCtx, w.ID) + if err != nil { + return err + } + defer releaseAT() + if err := owner.verifyLive(); err != nil { + return err + } + scope := db.SMSInboundFragmentScope{DeviceID: w.ID, ICCID: owner.ICCID, IMSI: owner.IMSI} + return w.Modem.WithSMSInbox(func(inbox *modem.SMSInbox) error { + state, err := loadATSMSParts(scope) + if err != nil { + return err + } + if storage != "" { + if err := inbox.Select(storage); err != nil { + return err + } + record, err := inbox.Read(index) + if err != nil { + return err + } + if err := owner.verifyLive(); err != nil { + return err + } + return w.ingestML307CSlot(inbox, owner, state, record, true, notifications) + } + + var scanErr error + for _, store := range ml307cSMSStores { + if err := inbox.Select(store); err != nil { + return errors.Join(scanErr, err) + } + records, err := inbox.List() + if err != nil { + scanErr = errors.Join(scanErr, err) + continue + } + if err := owner.verifyLive(); err != nil { + return errors.Join(scanErr, err) + } + for _, record := range records { + if err := w.ingestML307CSlot(inbox, owner, state, record, store == "SM", notifications); err != nil { + scanErr = errors.Join(scanErr, err) + } + } + } + if scanErr != nil { + return scanErr + } + if err := owner.check(); err != nil { + return err + } + return state.clearCompletedGroups() + }) +} + +func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notifications *[]InboundSMS) error { + if !record.Received() { + return nil + } + if err := owner.check(); err != nil { + return err + } + part, err := decodeATInboxPart(owner.SMSIdentity, record.PDU) + if err != nil { + return fmt.Errorf("SMS slot %d: %w", record.Index, err) + } + stored, inbound, err := state.persist(part, sourceKnown) + if err != nil { + return fmt.Errorf("persist SMS slot %d: %w", record.Index, err) + } + if inbound != nil { + *notifications = append(*notifications, *inbound) + } + if !stored { + return nil + } + if err := inbox.DeleteMatching(record, owner.verifyLive); err != nil { + return fmt.Errorf("delete persisted SMS slot %d: %w", record.Index, err) + } + return nil +} + +type atInboxPart struct { + smscodec.ATDeliverSMS + key string +} + +func decodeATInboxPart(identity SMSIdentity, pduHex string) (atInboxPart, error) { + raw, err := hex.DecodeString(pduHex) + if err != nil { + return atInboxPart{}, errors.New("invalid SMS PDU hex") + } + decoded, err := smscodec.DecodeATDeliverSMS(raw) + if err != nil || decoded.Sender == "" || decoded.Timestamp.IsZero() { + return atInboxPart{}, errors.New("cannot decode stored SMS-DELIVER") + } + key := fmt.Sprintf("%ssingle:%x", db.ATSMSInboundPrefix, sha256.Sum256(raw)) + concat := decoded.Concat + if concat.IsConcat { + if concat.Seq < 1 || concat.Seq > concat.Total { + return atInboxPart{}, errors.New("invalid SMS fragment sequence") + } + group := fmt.Sprintf("%q:%q:%d:%d:%d:%s", identity.IMSI, decoded.Sender, concat.RefBits, concat.Ref, concat.Total, decoded.SCTS) + key = fmt.Sprintf("%sparts:%x", db.ATSMSInboundPrefix, sha256.Sum256([]byte(group))) + } + return atInboxPart{ATDeliverSMS: decoded, key: key}, nil +} + +type atSMSParts struct { + scope db.SMSInboundFragmentScope + groups map[string][]db.SMSInboundFragment + seen map[string]bool +} + +func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { + rows, err := db.LoadSMSInboundFragments(scope) + if err != nil { + return nil, err + } + state := &atSMSParts{scope: scope, groups: make(map[string][]db.SMSInboundFragment), seen: make(map[string]bool)} + for _, row := range rows { + if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) { + state.groups[row.SessionKey] = append(state.groups[row.SessionKey], row) + } + } + return state, nil +} + +func (state *atSMSParts) persist(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { + if part.Concat.IsConcat { + state.seen[part.key] = true + if part.Binary { + return false, nil, nil + } + return state.persistFragment(part, sourceKnown) + } + if smsnotify.ShouldSuppressReceivedSMS(part.Content) { + return false, nil, nil + } + if !sourceKnown { + saved, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, part.key) + return found && strings.TrimSpace(part.Content) == saved.Content, nil, err + } + return state.commit(part, part.Content) +} + +func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { + fragments := state.groups[part.key] + matched := false + for _, saved := range fragments { + if saved.Sequence == part.Concat.Seq { + if saved.Content != part.Content { + return false, nil, db.ErrSMSInboundFragmentCollision + } + matched = true + break + } + } + if !matched { + // Another part with the exact session key establishes this ME + // fragment's provenance after the worker has restarted. + if !sourceKnown && len(fragments) == 0 { + return false, nil, nil + } + scope := state.scope + scope.SessionKey = part.key + concat := part.Concat + result, err := db.SaveSMSInboundFragment(scope, db.SMSInboundFragment{ + Sequence: concat.Seq, Reference: concat.Ref, ReferenceBits: concat.RefBits, + Total: concat.Total, Content: part.Content, ArrivedAt: part.Timestamp, + }) + if err != nil { + return false, nil, err + } + fragments = result.Fragments + state.groups[part.key] = fragments + } + if len(fragments) < part.Concat.Total { + return true, nil, nil + } + var content strings.Builder + for i, fragment := range fragments { + if fragment.Sequence != i+1 || fragment.Total != part.Concat.Total { + return false, nil, db.ErrSMSInboundFragmentCollision + } + content.WriteString(fragment.Content) + } + return state.commit(part, content.String()) +} + +func (state *atSMSParts) commit(part atInboxPart, content string) (bool, *InboundSMS, error) { + timestamp := correctSMSCTimestamp(state.scope.DeviceID, state.scope.IMSI, part.Timestamp, time.Now()) + result, err := db.SaveReceivedMultipartSMS(db.ReceivedMultipartSMS{ + ICCID: state.scope.ICCID, IMSI: state.scope.IMSI, + Sender: part.Sender, Content: content, Timestamp: timestamp, FragmentSessionKey: part.key, + }) + if err != nil { + return false, nil, err + } + if !result.Created { + return true, nil, nil + } + return true, &InboundSMS{ + DeviceID: state.scope.DeviceID, ICCID: state.scope.ICCID, IMSI: state.scope.IMSI, + Sender: part.Sender, Content: content, Time: timestamp, + }, nil +} + +func (state *atSMSParts) clearCompletedGroups() error { + for key, fragments := range state.groups { + if state.seen[key] || len(fragments) != fragments[0].Total { + continue + } + if slices.ContainsFunc(fragments, func(part db.SMSInboundFragment) bool { + return part.DeviceID != state.scope.DeviceID + }) { + continue + } + _, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, key) + if err != nil { + return err + } + if found { + scope := state.scope + scope.SessionKey = key + if err := db.DeleteSMSInboundFragments(scope); err != nil { + return err + } + } + } + return nil +} diff --git a/internal/device/sms_ml307c_test.go b/internal/device/sms_ml307c_test.go new file mode 100644 index 00000000..b46966bd --- /dev/null +++ b/internal/device/sms_ml307c_test.go @@ -0,0 +1,104 @@ +package device + +import ( + "encoding/hex" + "testing" + + "github.com/yibaiba/hideck/internal/db" +) + +func TestML307CStoredSMSPersistence(t *testing.T) { + initDevicePhoneNumberTestDB(t) + identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} + scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} + fragment := func(seq, second byte, ch rune) atInboxPart { + t.Helper() + pdu := []byte{ + 0, // default SMSC + 0x40, 3, 0x81, 0x77, 0xF7, // SMS-DELIVER, UDHI, sender 777 + 0, 8, // PID, UCS2 + 0x62, 0x11, 0x91, 0x21, 0, second, 0, // SCTS + 8, 5, 0, 3, 17, 2, seq, byte(ch >> 8), byte(ch), + } + part, err := decodeATInboxPart(identity, hex.EncodeToString(pdu)) + if err != nil { + t.Fatal(err) + } + if !part.Concat.IsConcat || part.Sender != "777" || part.Content != string(ch) { + t.Fatalf("unexpected decoded part: %+v", part) + } + return part + } + load := func(scope db.SMSInboundFragmentScope) *atSMSParts { + t.Helper() + state, err := loadATSMSParts(scope) + if err != nil { + t.Fatal(err) + } + return state + } + apply := func(state *atSMSParts, part atInboxPart, sourceKnown, wantStored bool, wantContent string) { + t.Helper() + stored, notification, err := state.persist(part, sourceKnown) + if err != nil || stored != wantStored { + t.Fatalf("persist = %t, %v, want %t", stored, err, wantStored) + } + if wantContent == "" { + if notification != nil { + t.Fatalf("unexpected notification: %+v", notification) + } + } else if notification == nil || notification.Content != wantContent { + t.Fatalf("notification = %+v, want %q", notification, wantContent) + } + } + + a1, a2 := fragment(1, 0, '甲'), fragment(2, 0, '乙') + b1, b2 := fragment(1, 0x10, '丙'), fragment(2, 0x10, '丁') + state := load(scope) + apply(state, a1, false, false, "") // unknown ME: no history and no delete + apply(state, a1, true, true, "") // CMTI persists the first part before removing its slot + + state = load(scope) // new process/worker can see the durable fragment + if state.groups[a1.key][0].Content != "甲" { + t.Fatal("first fragment was not restored") + } + apply(state, b2, true, true, "") // same ref, different SCTS cannot complete A + apply(state, a2, false, true, "甲乙") // the missing tail arrived in ME while HiDeck was offline + apply(state, b1, true, true, "丙丁") + + state = load(scope) // deletion failed before restart; the PDU is still on ME + apply(state, a2, false, true, "") // matched durable part, no duplicate notification + if err := state.clearCompletedGroups(); err != nil { + t.Fatal(err) + } + if len(load(scope).groups[a1.key]) != 2 { + t.Fatal("a scan containing a residual slot retired its fragment rows") + } + otherDevice := scope + otherDevice.DeviceID = "c-other" + if err := load(otherDevice).clearCompletedGroups(); err != nil { + t.Fatal(err) + } + if len(load(scope).groups[a1.key]) != 2 { + t.Fatal("another module's empty scan retired the original module's fragments") + } + if err := load(scope).clearCompletedGroups(); err != nil { // subsequent complete, empty scan + t.Fatal(err) + } + if len(load(scope).groups) != 0 { + t.Fatal("completed fragment groups were not collected") + } + + swapped := scope + swapped.ICCID, swapped.IMSI = "8988110000000000002", "001010123456788" + apply(load(swapped), a1, false, false, "") // unknown old ME after a card change + + state = load(scope) + database := db.DB + db.DB = nil + stored, _, err := state.persist(a1, true) + db.DB = database + if err == nil || stored { + t.Fatalf("DB failure allowed deleting the slot: %t, %v", stored, err) + } +} diff --git a/internal/device/sms_mode_at.go b/internal/device/sms_mode_at.go index 274c0668..765ac669 100644 --- a/internal/device/sms_mode_at.go +++ b/internal/device/sms_mode_at.go @@ -15,6 +15,10 @@ func configureWorkerATSMS(w *Worker) { } w.Modem.SetNewSMSHandler(nil) w.Modem.SetDisableURCRead(false) + if w.isML307C() { + w.Modem.SetStoredSMSHandler(w.handleML307CStoredSMS) + return + } w.Modem.SetSMSReadinessCheck(func() error { _, err := w.resolveSMSIdentity() return err diff --git a/internal/device/vowifi_delivery_store.go b/internal/device/vowifi_delivery_store.go index 936fa51a..aff672cc 100644 --- a/internal/device/vowifi_delivery_store.go +++ b/internal/device/vowifi_delivery_store.go @@ -2,6 +2,7 @@ package device import ( "errors" + "strings" "time" "github.com/iniwex5/vowifi-go/runtimehost/messaging" @@ -95,6 +96,9 @@ func (vowifiDeliveryStore) LoadInboundFragments( } result := make([]messaging.StoredInboundFragment, 0, len(rows)) for _, row := range rows { + if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) { + continue + } // The rows already match the owner's canonical ICCID and IMSI. Hand // the owner back as given so imscore's exact owner check accepts // fragments saved on another device or under a padded ICCID. diff --git a/internal/modem/at_parse.go b/internal/modem/at_parse.go index 1dda7a9a..ec586a6f 100644 --- a/internal/modem/at_parse.go +++ b/internal/modem/at_parse.go @@ -436,7 +436,13 @@ func extractSMSPDURecordsAfterPrefix(resp string, prefix string) []SMSPDURecord index, err := strconv.Atoi(strings.TrimSpace(fields[0])) if err == nil { pdu, _ := smscodec.TrimFullPDUHexByATHeader(next, lines[i]) - out = append(out, SMSPDURecord{Index: index, PDU: pdu}) + status := -1 + if len(fields) > 1 { + if parsed, err := strconv.Atoi(fields[1]); err == nil { + status = parsed + } + } + out = append(out, SMSPDURecord{Index: index, Status: status, PDU: pdu}) } } i++ diff --git a/internal/modem/commands.go b/internal/modem/commands.go index cc8ed1e8..2f3c5289 100644 --- a/internal/modem/commands.go +++ b/internal/modem/commands.go @@ -215,19 +215,54 @@ func (m *Manager) SMSReadPDU(index string) (string, error) { } type SMSPDURecord struct { - Index int - PDU string + Index int + Status int + PDU string } +func (r SMSPDURecord) Received() bool { return r.Status == 0 || r.Status == 1 } + func (m *Manager) SMSListAllPDURecords() ([]SMSPDURecord, error) { - resp, err := m.ExecuteAT("AT+CMGL=4", 10*time.Second) + return m.smsListAllPDURecords(false) +} + +func (m *Manager) smsListAllPDURecords(verify bool) ([]SMSPDURecord, error) { + execute := m.ExecuteAT + if verify { + execute = m.ExecuteATSilent + } + resp, err := execute("AT+CMGL=4", 10*time.Second) if err != nil { return nil, err } if strings.TrimSpace(resp) == "OK" { return nil, nil } - return extractSMSPDURecordsAfterPrefix(resp, "+CMGL:"), nil + records := extractSMSPDURecordsAfterPrefix(resp, "+CMGL:") + if verify { + headers, data := 0, 0 + for _, line := range splitLines(resp) { + switch { + case line == "", line == "OK": + case strings.HasPrefix(line, "+CMGL:"): + headers++ + default: + if _, err := hex.DecodeString(line); err != nil { + return nil, errors.New("unexpected CMGL response line") + } + data++ + } + } + if headers != len(records) || data != len(records) { + return nil, errors.New("incomplete CMGL response") + } + for _, record := range records { + if record.Index < 0 || record.Status < 0 || record.Status > 3 { + return nil, errors.New("invalid CMGL record") + } + } + } + return records, nil } func (m *Manager) SMSListAllPDU() ([]string, error) { diff --git a/internal/modem/manager.go b/internal/modem/manager.go index ec606a18..c227b00f 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -121,6 +121,8 @@ type Manager struct { smsCallback SMSCallback smsProcessor SMSProcessor smsReadinessCheck func() error + smsStorageMu sync.Mutex + storedSMSHandler func(storage, index string) newSMSHandler func(index string) // 处理新短信索引的回调 (用于 bubble up URC) disableURCRead bool // 如果启用 QMI,禁用 AT 自动读取 simStatusHandler func(inserted *bool, state string) @@ -1496,8 +1498,16 @@ func (m *Manager) handleURC(line string) { m.infoMu.RLock() disabled := m.disableURCRead handler := m.newSMSHandler + storedHandler := m.storedSMSHandler m.infoMu.RUnlock() + if storedHandler != nil { + if !disabled { + storedHandler(storage, index) + } + return + } + if handler != nil { go handler(index) return @@ -2127,6 +2137,10 @@ func (m *Manager) SendSMS(phone, message string) error { // SendSMSWithOptions 使用 PDU 模式发送短信,并允许调用方指定文本编码策略。 func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.SubmitOptions) error { + if m.atProfile == ATProfileML307C { + m.smsStorageMu.Lock() + defer m.smsStorageMu.Unlock() + } m.SetBusy(true) defer m.SetBusy(false) diff --git a/internal/modem/manager_sms_storage_test.go b/internal/modem/manager_sms_storage_test.go index be5de9aa..06f5185e 100644 --- a/internal/modem/manager_sms_storage_test.go +++ b/internal/modem/manager_sms_storage_test.go @@ -51,6 +51,62 @@ func TestHandleCMTIUsesIndicatedStorageForReadAndDelete(t *testing.T) { } } +func TestML307CSMSInboxRestoresStorageAfterDeleteFailure(t *testing.T) { + m := newRunningTestManager(t) + m.SetStoredSMSHandler(func(_, _ string) {}) + m.atProfile = ATProfileML307C + const pdu = "0004038101F100006250724190410A3754747A0E4ABBCD6F793B4C4FBFDDA0F41CE47ED341617B38CD0E8BD96590F92D07E5DF7539283C1EBFEB6E3A889E87971B" + deleteErr := errors.New("slot could not be deleted") + done := make(chan []string, 1) + go func() { + selection := `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180` + done <- respondToCommands(t, m, 9, func(req commandRequest) { + switch req.cmd { + case "AT+CPMS?": + req.respChan <- selection + case `AT+CPMS="SM","SM","SM"`: + selection = `+CPMS: "SM",2,10,"SM",2,10,"SM",2,10` + req.respChan <- "OK" + case "AT+CMGL=4": + req.respChan <- "+CMGL: 7,0,,59\n" + pdu + "\n+CMGL: 8,3,,59\n" + pdu + case "AT+CMGR=7": + req.respChan <- "+CMGR: 1,,59\n" + pdu + case "AT+CMGD=7": + req.errChan <- deleteErr + case `AT+CPMS="ME","ME","ME"`: + selection = `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180` + req.respChan <- "OK" + default: + req.errChan <- errors.New("unexpected command " + req.cmd) + } + }) + }() + + err := m.WithSMSInbox(func(inbox *SMSInbox) error { + if err := inbox.Select("SM"); err != nil { + return err + } + records, err := inbox.List() + if err != nil { + return err + } + if len(records) != 2 || records[0].Index != 7 || !records[0].Received() || records[1].Received() { + t.Fatalf("CMGL records = %+v", records) + } + return inbox.DeleteMatching(records[0], func() error { return nil }) + }) + if !errors.Is(err, deleteErr) { + t.Fatalf("WithSMSInbox() error = %v, want delete failure", err) + } + want := []string{ + "AT+CPMS?", `AT+CPMS="SM","SM","SM"`, "AT+CPMS?", "AT+CMGL=4", + "AT+CPMS?", "AT+CMGR=7", "AT+CMGD=7", `AT+CPMS="ME","ME","ME"`, "AT+CPMS?", + } + if got := <-done; !reflect.DeepEqual(got, want) { + t.Fatalf("commands = %v, want %v", got, want) + } +} + func TestHandleCommandDispatchesCMTIWithoutPollutingResponse(t *testing.T) { m := newRunningTestManager(t) m.port = &timeoutSerialPort{} diff --git a/internal/modem/sms_inbox.go b/internal/modem/sms_inbox.go new file mode 100644 index 00000000..03d7d065 --- /dev/null +++ b/internal/modem/sms_inbox.go @@ -0,0 +1,143 @@ +package modem + +import ( + "errors" + "fmt" + "slices" + "strconv" + "strings" + "time" +) + +// SMSInbox keeps one AT receive transaction on a verified CPMS read store. +type SMSInbox struct { + modem *Manager + current []string + dirty bool +} + +func (m *Manager) SetStoredSMSHandler(handler func(storage, index string)) { + m.infoMu.Lock() + defer m.infoMu.Unlock() + m.storedSMSHandler = handler +} + +func (m *Manager) StoredSMSReceiving() bool { + m.infoMu.RLock() + defer m.infoMu.RUnlock() + return m.storedSMSHandler != nil && !m.disableURCRead +} + +// WithSMSInbox shares the storage lock with PDU sending. The callback may +// select both stores before the original three CPMS locations are restored. +func (m *Manager) WithSMSInbox(run func(*SMSInbox) error) (err error) { + m.smsStorageMu.Lock() + defer m.smsStorageMu.Unlock() + if !m.StoredSMSReceiving() { + return errors.New("AT SMS receive is paused") + } + initial, err := m.smsStorageSelection() + if err != nil { + return err + } + inbox := &SMSInbox{modem: m, current: initial} + defer func() { + if inbox.dirty { + err = errors.Join(err, m.setAndVerifySMSStorage(initial)) + } + }() + return run(inbox) +} + +func (m *Manager) smsStorageSelection() ([]string, error) { + reply, err := m.ExecuteATSilent("AT+CPMS?", 3*time.Second) + if err != nil { + return nil, err + } + selection := parseCPMSStorages(reply) + if len(selection) != 3 { + return nil, errors.New("cannot verify all three CPMS locations") + } + return selection, nil +} + +func (m *Manager) setAndVerifySMSStorage(selection []string) error { + if _, err := m.ExecuteATSilent(cpmsSetCommand(selection...), 5*time.Second); err != nil { + return err + } + return m.verifySMSStorage(selection) +} + +func (m *Manager) verifySMSStorage(selection []string) error { + actual, err := m.smsStorageSelection() + if err != nil { + return err + } + if !slices.Equal(actual, selection) { + return fmt.Errorf("CPMS selected %v, expected %v", actual, selection) + } + return nil +} + +func (inbox *SMSInbox) Select(storage string) error { + storage = strings.ToUpper(strings.TrimSpace(storage)) + if storage != "SM" && storage != "ME" { + return fmt.Errorf("unsupported SMS read store %q", storage) + } + if inbox.current == nil { + return errors.New("CPMS selection failed in this transaction") + } + if inbox.current[0] == storage { + return nil + } + // ML307C accepts the same store for all three locations. + selection := []string{storage, storage, storage} + inbox.dirty = true + inbox.current = nil + if err := inbox.modem.setAndVerifySMSStorage(selection); err != nil { + return err + } + inbox.current = selection + return nil +} + +func (inbox *SMSInbox) List() ([]SMSPDURecord, error) { + return inbox.modem.smsListAllPDURecords(true) +} + +func (inbox *SMSInbox) Read(index int) (SMSPDURecord, error) { + reply, err := inbox.modem.ExecuteATSilent("AT+CMGR="+strconv.Itoa(index), 5*time.Second) + if err != nil { + return SMSPDURecord{}, err + } + header, _ := findLineWithPrefix(reply, "+CMGR:") + fields := parseCommaFields(parseURCAfterColon(header)) + pdu, ok := extractSMSPDUAfterPrefix(reply, "+CMGR:") + if !ok || len(fields) == 0 { + return SMSPDURecord{}, errors.New("incomplete CMGR record") + } + status, err := strconv.Atoi(fields[0]) + if err != nil { + return SMSPDURecord{}, errors.New("invalid CMGR status") + } + return SMSPDURecord{Index: index, Status: status, PDU: pdu}, nil +} + +// DeleteMatching confirms that the selected store and slot still match the +// committed PDU. check runs just before the delete to recheck SIM ownership. +func (inbox *SMSInbox) DeleteMatching(record SMSPDURecord, check func() error) error { + if err := inbox.modem.verifySMSStorage(inbox.current); err != nil { + return err + } + current, err := inbox.Read(record.Index) + if err != nil { + return err + } + if !current.Received() || !strings.EqualFold(current.PDU, record.PDU) { + return errors.New("SMS slot changed before deletion") + } + if err := check(); err != nil { + return err + } + return inbox.modem.DeleteSMS(uint32(record.Index)) +} diff --git a/pkg/smscodec/pdu.go b/pkg/smscodec/pdu.go index ba4606af..d87f0ec5 100644 --- a/pkg/smscodec/pdu.go +++ b/pkg/smscodec/pdu.go @@ -369,6 +369,35 @@ type ConcatInfo struct { Seq int // 当前序号 (1-based) } +type ATDeliverSMS struct { + Sender string + Content string + Timestamp time.Time + SCTS string + Concat ConcatInfo + Binary bool +} + +// DecodeATDeliverSMS decodes a full PDU from an AT storage slot, preserving +// the original SCTS octets used to separate multipart sessions. +func DecodeATDeliverSMS(fullPDU []byte) (ATDeliverSMS, error) { + if len(fullPDU) == 0 || 1+int(fullPDU[0]) >= len(fullPDU) { + return ATDeliverSMS{}, errors.New("invalid SMSC length") + } + tpduBytes := fullPDU[1+int(fullPDU[0]):] + _, _, udOffset, _, alphabet, ok := deliverTPDULayout(tpduBytes) + if !ok { + return ATDeliverSMS{}, errors.New("invalid SMS-DELIVER TPDU layout") + } + part := ATDeliverSMS{ + SCTS: hex.EncodeToString(tpduBytes[udOffset-8 : udOffset-1]), + Binary: alphabet == tpdu.Alpha8Bit, + } + var err error + part.Sender, part.Content, part.Timestamp, part.Concat, err = DecodeDeliverTPDU(tpduBytes) + return part, err +} + // DecodeDeliverTPDU 解码下行短信 TPDU,返回发送方号码、文本内容、发送时间、和 concat 分片信息。 // 如果 TPDU 包含 UDH concatenation header(长短信分片),concat.IsConcat 为 true。 func DecodeDeliverTPDU(tpduBytes []byte) (sender string, text string, ts time.Time, concat ConcatInfo, err error) { From 9db03ed2db592ab039e02026bad53f72ba0e3673 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 14:33:51 +0800 Subject: [PATCH 04/39] fix(modem): read ML307C firmware with MSWVER --- internal/modem/at_profile.go | 26 ++++++++++++++++++++++++++ internal/modem/at_profile_test.go | 13 +++++++++++++ internal/modem/commands.go | 4 ++-- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/internal/modem/at_profile.go b/internal/modem/at_profile.go index dd8f5220..1201010b 100644 --- a/internal/modem/at_profile.go +++ b/internal/modem/at_profile.go @@ -29,6 +29,32 @@ func (p ATProfile) parseIMEI(resp string) string { return parseIMEI(resp) } +func (p ATProfile) firmwareCommand() string { + if p == ATProfileML307C { + return "AT+MSWVER" + } + return "AT+CGMR" +} + +func (p ATProfile) parseFirmware(resp string) string { + if p != ATProfileML307C { + return parseFirmware(resp) + } + + // MSWVER reports model, firmware version and build on separate lines. + var fields []string + for _, line := range splitLines(resp) { + if line == "" || line == "OK" || line == "AT+MSWVER" || strings.HasPrefix(line, "+") { + continue + } + fields = append(fields, line) + } + if len(fields) != 3 { + return "" + } + return fields[1] + " / " + fields[2] +} + func (p ATProfile) iccidCommand() string { if p == ATProfileML307C { return "AT+MCCID" diff --git a/internal/modem/at_profile_test.go b/internal/modem/at_profile_test.go index 142a24c8..b5734ebf 100644 --- a/internal/modem/at_profile_test.go +++ b/internal/modem/at_profile_test.go @@ -20,6 +20,7 @@ func TestML307CATQueries(t *testing.T) { fixtures := map[string][]string{ "AT+CGSN=1": {"+CGSN: 490154203237518", "OK"}, "AT+MCCID": {"+MCCID: 8988110000000000001F", "OK"}, + "AT+MSWVER": {"ML307C-DC-CN-MBRH0S00", "4.0.8.2506051839_release", "6c31ce603", "OK"}, "AT+CEREG?": {"+CEREG: 0,5", "OK"}, "AT+COPS?": {"+COPS: 0,0,\"CHN-UNICOM\",7", "OK"}, "AT+CSQ": {"+CSQ: 24,99", "OK"}, @@ -55,6 +56,9 @@ func TestML307CATQueries(t *testing.T) { if imei, err := m.QueryIMEI(); err != nil || imei != "490154203237518" { t.Fatalf("QueryIMEI() = %q, %v", imei, err) } + if firmware, err := m.QueryFirmware(); err != nil || firmware != "4.0.8.2506051839_release / 6c31ce603" { + t.Fatalf("QueryFirmware() = %q, %v", firmware, err) + } if iccid, err := m.QueryICCID(); err != nil || iccid != "8988110000000000001" { t.Fatalf("QueryICCID() = %q, %v", iccid, err) } @@ -84,6 +88,15 @@ func TestML307CATQueries(t *testing.T) { } } +func TestML307CFirmwareParsingRejectsIncompleteReply(t *testing.T) { + if got := ATProfileML307C.parseFirmware("AT+MSWVER\nML307C-DC-CN-MBRH0S00\n+CPIN: READY\nOK"); got != "" { + t.Fatalf("incomplete MSWVER reply parsed as %q", got) + } + if got := ATProfileDefault.parseFirmware("EC20EFAR06A05M4G\nOK"); got != "EC20EFAR06A05M4G" { + t.Fatalf("default firmware parsed as %q", got) + } +} + func TestML307CIMEIParsing(t *testing.T) { profile := ATProfileML307C for _, invalid := range []string{"20200X000000000000", "+CGSN: 4901542032375180", "+CGSN: 490154203237518,0"} { diff --git a/internal/modem/commands.go b/internal/modem/commands.go index 2f3c5289..6a7efeeb 100644 --- a/internal/modem/commands.go +++ b/internal/modem/commands.go @@ -24,11 +24,11 @@ func (m *Manager) QueryIMEI() (string, error) { } func (m *Manager) QueryFirmware() (string, error) { - resp, err := m.ExecuteATSilent("AT+CGMR", 2*time.Second) + resp, err := m.ExecuteATSilent(m.atProfile.firmwareCommand(), 2*time.Second) if err != nil { return "", err } - return parseFirmware(resp), nil + return m.atProfile.parseFirmware(resp), nil } func (m *Manager) QuerySIMInserted() (bool, error) { From 508fba4d30578d664cc6313c2d4644a0b5468f7e Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 15:01:33 +0800 Subject: [PATCH 05/39] fix(modem): keep ML307C SMS submission under one serial owner --- internal/modem/manager.go | 57 +++++--- internal/modem/sms_submit_ml307c.go | 179 +++++++++++++++++++++++ internal/modem/sms_submit_ml307c_test.go | 142 ++++++++++++++++++ 3 files changed, 357 insertions(+), 21 deletions(-) create mode 100644 internal/modem/sms_submit_ml307c.go create mode 100644 internal/modem/sms_submit_ml307c_test.go diff --git a/internal/modem/manager.go b/internal/modem/manager.go index c227b00f..3f55e283 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -50,9 +50,10 @@ type commandRequest struct { highPriority bool // 交互式模式支持 - interactive bool // 是否为交互式命令 (如发送短信) - waitPrompt bool // 是否等待 "> " 提示符 - followUp string // 后续指令 (当 waitPrompt=true 且收到提示符时发送) + interactive bool // 是否为交互式命令 (如发送短信) + waitPrompt bool // 是否等待 "> " 提示符 + followUp string // 后续指令 (当 waitPrompt=true 且收到提示符时发送) + smsFinalTimeout time.Duration // ML307C CMGS budget after a complete Ctrl+Z write. } // Manager 管理单个 EC20 模块的 AT 指令通信 @@ -718,6 +719,10 @@ func (m *Manager) handleCommand(req commandRequest) { m.handleFileUpload(req) return } + if m.atProfile == ATProfileML307C && req.smsFinalTimeout > 0 { + m.handleML307CSMS(req) + return + } startTime := time.Now() // 发送命令 @@ -1879,6 +1884,7 @@ func (m *Manager) executeAT(cmd string, timeout time.Duration, silent, highPrior req.interactive = false req.waitPrompt = false req.followUp = "" + req.smsFinalTimeout = 0 // 确保回收资源 defer func() { @@ -2144,7 +2150,9 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit m.SetBusy(true) defer m.SetBusy(false) - logger.Info(fmt.Sprintf("[%s] 准备发送短信 (PDU)", m.cfg.ID), "to", phone) + if m.atProfile != ATProfileML307C { + logger.Info(fmt.Sprintf("[%s] 准备发送短信 (PDU)", m.cfg.ID), "to", phone) + } // 确保处于 PDU 模式 if _, err := m.ExecuteATHigh("AT+CMGF=0", 3*time.Second); err != nil { @@ -2159,8 +2167,6 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit for i, pduHex := range pduHexList { tpduLen := tpduLenList[i] - logger.Debug(fmt.Sprintf("[%s] PDU 编码完成 (分片 %d/%d)", m.cfg.ID, i+1, len(pduHexList)), "pdu", pduHex, "tpdu_len", tpduLen) - req := commandRequest{ cmd: fmt.Sprintf("AT+CMGS=%d", tpduLen), // PDU 长度 (不含 SMSC) respChan: make(chan string, 1), @@ -2172,23 +2178,32 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit followUp: pduHex + "\x1A", // PDU + Ctrl+Z } - // 使用高优先级通道原子执行 - select { - case m.cmdChanHigh <- req: - case <-time.After(5 * time.Second): - return errors.New("command queue full") - } + if m.atProfile == ATProfileML307C { + req.timeout = ml307cSMSPromptTimeout + req.smsFinalTimeout = ml307cSMSResultTimeout + if err := m.sendML307CSMSPart(req); err != nil { + return fmt.Errorf("发送分片 %d: %w", i+1, err) + } + } else { + logger.Debug(fmt.Sprintf("[%s] PDU 编码完成 (分片 %d/%d)", m.cfg.ID, i+1, len(pduHexList)), "pdu", pduHex, "tpdu_len", tpduLen) + // 使用高优先级通道原子执行 + select { + case m.cmdChanHigh <- req: + case <-time.After(5 * time.Second): + return errors.New("command queue full") + } - // 等待最终响应 (OK) - select { - case resp := <-req.respChan: - if !strings.Contains(resp, "OK") && !strings.Contains(resp, "+CMGS:") { - return fmt.Errorf("发送分片 %d 失败: %s", i+1, resp) + // 等待最终响应 (OK) + select { + case resp := <-req.respChan: + if !strings.Contains(resp, "OK") && !strings.Contains(resp, "+CMGS:") { + return fmt.Errorf("发送分片 %d 失败: %s", i+1, resp) + } + case err := <-req.errChan: + return fmt.Errorf("发送分片 %d 失败: %w", i+1, err) + case <-time.After(20 * time.Second): + return errors.New("发送超时") } - case err := <-req.errChan: - return fmt.Errorf("发送分片 %d 失败: %w", i+1, err) - case <-time.After(20 * time.Second): - return errors.New("发送超时") } // 稍微等待下一段发信,防止模组队列溢出 diff --git a/internal/modem/sms_submit_ml307c.go b/internal/modem/sms_submit_ml307c.go new file mode 100644 index 00000000..1b120543 --- /dev/null +++ b/internal/modem/sms_submit_ml307c.go @@ -0,0 +1,179 @@ +package modem + +import ( + "errors" + "fmt" + "io" + "strconv" + "strings" + "time" + + "github.com/yibaiba/hideck/pkg/logger" +) + +const ( + ml307cSMSPromptTimeout = 5 * time.Second + ml307cSMSResultTimeout = 60 * time.Second +) + +var errML307CSMSResultUnknown = errors.New("短信已提交,结果未知,请勿自动重发") + +func (m *Manager) sendML307CSMSPart(req commandRequest) error { + select { + case <-m.stop: + return errors.New("AT 管理器停止") + case m.cmdChanHigh <- req: + case <-time.After(5 * time.Second): + return errors.New("command queue full") + } + select { + case err := <-req.errChan: + return err + case <-req.respChan: + return nil + case <-m.stopped: + select { + case err := <-req.errChan: + return err + case <-req.respChan: + return nil + default: + return errors.New("AT 管理器停止") + } + } +} + +// handleML307CSMS owns the AT queue from the command through the final +// response. No caller timeout can release the SMS lock mid-submission. +func (m *Manager) handleML307CSMS(req commandRequest) { + start := time.Now() + stage := "command" + promptSeen, submitted := false, false + written, mr, cms := 0, -1, -1 + report := func(err error) { + fields := []any{ + "device", m.cfg.ID, "stage", stage, "prompt_seen", promptSeen, + "planned_bytes", len(req.followUp), "written_bytes", written, + "elapsed", time.Since(start).Truncate(time.Millisecond), + } + if mr >= 0 { + fields = append(fields, "mr", mr) + } + if cms >= 0 { + fields = append(fields, "cms_code", cms) + } + if err != nil { + logger.Warn("ML307C 短信提交失败", append(fields, "err", err)...) + } else { + logger.Info("ML307C 短信提交已确认", fields...) + } + } + fail := func(err error, recoverPort, cancelInput bool) { + report(err) + if recoverPort { + if cancelInput { + // Cancel is best effort. Retire this owner even if ESC writes. + _, _ = m.port.Write([]byte{0x1B}) + } + m.markUnhealthy() + m.Stop() + m.notifyDisconnect("ml307c_sms_unsynchronized") + } + req.errChan <- err + } + + command := req.cmd + "\r" + n, err := m.port.Write([]byte(command)) + if n != len(command) { + err = errors.Join(err, io.ErrShortWrite) + } + if err != nil { + fail(fmt.Errorf("写入 CMGS 命令失败 (%d/%d): %w", n, len(command), err), true, false) + return + } + stage = "prompt" + timer := time.NewTimer(req.timeout) + defer timer.Stop() + for { + select { + case <-timer.C: + if submitted { + fail(errML307CSMSResultUnknown, true, false) + } else { + fail(errors.New("等待 CMGS 短信输入提示超时"), true, true) + } + return + case <-m.stop: + err := errors.New("AT 管理器停止") + if submitted { + err = errML307CSMSResultUnknown + } + fail(err, false, false) + return + case message := <-m.rxChan: + if message.Err != nil { + err := message.Err + if submitted { + err = errML307CSMSResultUnknown + } + fail(err, true, false) + return + } + line := strings.TrimSpace(message.Data) + switch { + case line == ">": + if promptSeen { + continue + } + stage = "submit" + promptSeen = true + written, err = m.port.Write([]byte(req.followUp)) + if written != len(req.followUp) { + fail(errors.Join(errors.New("短信 PDU 写入未完成"), err, io.ErrShortWrite), true, true) + return + } + if err != nil { + fail(errML307CSMSResultUnknown, true, false) + return + } + submitted = true + stage = "final" + timer.Reset(req.smsFinalTimeout) + case submitted && strings.HasPrefix(line, "+CMGS:"): + if value, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "+CMGS:"))); err == nil { + mr = value + } + case line == "OK": + m.resetATTimeoutWatchdog() + if !submitted { + fail(errors.New("未收到 CMGS 短信输入提示"), false, false) + return + } + if mr < 0 { + fail(errML307CSMSResultUnknown, false, false) + return + } + report(nil) + req.respChan <- fmt.Sprintf("+CMGS: %d", mr) + return + case line == "ERROR" || strings.HasPrefix(line, "+CMS ERROR:") || strings.HasPrefix(line, "+CME ERROR:"): + m.resetATTimeoutWatchdog() + if value, ok := strings.CutPrefix(line, "+CMS ERROR:"); ok { + if code, err := strconv.Atoi(strings.TrimSpace(value)); err == nil { + cms = code + } + } + err := errors.New("模组拒绝 CMGS 短信提交") + if cms >= 0 { + err = fmt.Errorf("模组拒绝 CMGS 短信提交 (+CMS ERROR: %d)", cms) + } + fail(err, false, false) + return + default: + if m.isURC(line) { + m.handleURC(line) + } + } + } + } +} diff --git a/internal/modem/sms_submit_ml307c_test.go b/internal/modem/sms_submit_ml307c_test.go new file mode 100644 index 00000000..d3ff6757 --- /dev/null +++ b/internal/modem/sms_submit_ml307c_test.go @@ -0,0 +1,142 @@ +package modem + +import ( + "errors" + "io" + "slices" + "strings" + "testing" + "time" +) + +type smsSubmitWirePort struct { + timeoutSerialPort + input chan string + done chan struct{} + write func([]byte) (int, error) +} + +func (p *smsSubmitWirePort) Read(buf []byte) (int, error) { + select { + case data := <-p.input: + return copy(buf, data), nil + case <-p.done: + return 0, io.EOF + } +} + +func (p *smsSubmitWirePort) Write(data []byte) (int, error) { return p.write(data) } + +func (p *smsSubmitWirePort) Close() error { + close(p.done) + return nil +} + +func TestML307CSMSSubmitWire(t *testing.T) { + const payload = "000100038177F700000341E110\x1A" + tests := []struct { + name string + profile ATProfile + short bool + missingFinal bool + wantErr error + }{ + {name: "ML307C success", profile: ATProfileML307C}, + {name: "ML307C result unknown", profile: ATProfileML307C, missingFinal: true, wantErr: errML307CSMSResultUnknown}, + {name: "ML307C short payload write", profile: ATProfileML307C, short: true, wantErr: io.ErrShortWrite}, + {name: "legacy CRLF", profile: ATProfileDefault}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := newRunningTestManager(t) + m.atProfile = tt.profile + wire := &smsSubmitWirePort{input: make(chan string, 2), done: make(chan struct{})} + m.port = wire + t.Cleanup(func() { m.StopAndWait(time.Second) }) + disconnected := make(chan string, 1) + m.SetOnDisconnectWithReason(func(reason string) { disconnected <- reason }) + + var writes []string + wire.write = func(data []byte) (int, error) { + n := len(data) + switch len(writes) { + case 0: + wire.input <- "\r\n> " + case 1: + if tt.short { + n-- + } else if !tt.missingFinal { + if tt.profile == ATProfileML307C { + // The final reply arrives after the prompt deadline. + time.AfterFunc(250*time.Millisecond, func() { wire.input <- "\r\n+CMGS: 8\r\nOK\r\n" }) + } else { + wire.input <- "\r\n+CMGS: 8\r\nOK\r\n" + } + } + } + writes = append(writes, string(data[:n])) + return n, nil + } + + req := commandRequest{ + cmd: "AT+CMGS=12", timeout: 200 * time.Millisecond, + respChan: make(chan string, 1), errChan: make(chan error, 1), + interactive: true, waitPrompt: true, followUp: payload, + } + if tt.profile == ATProfileML307C { + req.smsFinalTimeout = time.Second + if tt.missingFinal { + req.smsFinalTimeout = 10 * time.Millisecond + } + } + + m.loopWG.Add(2) + go func() { + defer m.loopWG.Done() + m.readLoop() + }() + go func() { + defer m.loopWG.Done() + m.handleCommand(<-m.cmdChanHigh) + }() + + wantWire := []string{"AT+CMGS=12\r", payload} + if tt.profile == ATProfileDefault { + m.cmdChanHigh <- req + select { + case reply := <-req.respChan: + if !strings.Contains(reply, "+CMGS: 8") { + t.Fatalf("legacy reply = %q", reply) + } + case err := <-req.errChan: + t.Fatal(err) + case <-time.After(time.Second): + t.Fatal("legacy submit did not complete") + } + wantWire[0] += "\n" + } else if err := m.sendML307CSMSPart(req); !errors.Is(err, tt.wantErr) { + t.Fatalf("submit error = %v, want %v", err, tt.wantErr) + } + if tt.short { + wantWire[1] = payload[:len(payload)-1] + wantWire = append(wantWire, "\x1B") + } + if tt.wantErr != nil { + select { + case reason := <-disconnected: + if reason != "ml307c_sms_unsynchronized" { + t.Fatalf("disconnect reason = %q", reason) + } + case <-time.After(time.Second): + t.Fatal("failed submit did not retire the serial owner") + } + if _, err := m.ExecuteAT("AT+CIMI", time.Millisecond); err == nil { + t.Fatal("AT query accepted on the retired serial owner") + } + } + if !slices.Equal(writes, wantWire) { + t.Fatalf("serial writes = %q, want %q", writes, wantWire) + } + }) + } +} From a9791a220b532785688f6aebba7d610931b8eaae Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 16:32:15 +0800 Subject: [PATCH 06/39] fix(phone): report unsupported ML307C native voice modes --- internal/api/card_policy.go | 19 +++- internal/api/card_policy_test.go | 56 ++++++++++ internal/api/phone.go | 3 + internal/api/route_adapters.go | 52 +++++++--- internal/device/modem_voice.go | 5 +- internal/device/phone_mode.go | 15 ++- internal/device/phone_mode_test.go | 103 +++++++++++++++++++ internal/device/policy_apply.go | 5 + internal/device/pool_vowifi_reconcile.go | 2 +- internal/device/pool_vowifi_runtime.go | 15 ++- internal/device/volte_start.go | 3 + internal/device/vowifi_start_orchestrator.go | 3 + web/src/services/phone.ts | 1 + web/src/utils/phoneModeSwitch.ts | 10 +- web/src/views/Phone.vue | 20 +++- web/tests/phoneModeSwitch.test.ts | 11 ++ 16 files changed, 291 insertions(+), 32 deletions(-) diff --git a/internal/api/card_policy.go b/internal/api/card_policy.go index f37399c9..af65760e 100644 --- a/internal/api/card_policy.go +++ b/internal/api/card_policy.go @@ -61,6 +61,13 @@ func (s *Server) cardPolicyStore() cardPolicyStore { // patchCardPolicyForDevice 解析设备当前 ICCID,对 card_policies 行执行原地修改并落库。 // mutate 在 resolve 后的副本上改字段(source 会被强制为 "user")。 func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardPolicy)) (iccid string, applied bool, err error) { + return s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error { + mutate(p) + return nil + }) +} + +func (s *Server) patchCardPolicyForDeviceChecked(deviceID string, mutate func(*db.CardPolicy) error) (iccid string, applied bool, err error) { worker := s.pool.GetWorker(deviceID) if worker == nil { return "", false, fmt.Errorf("设备未找到") @@ -73,7 +80,9 @@ func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardP if err != nil { return iccid, false, fmt.Errorf("获取卡策略失败: %w", err) } - mutate(&p) + if err := mutate(&p); err != nil { + return iccid, false, err + } p.Source = "user" db.NormalizeCardPolicy(&p) if err := s.cardPolicyStore().Upsert(p); err != nil { @@ -357,9 +366,15 @@ func normalizeCardPolicyIPVersion(value string) (string, error) { } func writeCardPolicyMutationError(c businessContext, err error) { + if writeLebaraUKRFLockError(c, err) { + return + } status := http.StatusInternalServerError - if errors.Is(err, errCardPolicyIdentityUnavailable) { + switch { + case errors.Is(err, errCardPolicyIdentityUnavailable): status = http.StatusConflict + case errors.Is(err, device.ErrML307CNativeVoiceUnavailable): + status = http.StatusUnprocessableEntity } c.JSON(status, gin.H{"status": "error", "message": err.Error()}) } diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go index 7fa8a467..e543fd8a 100644 --- a/internal/api/card_policy_test.go +++ b/internal/api/card_policy_test.go @@ -1,6 +1,7 @@ package api import ( + "context" "encoding/json" "errors" "fmt" @@ -17,6 +18,8 @@ import ( "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/db" "github.com/yibaiba/hideck/internal/device" + "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/vowifihost" ) type cardPolicyStoreStub struct { @@ -604,6 +607,59 @@ func TestPutCardPolicyAirplaneField(t *testing.T) { } } +func TestML307CPhoneModePatchUsesEffectivePolicy(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name, imsi, workerMode, storedMode, body string + wantEnabled bool + }{ + {name: "native VoLTE", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"volte"}`}, + {name: "direct dial", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"modem_voice"}`}, + {name: "China software fallback", imsi: "460011234567890", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"wifi"}`}, + {name: "stored VoLTE ahead of worker", imsi: "530010000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`}, + {name: "stored WiFi ahead of worker", imsi: "530010000000001", workerMode: "volte", storedMode: "wifi", body: `{"enabled":true}`, wantEnabled: true}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: "at", ATPort: "/dev/test-ml307c", PhoneMode: tc.workerMode} + manager, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + pool := device.NewPool(&config.Config{}) + host := vowifihost.NewManager() + host.LifecycleControllerForTest().TestRun = func(context.Context, vowifihost.LifecycleCommand) error { return nil } + setNestedPrivateField(t, pool, []string{"vowifiHost"}, host) + w := &device.Worker{ID: cfg.ID, Config: cfg, Modem: manager} + policy := db.CardPolicy{ICCID: "8986012345678901234", PhoneMode: tc.storedMode, Source: "auto"} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, policy.ICCID) + setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, tc.imsi) + injectWorker(pool, w) + store := &cardPolicyStoreStub{policy: policy} + s := &Server{pool: pool, cardPolicies: store} + r := gin.New() + r.PATCH("/api/devices/:device_id/vowifi", s.handleDeviceVoWiFiPatch) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPatch, "/api/devices/ml307c/vowifi", strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(rec, req) + + if tc.wantEnabled { + if rec.Code != http.StatusOK || !store.policy.VoWiFiEnabled || !w.Config.VoWiFiEnabled || + w.Config.PhoneMode != tc.storedMode || !w.Config.AirplaneEnabled { + t.Fatalf("code=%d body=%s policy=%+v worker=%+v", rec.Code, rec.Body.String(), store.policy, w.Config) + } + return + } + if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), device.ErrML307CNativeVoiceUnavailable.Error()) { + t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) + } + if store.policy != policy || w.Config != cfg { + t.Fatalf("the rejected request changed policy or worker: %+v, %+v", store.policy, w.Config) + } + }) + } +} + func TestLebaraUKRFLockRejectsNetworkAndCellular(t *testing.T) { gin.SetMode(gin.TestMode) openTestDB(t) diff --git a/internal/api/phone.go b/internal/api/phone.go index 909b119f..e7f58f58 100644 --- a/internal/api/phone.go +++ b/internal/api/phone.go @@ -109,6 +109,9 @@ func (s *Server) usePhoneDevices(c businessContext) { "software_ims_blocked": device.WorkerSoftwareIMSBlocked(worker), "rf_lock": class.RFLock(), } + if err := worker.CheckPhoneModeSupported(device.PhoneModeVoLTE); err != nil { + item["native_voice_unavailable_reason"] = err.Error() + } if region := s.phoneNumberRegion(worker.ID); region != "" { item["phone_region"] = region if code := phonenumbers.GetCountryCodeForRegion(region); code != 0 { diff --git a/internal/api/route_adapters.go b/internal/api/route_adapters.go index c0c4952a..70d62c11 100644 --- a/internal/api/route_adapters.go +++ b/internal/api/route_adapters.go @@ -1,6 +1,7 @@ package api import ( + "fmt" "net/http" "strings" @@ -128,41 +129,64 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { if *req.Enabled { // 落库:置 vowifi_enabled=true。若带 mode/data_strategy 则一并落库。 + w := s.pool.GetWorker(deviceID) mode := normalizePhoneMode(req.Mode) - if req.Mode == nil { - if w := s.pool.GetWorker(deviceID); w != nil { - mode = w.Config.PhoneMode - } + if req.Mode == nil && w != nil { + mode = w.Config.PhoneMode } if !s.allowModemVoiceModeChange(c, deviceID, mode) { return } strategy := normalizeDataStrategy(req.DataStrategy) forceVoLTE := false - if w := s.pool.GetWorker(deviceID); device.WorkerSoftwareIMSBlocked(w) && !device.IsModemVoiceMode(mode) { + if device.WorkerSoftwareIMSBlocked(w) && !device.IsModemVoiceMode(mode) { mode = device.PhoneModeVoLTE forceVoLTE = true } - if device.PhoneModeCampsOnCell(mode) { - class, classifyErr := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID) - if rejectLebaraUKRFUnlock(c, class, classifyErr) { + useStoredMode := req.Mode == nil && !forceVoLTE && w.CheckPhoneModeSupported(device.PhoneModeVoLTE) != nil + validateMode := func() error { + if err := w.CheckPhoneModeSupported(mode); err != nil { + return err + } + if device.PhoneModeCampsOnCell(mode) { + class, err := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID) + if err != nil { + return fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err) + } + if class.IsLebara { + return device.ErrLebaraUKRFLocked + } + } + return nil + } + if !useStoredMode { + if err := validateMode(); err != nil { + writeCardPolicyMutationError(c, err) return } } - if _, _, err := s.patchCardPolicyForDevice(deviceID, func(p *db.CardPolicy) { + if _, _, err := s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error { if req.Mode != nil || forceVoLTE { p.PhoneMode = mode + } else if useStoredMode { + mode = p.PhoneMode + if err := validateMode(); err != nil { + return err + } } if req.DataStrategy != nil { p.DataStrategy = strategy + } else if useStoredMode { + strategy = p.DataStrategy } applyVoWiFiEnableToCardPolicy(p) + return nil }); err != nil { writeCardPolicyMutationError(c, err) return } // 同步 w.Config,使概览即时切到 VoWiFi 模式面板(EnableVoWiFi 不碰 Config)。 - w := s.pool.GetWorker(deviceID) + w = s.pool.GetWorker(deviceID) prevMode, prevStrategy := "", "" if w != nil { prevMode = w.Config.PhoneMode @@ -173,10 +197,10 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { if prevStrategy == "" { prevStrategy = "on_demand" } - if req.Mode != nil || forceVoLTE { + if req.Mode != nil || forceVoLTE || useStoredMode { w.Config.PhoneMode = mode } - if req.DataStrategy != nil { + if req.DataStrategy != nil || useStoredMode { w.Config.DataStrategy = strategy } } @@ -221,8 +245,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { }) return } - modeChanged := req.Mode != nil && mode != prevMode - strategyChanged := req.DataStrategy != nil && strategy != prevStrategy + modeChanged := (req.Mode != nil || useStoredMode) && mode != prevMode + strategyChanged := (req.DataStrategy != nil || useStoredMode) && strategy != prevStrategy if s.pool.IsVoWiFiActive(deviceID) && (modeChanged || strategyChanged) { if err := s.pool.RestartVoWiFi(deviceID); err != nil { c.JSON(http.StatusInternalServerError, gin.H{ diff --git a/internal/device/modem_voice.go b/internal/device/modem_voice.go index 4a4628b5..a47b79cc 100644 --- a/internal/device/modem_voice.go +++ b/internal/device/modem_voice.go @@ -93,10 +93,13 @@ func (p *Pool) stopNativeVoLTEForModemVoice(id string) error { // This constructor is the infrastructure boundary. Optional tools and bundles // are accessed only after the user explicitly selects modem_voice. func (p *Pool) prepareModemVoice(ctx context.Context, id string) (*host.Resources, error) { + w := p.GetWorker(id) + if err := w.CheckPhoneModeSupported(PhoneModeModemVoice); err != nil { + return nil, err + } if runtime.GOOS != "linux" { return nil, errors.New("模组直拨音频目前仅支持 Linux") } - w := p.GetWorker(id) if w == nil || w.CurrentICCID() == "" { return nil, errors.New("模组直拨需要已识别的 SIM 卡") } diff --git a/internal/device/phone_mode.go b/internal/device/phone_mode.go index 269e4108..d4bc2001 100644 --- a/internal/device/phone_mode.go +++ b/internal/device/phone_mode.go @@ -11,6 +11,8 @@ import ( var ErrModemVoiceSoftwareIMS = errors.New("模组直拨模式不使用软件 IMS") +var ErrML307CNativeVoiceUnavailable = errors.New("ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨") + const ( PhoneModeWiFi = "wifi" PhoneModeCellular = "cellular" @@ -51,8 +53,8 @@ func cellularAlwaysData(cfg config.DeviceConfig) bool { return strings.TrimSpace(cfg.PhoneMode) == PhoneModeCellular && strings.TrimSpace(cfg.DataStrategy) == "always" } -// WorkerSoftwareIMSBlocked reports China MCC 460/461, which has no ePDG -// software IMS path in this stack. Phone service must use modem call control. +// WorkerSoftwareIMSBlocked reports whether the SIM's MCC is blocked by the +// software IMS policy. Phone service must use modem call control. func WorkerSoftwareIMSBlocked(w *Worker) bool { if w == nil { return false @@ -68,6 +70,15 @@ func WorkerSoftwareIMSBlocked(w *Worker) bool { return false } +// CheckPhoneModeSupported applies ML307C's native voice limit, including SIMs +// whose carrier policy requires native call control. +func (w *Worker) CheckPhoneModeSupported(mode string) error { + if w.isML307C() && (UsesModemPhoneControl(mode) || WorkerSoftwareIMSBlocked(w)) { + return ErrML307CNativeVoiceUnavailable + } + return nil +} + func forceSoftwareIMSBlockedToVoLTE(w *Worker, pol cardpolicy.Policy) { if w == nil || !PhoneServiceEnabled(w.Config) || !WorkerSoftwareIMSBlocked(w) || IsModemVoiceMode(w.Config.PhoneMode) { return diff --git a/internal/device/phone_mode_test.go b/internal/device/phone_mode_test.go index 740adb9c..87621af6 100644 --- a/internal/device/phone_mode_test.go +++ b/internal/device/phone_mode_test.go @@ -1,9 +1,16 @@ package device import ( + "context" + "errors" "testing" + "time" + "github.com/yibaiba/hideck/internal/backend" + "github.com/yibaiba/hideck/internal/cardpolicy" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/vowifihost" ) func TestWorkerSoftwareIMSBlockedChinaMCC(t *testing.T) { @@ -55,3 +62,99 @@ func TestApplyPhoneRadioPolicyByMode(t *testing.T) { t.Fatalf("volte should camp without forcing data: %+v", volte) } } + +func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { + for _, tc := range []struct { + name, imsi, mode string + airplane bool + }{ + {name: "China WiFi", imsi: "460011234567890", mode: PhoneModeWiFi}, + {name: "China cellular", imsi: "460011234567890", mode: PhoneModeCellular}, + {name: "overseas VoLTE", imsi: "530240000000001", mode: PhoneModeVoLTE}, + {name: "overseas direct dial", imsi: "530240000000001", mode: PhoneModeModemVoice, airplane: true}, + } { + t.Run(tc.name, func(t *testing.T) { + p := newDesiredVoWiFiTestPool(t, "ml307c", false, tc.imsi) + t.Cleanup(p.cancel) + w := p.GetWorker("ml307c") + w.Modem = newML307CPhoneTestModem(t, w.ID) + radio := &esimSwitchRestoreBackendStub{mode: backend.BackendAT, getMode: backend.ModeOnline} + w.Backend = radio + pol := cardpolicy.Policy{ + ICCID: w.CurrentICCID(), VoWiFiEnabled: true, AirplaneEnabled: tc.airplane, + NetworkEnabled: !tc.airplane, PhoneMode: tc.mode, DataStrategy: "on_demand", + } + resolver := &stubPolicyResolver{pol: pol} + p.SetPolicyResolver(resolver) + + result := p.resolveAndApplyPolicy(w, "test") + if !result.Applied || result.Err != nil { + t.Fatalf("apply policy: %+v", result) + } + if w.Config.VoWiFiEnabled || p.IsNativeVoLTE(w.ID) || p.IsModemVoice(w.ID) || + w.Config.PhoneMode != tc.mode || w.Config.AirplaneEnabled != tc.airplane || + w.Config.NetworkEnabled != pol.NetworkEnabled || !w.Config.SMSEnabled { + t.Fatalf("unexpected effective config: %+v", w.Config) + } + if tc.airplane { + if len(radio.setCalls) != 1 || radio.setCalls[0] != backend.ModeRFOff { + t.Fatalf("explicit airplane mode was not applied: %v", radio.setCalls) + } + } else if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() { + t.Fatalf("unsupported voice mode changed radio state: %v", radio.setCalls) + } + if resolver.pol != pol || p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test") { + t.Fatalf("card policy changed or still enables recovery: %+v", resolver.pol) + } + if tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular { + if err := p.EnableVoWiFi(w.ID); !errors.Is(err, ErrML307CNativeVoiceUnavailable) { + t.Fatalf("direct software IMS start error = %v", err) + } + if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() { + t.Fatalf("direct software IMS start changed radio state: %v", radio.setCalls) + } + } + }) + } +} + +func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) { + p := newDesiredVoWiFiTestPool(t, "ml307c", false, "530010000000001") + t.Cleanup(p.cancel) + w := p.GetWorker("ml307c") + w.Modem = newML307CPhoneTestModem(t, w.ID) + p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ + ICCID: w.CurrentICCID(), PhoneMode: PhoneModeWiFi, VoWiFiEnabled: true, + }}) + commands := make(chan vowifihost.LifecycleCommand, 1) + p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, cmd vowifihost.LifecycleCommand) error { + commands <- cmd + return nil + } + if result := p.resolveAndApplyPolicy(w, "test"); !result.Applied || result.Err != nil { + t.Fatalf("apply policy: %+v", result) + } + if !w.Config.VoWiFiEnabled || !w.Config.AirplaneEnabled || w.Config.PhoneMode != PhoneModeWiFi { + t.Fatalf("WiFi policy changed: %+v", w.Config) + } + if !p.currentCardPolicyAllowsVoWiFi(w, w.CurrentICCID(), "test") { + t.Fatal("One NZ lost software IMS recovery") + } + select { + case cmd := <-commands: + if cmd.DeviceID != w.ID { + t.Fatalf("unexpected recovery: %+v", cmd) + } + case <-time.After(time.Second): + t.Fatal("WiFi recovery was not scheduled") + } +} + +func newML307CPhoneTestModem(t *testing.T, id string) *modem.Manager { + t.Helper() + m, err := modem.NewWithATProfile(config.DeviceConfig{ID: id, DeviceBackend: "at", ATPort: "/dev/test-ml307c"}, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + return m +} diff --git a/internal/device/policy_apply.go b/internal/device/policy_apply.go index 738c5a1b..0c09f523 100644 --- a/internal/device/policy_apply.go +++ b/internal/device/policy_apply.go @@ -54,6 +54,11 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if err := validate(); err != nil { return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err} } + // Apply the unsupported mode as phone-off for this worker only. Keep the + // card's saved mode and explicit radio and network settings. + if worker.CheckPhoneModeSupported(pol.PhoneMode) != nil { + pol.VoWiFiEnabled = false + } // Finish the old call before projecting a policy that disallows new calls. // Failed hangup leaves the current session and policy available for retry. var finishNativeTransition func() diff --git a/internal/device/pool_vowifi_reconcile.go b/internal/device/pool_vowifi_reconcile.go index a0a96049..3360a487 100644 --- a/internal/device/pool_vowifi_reconcile.go +++ b/internal/device/pool_vowifi_reconcile.go @@ -227,7 +227,7 @@ func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason stri p.clearDesiredVoWiFiRecoverState(deviceID) return false } - if !pol.VoWiFiEnabled { + if w.CheckPhoneModeSupported(pol.PhoneMode) != nil || !pol.VoWiFiEnabled { p.clearDesiredVoWiFiRecoverState(deviceID) // logger.Info("VoWiFi 目标态恢复跳过:当前卡策略未开启 VoWiFi", // "event", "VOWIFI_DESIRED_RECOVER_SKIPPED_CARD_POLICY", diff --git a/internal/device/pool_vowifi_runtime.go b/internal/device/pool_vowifi_runtime.go index 124b5c1f..0f0eb672 100644 --- a/internal/device/pool_vowifi_runtime.go +++ b/internal/device/pool_vowifi_runtime.go @@ -205,11 +205,16 @@ func (p *Pool) enableVoWiFi(deviceID string, lifecycleGeneration uint64) error { if p.IsESIMSwitching(deviceID) { return fmt.Errorf("设备 %s 正在切卡,暂不允许启动 VoWiFi", deviceID) } - if w := p.GetWorker(deviceID); w != nil && IsNativeVoLTEMode(w.Config.PhoneMode) { - return p.EnableNativeVoLTE(deviceID) - } - if w := p.GetWorker(deviceID); w != nil && IsModemVoiceMode(w.Config.PhoneMode) { - return fmt.Errorf("设备 %s: %w", deviceID, ErrModemVoiceSoftwareIMS) + if w := p.GetWorker(deviceID); w != nil { + if err := w.CheckPhoneModeSupported(w.Config.PhoneMode); err != nil { + return err + } + if IsNativeVoLTEMode(w.Config.PhoneMode) { + return p.EnableNativeVoLTE(deviceID) + } + if IsModemVoiceMode(w.Config.PhoneMode) { + return fmt.Errorf("设备 %s: %w", deviceID, ErrModemVoiceSoftwareIMS) + } } p.stopNativeVoLTE(deviceID, "enable_vowifi") if err := p.stopModemVoice(deviceID); err != nil { diff --git a/internal/device/volte_start.go b/internal/device/volte_start.go index 8c459473..f94667ca 100644 --- a/internal/device/volte_start.go +++ b/internal/device/volte_start.go @@ -125,6 +125,9 @@ func (p *Pool) validateNativeVoLTEStart(deviceID string, start *nativeVoLTEStart if w == nil || w != start.worker || currentSIMOwnership(w) != start.sim || p.IsESIMSwitching(deviceID) { return errors.New("VoLTE 启动已失效:设备或 SIM 已更换或正在切卡") } + if err := w.CheckPhoneModeSupported(PhoneModeVoLTE); err != nil { + return err + } if !IsNativeVoLTEMode(w.Config.PhoneMode) || !PhoneServiceEnabled(w.Config) || w.Config.AirplaneEnabled { return errors.New("VoLTE 启动已失效:电话模式已切换或处于飞行模式") } diff --git a/internal/device/vowifi_start_orchestrator.go b/internal/device/vowifi_start_orchestrator.go index 110223cb..6ef07a20 100644 --- a/internal/device/vowifi_start_orchestrator.go +++ b/internal/device/vowifi_start_orchestrator.go @@ -151,6 +151,9 @@ func (p *Pool) prepareVoWiFiStartContext(ctx context.Context, deviceID, traceID, if w == nil { return startCtx, fmt.Errorf("设备 %s 不存在", deviceID) } + if err := w.CheckPhoneModeSupported(w.Config.PhoneMode); err != nil { + return startCtx, err + } startCtx.worker = w if IsModemVoiceMode(w.Config.PhoneMode) { return startCtx, ErrModemVoiceSoftwareIMS diff --git a/web/src/services/phone.ts b/web/src/services/phone.ts index cafb825e..4dcc854f 100644 --- a/web/src/services/phone.ts +++ b/web/src/services/phone.ts @@ -29,6 +29,7 @@ export type PhoneDevice = { vowifi_enabled?: boolean vowifi_active?: boolean software_ims_blocked?: boolean + native_voice_unavailable_reason?: string phone_region?: string phone_country_code?: number rf_lock?: string diff --git a/web/src/utils/phoneModeSwitch.ts b/web/src/utils/phoneModeSwitch.ts index b7223cef..51816b53 100644 --- a/web/src/utils/phoneModeSwitch.ts +++ b/web/src/utils/phoneModeSwitch.ts @@ -6,7 +6,12 @@ export type PhoneModeWarning = { title: string; message: string } export function phoneModeDisabledReason(device: PhoneDevice | undefined, mode: string): string | undefined { if (!device) return '请先选择设备' if ((mode === 'wifi' || mode === 'cellular') && device.software_ims_blocked) { - return '此 SIM 卡不支持软件 IMS,请使用 VoLTE 或模组直拨' + return device.native_voice_unavailable_reason + ? `此 SIM 卡不支持软件 IMS。${device.native_voice_unavailable_reason}` + : '此 SIM 卡不支持软件 IMS,请使用 VoLTE 或模组直拨' + } + if ((mode === 'volte' || mode === 'modem_voice') && device.native_voice_unavailable_reason) { + return device.native_voice_unavailable_reason } if (phoneModeCampsOnCell(mode) && device.rf_lock) { return '此 SIM 卡禁止蜂窝驻网,不能切换到该模式' @@ -54,7 +59,8 @@ export async function confirmPhoneModeChange(options: ChangeOptions): Promise phone.devices.find((device) => device.id === sel const calleeError = computed(() => dialNumberError(callee.value, selected.value?.phone_region)) const canPlaceCall = computed(() => !!callee.value && !calleeError.value && !!selected.value + && !selectedModeBlocked.value && (isDeviceReady(selected.value) || selected.value.phone_mode === 'cellular' || selected.value.phone_mode === 'volte') && !isDeviceBusy(selected.value)) watch(call, (current) => { @@ -115,6 +116,9 @@ function deviceModeLabel(device?: PhoneDevice) { function deviceStatus(device?: PhoneDevice) { if (!device) return '未选择设备' if (isDeviceBusy(device)) return '通话占用' + if (device.native_voice_unavailable_reason && phoneModeDisabledReason(device, device.phone_mode || 'wifi')) { + return '当前通话方式不可用' + } const mode = deviceModeLabel(device) if (device.phone_mode === 'modem_voice') { if (device.voice.phase === 'restarting') return `${mode} · 重启模组中` @@ -147,6 +151,9 @@ const selectedMode = computed(() => { if (mode === 'cellular' || mode === 'volte' || mode === 'modem_voice') return mode return 'wifi' }) +const selectedModeBlocked = computed(() => selected.value?.native_voice_unavailable_reason + ? phoneModeDisabledReason(selected.value, selectedMode.value) + : undefined) const selectedStrategy = computed(() => selected.value?.data_strategy === 'always' ? 'always' : 'on_demand') const modePending = ref(false) @@ -473,7 +480,7 @@ async function sendDTMF(digit: string) { 模组直拨 -

+

+ {{ selectedModeBlocked || selected.native_voice_unavailable_reason }} +

+

{{ selected?.network_enabled ? (selectedStrategy === 'always' ? '网络已开,数据会保持连接。' : '网络已开,只有拨号时才连数据,挂断后关闭。') : '会正常驻网,待机不走流量。打蜂窝电话会临时打开数据。' }}

-
+

使用 SIM 卡拨打和接听,声音通过网页传输。接通后可用键盘按键。

重新准备
-

+

{{ selected?.software_ims_blocked ? '这张卡需要使用模组驻网通话,可选择 VoLTE 或已适配的模组直拨。打开「网络」才会用上网流量。' : selected?.native_volte?.uac_unusable @@ -517,7 +527,7 @@ async function sendDTMF(digit: string) { { + const reason = 'ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨' + const oneNZ = { ...device(), phone_region: 'NZ', native_voice_unavailable_reason: reason } + assert.equal(phoneModeDisabledReason(oneNZ, 'volte'), reason) + assert.equal(phoneModeDisabledReason(oneNZ, 'modem_voice'), reason) + assert.equal(phoneModeDisabledReason(oneNZ, 'wifi'), undefined) + assert.equal(phoneModeDisabledReason(oneNZ, 'cellular'), undefined) + const china = { ...oneNZ, phone_region: 'CN', software_ims_blocked: true } + assert.equal(phoneModeDisabledReason(china, 'wifi'), `此 SIM 卡不支持软件 IMS。${reason}`) +}) + test('mode radio buttons use the group change event, not clicks on disabled labels', () => { const source = readFileSync(new URL('../src/views/Phone.vue', import.meta.url), 'utf8') const group = source.match(//)![0] From 1648753e8dde831a3fb84ae65500dca19a478aa6 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:33:14 +0800 Subject: [PATCH 07/39] fix(sms): preserve unconfirmed submission outcomes --- internal/api/openapi.hideck.yaml | 11 ++- internal/api/sms_send_usecase.go | 29 ++++++++ internal/api/sms_send_usecase_test.go | 88 ++++++++++++++++++++++++ internal/db/db.go | 5 +- internal/db/sms_delivery.go | 1 + internal/device/vowifi_sms_send.go | 39 ++++++++--- internal/device/vowifi_sms_send_test.go | 17 +++++ internal/modem/manager.go | 25 ++++++- internal/modem/sms_submit_ml307c.go | 16 ++--- internal/modem/sms_submit_ml307c_test.go | 47 ++++++++++++- web/src/services/sms.ts | 7 +- web/src/views/Sms.vue | 11 ++- 12 files changed, 271 insertions(+), 25 deletions(-) create mode 100644 internal/api/sms_send_usecase_test.go diff --git a/internal/api/openapi.hideck.yaml b/internal/api/openapi.hideck.yaml index 70e07e2a..7d42af66 100644 --- a/internal/api/openapi.hideck.yaml +++ b/internal/api/openapi.hideck.yaml @@ -446,6 +446,12 @@ paths: application/json: schema: $ref: '#/components/schemas/SMSSendResponse' + '202': + description: 短信提交结果未知或仅确认了部分分段,请勿重发整条 + content: + application/json: + schema: + $ref: '#/components/schemas/SMSSendResponse' '400': $ref: '#/components/responses/ErrorMessage' '404': @@ -5205,9 +5211,12 @@ components: type: string parts_total: type: integer + parts_confirmed: + type: integer + description: 202 响应中模组已确认提交的分段数量 delivery_state: type: string - description: 通道发送状态;acked 仅表示发送端已受理,不保证收件手机已收到 + description: acked 表示发送端已受理;202 响应中的 unknown 表示结果未知,partial_ack 表示仅部分分段获确认 SMSDeliveryResponse: type: object diff --git a/internal/api/sms_send_usecase.go b/internal/api/sms_send_usecase.go index 2e8c9b47..3102cfef 100644 --- a/internal/api/sms_send_usecase.go +++ b/internal/api/sms_send_usecase.go @@ -1,10 +1,12 @@ package api import ( + "fmt" "net/http" "strings" "time" + "github.com/yibaiba/hideck/internal/db" "github.com/yibaiba/hideck/internal/device" "github.com/yibaiba/hideck/pkg/smscodec" @@ -64,6 +66,33 @@ func (s *Server) useSendSMS(c businessContext) { } messageID = strings.TrimSpace(routed.Outcome.MessageID) if err != nil { + if routed.Via == device.RoutedSMSViaCS && + (deliveryState == db.SMSDeliveryStateUnknown || deliveryState == db.SMSDeliveryStatePartialAck) { + if persistErr := saveRoutedSMSRecord(routedSMSRecord{ + Identity: routed.Identity, Sender: worker.ID, Recipient: req.Phone, + Content: req.Message, Status: db.SMSStatusSubmitUnconfirmed, + }); persistErr != nil { + logger.Warn("短信提交状态未确认记录入库失败", "device", deviceID, "err", persistErr) + } + message := "短信发送结果未知,请勿重发整条" + if deliveryState == db.SMSDeliveryStatePartialAck { + message = fmt.Sprintf("短信仅确认提交 %d/%d 段,请勿重发整条", routed.PartsConfirmed, partsTotal) + } else if routed.PartsConfirmed > 0 { + message = fmt.Sprintf("短信已确认提交 %d/%d 段,整体结果未知,请勿重发整条", routed.PartsConfirmed, partsTotal) + } + c.JSON(http.StatusAccepted, gin.H{ + "status": "uncertain", + "message": message, + "device": deviceID, + "phone": req.Phone, + "destination": routed.Destination, + "message_id": messageID, + "parts_total": partsTotal, + "parts_confirmed": routed.PartsConfirmed, + "delivery_state": deliveryState, + }) + return + } if routed.Via == device.RoutedSMSViaVoWiFi || routed.FellBackToCS { deliveryState = "failed" recordErr := device.RecordVoWiFiSMSSendFailure(s.pool, device.VoWiFiSMSSendFailure{ diff --git a/internal/api/sms_send_usecase_test.go b/internal/api/sms_send_usecase_test.go new file mode 100644 index 00000000..e457254e --- /dev/null +++ b/internal/api/sms_send_usecase_test.go @@ -0,0 +1,88 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vowifi-go/runtimehost/messaging" + "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/device" + "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/pkg/smscodec" +) + +func TestSendSMSRecordsUnconfirmedSubmission(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, test := range []struct { + name string + fallback bool + sendError error + state string + confirmed int + total int + }{ + { + name: "direct unknown", state: db.SMSDeliveryStateUnknown, total: 1, + sendError: modem.ErrSMSSubmitUnknown, + }, + { + name: "unknown after fallback", state: db.SMSDeliveryStateUnknown, fallback: true, confirmed: 1, total: 3, + sendError: &modem.SMSSubmitError{PartsConfirmed: 1, PartsTotal: 3, Err: modem.ErrSMSSubmitUnknown}, + }, + { + name: "partially accepted", state: db.SMSDeliveryStatePartialAck, confirmed: 1, total: 2, + sendError: &modem.SMSSubmitError{PartsConfirmed: 1, PartsTotal: 2, Err: errors.New("modem rejected submit")}, + }, + } { + t.Run(test.name, func(t *testing.T) { + openTestDB(t) + pool := device.NewPool(&config.Config{}) + worker := &device.Worker{ID: "sms-at", Config: config.DeviceConfig{VoWiFiEnabled: test.fallback}} + identity := device.SMSIdentity{ICCID: "8944000000000000601", IMSI: "234150000000601"} + pool.AttachWorkerWithSMSIdentityForTest(worker, identity) + imsCalls, csCalls := 0, 0 + pool.SetRoutedSMSTestSenders( + func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) { + imsCalls++ + return messaging.SendOutcome{MessageID: "ims-only", DeliveryState: "failed", + RecommendCSFallback: true}, messaging.ErrSMSNotReady + }, + func(string, string, string) error { csCalls++; return test.sendError }, + ) + server := &Server{pool: pool} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/api/sms/send", strings.NewReader( + `{"device_id":"sms-at","phone":"777","message":"test"}`)) + c.Request.Header.Set("Content-Type", "application/json") + server.handleSendSMS(c) + var response struct { + Status string `json:"status"` + DeliveryState string `json:"delivery_state"` + Message string `json:"message"` + MessageID string `json:"message_id"` + PartsTotal int `json:"parts_total"` + PartsConfirmed int `json:"parts_confirmed"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if recorder.Code != http.StatusAccepted || response.Status != "uncertain" || response.DeliveryState != test.state || + !strings.Contains(response.Message, "请勿重发整条") || response.MessageID != "" || + response.PartsTotal != test.total || response.PartsConfirmed != test.confirmed || csCalls != 1 || (imsCalls == 1) != test.fallback { + t.Fatalf("HTTP %d: %s (IMS calls %d, CS calls %d)", recorder.Code, recorder.Body, imsCalls, csCalls) + } + messages, err := db.GetSMSByICCID(identity.ICCID, 10) + if err != nil || len(messages) != 1 || messages[0].Type != 2 || messages[0].Status != db.SMSStatusSubmitUnconfirmed { + t.Fatalf("SMS history = %+v, err = %v", messages, err) + } + }) + } +} diff --git a/internal/db/db.go b/internal/db/db.go index ee1f8380..465c72bc 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -82,6 +82,9 @@ type PendingPhoneNumber struct { func (PendingPhoneNumber) TableName() string { return "pending_phone_numbers" } // SMS 短信表 (关联 IMSI) +// SMSStatusSubmitUnconfirmed marks an outbound attempt without complete confirmation. +const SMSStatusSubmitUnconfirmed = 4 + type SMS struct { ID uint `gorm:"primaryKey" json:"id"` IMSI string `gorm:"column:imsi;index:idx_sms_imsi_peer_ts,priority:1;index:idx_sms_imsi_ts,priority:1;index:idx_sms_fragment_session,priority:1" json:"imsi"` @@ -92,7 +95,7 @@ type SMS struct { Recipient string `json:"recipient"` Content string `json:"content"` Type int `json:"type"` // 1: 接收, 2: 发送 - Status int `json:"status"` // 0: 未读, 1: 已读, 2: 发送成功, 3: 发送失败 + Status int `json:"status"` // 0: 未读, 1: 已读, 2: 提交成功, 3: 发送失败, 4: 提交未完全确认 Timestamp time.Time `gorm:"index:idx_sms_imsi_peer_ts,priority:3,sort:desc;index:idx_sms_ts,sort:desc;index:idx_sms_imsi_ts,priority:2,sort:desc" json:"timestamp"` CreatedAt time.Time `json:"created_at"` FragmentSessionKey string `gorm:"column:fragment_session_key;index:idx_sms_fragment_session,priority:2" json:"-"` diff --git a/internal/db/sms_delivery.go b/internal/db/sms_delivery.go index 63aecacf..c44e8fb6 100644 --- a/internal/db/sms_delivery.go +++ b/internal/db/sms_delivery.go @@ -14,6 +14,7 @@ const ( SMSDeliveryStatePartialAck = "partial_ack" SMSDeliveryStateAcked = "acked" SMSDeliveryStateFailed = "failed" + SMSDeliveryStateUnknown = "unknown" ) const ( diff --git a/internal/device/vowifi_sms_send.go b/internal/device/vowifi_sms_send.go index 88ed77df..b7eee30d 100644 --- a/internal/device/vowifi_sms_send.go +++ b/internal/device/vowifi_sms_send.go @@ -9,6 +9,8 @@ import ( "github.com/iniwex5/vowifi-go/runtimehost" "github.com/iniwex5/vowifi-go/runtimehost/messaging" + "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/smscodec" ) @@ -19,12 +21,13 @@ const ( ) type routedSMSSendResult struct { - Via string - Outcome messaging.SendOutcome - FellBackToCS bool - Destination string - Identity SMSIdentity - IdentityRead bool + Via string + Outcome messaging.SendOutcome + FellBackToCS bool + PartsConfirmed int + Destination string + Identity SMSIdentity + IdentityRead bool } // ShouldFallbackVoWiFiSMSToCS reports whether IMS never accepted the MESSAGE. @@ -55,6 +58,10 @@ func sendRoutedSMS( return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome}, err } if csErr := sendCS(); csErr != nil { + if result := csSMSResult(csErr); result.Outcome.DeliveryState != "" { + result.FellBackToCS = true + return result, csErr + } return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome, FellBackToCS: true}, err } return routedSMSSendResult{Via: RoutedSMSViaCS, Outcome: outcome, FellBackToCS: true}, nil @@ -62,10 +69,24 @@ func sendRoutedSMS( if sendCS == nil { return routedSMSSendResult{Via: RoutedSMSViaCS}, errors.New("sms route: CS sender is unavailable") } - if err := sendCS(); err != nil { - return routedSMSSendResult{Via: RoutedSMSViaCS}, err + err := sendCS() + return csSMSResult(err), err +} + +func csSMSResult(err error) routedSMSSendResult { + result := routedSMSSendResult{Via: RoutedSMSViaCS} + var progress *modem.SMSSubmitError + if errors.As(err, &progress) { + result.Outcome.PartsTotal = progress.PartsTotal + result.PartsConfirmed = progress.PartsConfirmed } - return routedSMSSendResult{Via: RoutedSMSViaCS}, nil + switch { + case errors.Is(err, modem.ErrSMSSubmitUnknown): + result.Outcome.DeliveryState = db.SMSDeliveryStateUnknown + case result.PartsConfirmed > 0: + result.Outcome.DeliveryState = db.SMSDeliveryStatePartialAck + } + return result } // SendRoutedSMS sends via VoWiFi when that path is selected, and falls back to diff --git a/internal/device/vowifi_sms_send_test.go b/internal/device/vowifi_sms_send_test.go index 1ae70cdb..083deba1 100644 --- a/internal/device/vowifi_sms_send_test.go +++ b/internal/device/vowifi_sms_send_test.go @@ -12,6 +12,7 @@ import ( "github.com/iniwex5/vowifi-go/runtimehost" "github.com/iniwex5/vowifi-go/runtimehost/messaging" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/smscodec" ) @@ -297,6 +298,22 @@ func TestSendRoutedSMSKeepsVoWiFiErrorWhenCSAlsoFails(t *testing.T) { } } +func TestSendRoutedSMSKeepsUnknownCSFallbackResult(t *testing.T) { + imsErr := errors.New("503") + csErr := fmt.Errorf("CS submit: %w", modem.ErrSMSSubmitUnknown) + calls := 0 + result, err := sendRoutedSMS(true, + func() (messaging.SendOutcome, error) { + return messaging.SendOutcome{MessageID: "ims-1", RecommendCSFallback: true, DeliveryState: "failed"}, imsErr + }, + func() error { calls++; return csErr }, + ) + if err != csErr || !result.FellBackToCS || result.Via != RoutedSMSViaCS || + result.Outcome.DeliveryState != "unknown" || result.Outcome.MessageID != "" || calls != 1 { + t.Fatalf("fallback result=%+v err=%v CS calls=%d", result, err, calls) + } +} + type voWiFiSMSSendResult struct { outcome messaging.SendOutcome err error diff --git a/internal/modem/manager.go b/internal/modem/manager.go index 3f55e283..a264e12b 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -2136,6 +2136,25 @@ func (m *Manager) DeleteSMS(index uint32) error { return err } +// ErrSMSSubmitUnknown means the payload was written but acceptance is unconfirmed. +var ErrSMSSubmitUnknown = errors.New("短信发送结果未知,请勿自动重发") + +// SMSSubmitError retains the segment counts when submission stopped early. +type SMSSubmitError struct { + PartsTotal int + PartsConfirmed int + Err error +} + +func (e *SMSSubmitError) Error() string { + if e.PartsConfirmed == 0 { + return e.Err.Error() + } + return fmt.Sprintf("短信已确认提交 %d/%d 段: %v", e.PartsConfirmed, e.PartsTotal, e.Err) +} + +func (e *SMSSubmitError) Unwrap() error { return e.Err } + // SendSMS 使用 PDU 模式发送短信 func (m *Manager) SendSMS(phone, message string) error { return m.SendSMSWithOptions(phone, message, smscodec.SubmitOptions{}) @@ -2182,7 +2201,11 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit req.timeout = ml307cSMSPromptTimeout req.smsFinalTimeout = ml307cSMSResultTimeout if err := m.sendML307CSMSPart(req); err != nil { - return fmt.Errorf("发送分片 %d: %w", i+1, err) + partErr := fmt.Errorf("发送分片 %d: %w", i+1, err) + if i > 0 || errors.Is(err, ErrSMSSubmitUnknown) { + return &SMSSubmitError{PartsTotal: len(pduHexList), PartsConfirmed: i, Err: partErr} + } + return partErr } } else { logger.Debug(fmt.Sprintf("[%s] PDU 编码完成 (分片 %d/%d)", m.cfg.ID, i+1, len(pduHexList)), "pdu", pduHex, "tpdu_len", tpduLen) diff --git a/internal/modem/sms_submit_ml307c.go b/internal/modem/sms_submit_ml307c.go index 1b120543..27bee011 100644 --- a/internal/modem/sms_submit_ml307c.go +++ b/internal/modem/sms_submit_ml307c.go @@ -16,8 +16,6 @@ const ( ml307cSMSResultTimeout = 60 * time.Second ) -var errML307CSMSResultUnknown = errors.New("短信已提交,结果未知,请勿自动重发") - func (m *Manager) sendML307CSMSPart(req commandRequest) error { select { case <-m.stop: @@ -62,7 +60,9 @@ func (m *Manager) handleML307CSMS(req commandRequest) { if cms >= 0 { fields = append(fields, "cms_code", cms) } - if err != nil { + if errors.Is(err, ErrSMSSubmitUnknown) { + logger.Warn("ML307C 短信提交结果未知", append(fields, "err", err)...) + } else if err != nil { logger.Warn("ML307C 短信提交失败", append(fields, "err", err)...) } else { logger.Info("ML307C 短信提交已确认", fields...) @@ -98,7 +98,7 @@ func (m *Manager) handleML307CSMS(req commandRequest) { select { case <-timer.C: if submitted { - fail(errML307CSMSResultUnknown, true, false) + fail(ErrSMSSubmitUnknown, true, false) } else { fail(errors.New("等待 CMGS 短信输入提示超时"), true, true) } @@ -106,7 +106,7 @@ func (m *Manager) handleML307CSMS(req commandRequest) { case <-m.stop: err := errors.New("AT 管理器停止") if submitted { - err = errML307CSMSResultUnknown + err = ErrSMSSubmitUnknown } fail(err, false, false) return @@ -114,7 +114,7 @@ func (m *Manager) handleML307CSMS(req commandRequest) { if message.Err != nil { err := message.Err if submitted { - err = errML307CSMSResultUnknown + err = ErrSMSSubmitUnknown } fail(err, true, false) return @@ -133,7 +133,7 @@ func (m *Manager) handleML307CSMS(req commandRequest) { return } if err != nil { - fail(errML307CSMSResultUnknown, true, false) + fail(ErrSMSSubmitUnknown, true, false) return } submitted = true @@ -150,7 +150,7 @@ func (m *Manager) handleML307CSMS(req commandRequest) { return } if mr < 0 { - fail(errML307CSMSResultUnknown, false, false) + fail(ErrSMSSubmitUnknown, false, false) return } report(nil) diff --git a/internal/modem/sms_submit_ml307c_test.go b/internal/modem/sms_submit_ml307c_test.go index d3ff6757..d5e7a62c 100644 --- a/internal/modem/sms_submit_ml307c_test.go +++ b/internal/modem/sms_submit_ml307c_test.go @@ -7,6 +7,8 @@ import ( "strings" "testing" "time" + + "github.com/yibaiba/hideck/pkg/smscodec" ) type smsSubmitWirePort struct { @@ -42,7 +44,7 @@ func TestML307CSMSSubmitWire(t *testing.T) { wantErr error }{ {name: "ML307C success", profile: ATProfileML307C}, - {name: "ML307C result unknown", profile: ATProfileML307C, missingFinal: true, wantErr: errML307CSMSResultUnknown}, + {name: "ML307C result unknown", profile: ATProfileML307C, missingFinal: true, wantErr: ErrSMSSubmitUnknown}, {name: "ML307C short payload write", profile: ATProfileML307C, short: true, wantErr: io.ErrShortWrite}, {name: "legacy CRLF", profile: ATProfileDefault}, } @@ -140,3 +142,46 @@ func TestML307CSMSSubmitWire(t *testing.T) { }) } } + +func TestML307CSMSSubmitPreservesConfirmedParts(t *testing.T) { + for _, test := range []struct { + name string + err error + }{ + {name: "unknown submit", err: ErrSMSSubmitUnknown}, + {name: "explicit rejection", err: errors.New("modem rejected submit")}, + } { + t.Run(test.name, func(t *testing.T) { + m := newRunningTestManager(t) + m.atProfile = ATProfileML307C + commands := make(chan []string, 1) + go func() { + var seen []string + for i := 0; i < 3; i++ { + req := <-m.cmdChanHigh + seen = append(seen, req.cmd) + if i == 2 { + req.errChan <- test.err + } else { + req.respChan <- "OK" + } + } + commands <- seen + }() + err := m.SendSMSWithOptions("777", strings.Repeat("A", 320), smscodec.SubmitOptions{}) + var progress *SMSSubmitError + if !errors.Is(err, test.err) || !errors.As(err, &progress) || progress.PartsConfirmed != 1 || progress.PartsTotal != 3 { + t.Fatalf("send progress = %+v, err = %v", progress, err) + } + seen := <-commands + if seen[0] != "AT+CMGF=0" || !strings.HasPrefix(seen[1], "AT+CMGS=") || !strings.HasPrefix(seen[2], "AT+CMGS=") { + t.Fatalf("commands = %v", seen) + } + select { + case req := <-m.cmdChanHigh: + t.Fatalf("unexpected submission after a segment failed: %q", req.cmd) + default: + } + }) + } +} diff --git a/web/src/services/sms.ts b/web/src/services/sms.ts index a589c8f9..21a4c8bc 100644 --- a/web/src/services/sms.ts +++ b/web/src/services/sms.ts @@ -121,10 +121,13 @@ export const smsService = { }, send(payload: SmsSendPayload) { return callService(async () => { - const res = await api.post<{ parts_total?: number; destination: string }>('/sms/send', payload) + const res = await api.post<{ parts_total?: number; destination: string; delivery_state?: string; message?: string }>('/sms/send', payload) + const { delivery_state, message } = res.data + const uncertain = res.status === 202 && (delivery_state === 'unknown' || delivery_state === 'partial_ack') return { partsTotal: Number(res.data?.parts_total || 0), - destination: res.data.destination + destination: res.data.destination, + submissionWarning: uncertain ? (message || '短信提交未完全确认,请勿重发整条') : '' } }) }, diff --git a/web/src/views/Sms.vue b/web/src/views/Sms.vue index a0aee340..5cd08a20 100644 --- a/web/src/views/Sms.vue +++ b/web/src/views/Sms.vue @@ -646,8 +646,12 @@ async function handleSendModal() { message: sendForm.value.message }) if (!result.ok) throw new Error(result.error.message || '发送失败') - const parts = result.data.partsTotal - ElMessage.success(`短信已提交${parts > 1 ? `(${parts}段)` : ''}`) + if (result.data.submissionWarning) { + ElMessage.warning(result.data.submissionWarning) + } else { + const parts = result.data.partsTotal + ElMessage.success(`短信已提交${parts > 1 ? `(${parts}段)` : ''}`) + } showSendModal.value = false setTimeout(async () => { await fetchMessagesAndThread() @@ -673,6 +677,9 @@ async function sendToCurrentThread() { try { const result = await smsStore.send({ iccid: t.iccid, phone: t.peer, message: text }) if (!result.ok) throw new Error(result.error.message || '发送失败') + if (result.data.submissionWarning) { + ElMessage.warning(result.data.submissionWarning) + } composer.value = '' if (viewingTarget.value && selectedThreadKey.value === t.key) { showLatestMessages() From e54a06cb266251d467a56abd1958a2c40a8f2665 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:33:15 +0800 Subject: [PATCH 08/39] fix(esim): scope bare channel responses to ML307C --- internal/modem/at_parse.go | 7 +++++-- internal/modem/at_parse_test.go | 23 +++++++++++++---------- internal/modem/commands.go | 2 +- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/internal/modem/at_parse.go b/internal/modem/at_parse.go index ec586a6f..24933bbd 100644 --- a/internal/modem/at_parse.go +++ b/internal/modem/at_parse.go @@ -555,10 +555,13 @@ func ParseUSBNetMode(resp string) (int, error) { // parseCCHO 解析 AT+CCHO 响应,提取逻辑通道号 // 响应格式: +CCHO: 。ML307C 返回单行裸通道号。 -func parseCCHO(resp string) (int, bool) { +func parseCCHO(resp string, profile ATProfile) (int, bool) { line, ok := findLineWithPrefix(resp, "+CCHO:") if !ok { - return parseBareCCHO(resp) + if profile == ATProfileML307C { + return parseBareCCHO(resp) + } + return -1, false } parts := strings.Split(line, ":") if len(parts) < 2 { diff --git a/internal/modem/at_parse_test.go b/internal/modem/at_parse_test.go index 87c3694a..c546ea02 100644 --- a/internal/modem/at_parse_test.go +++ b/internal/modem/at_parse_test.go @@ -219,22 +219,25 @@ func TestParseCCHO(t *testing.T) { tests := []struct { name string resp string + profile ATProfile channel int }{ {name: "prefixed", resp: "\r\n+CCHO: 2\r\nOK\r\n", channel: 2}, - {name: "ML307C", resp: "\r\n2\r\nOK\r\n", channel: 2}, - {name: "terminal stripped", resp: "2", channel: 2}, - {name: "only OK", resp: "OK", channel: -1}, - {name: "bare followed by ERROR", resp: "2\nERROR", channel: -1}, - {name: "command rejected", resp: "+CME ERROR: 3", channel: -1}, - {name: "multiple numbers", resp: "2\n3\nOK", channel: -1}, - {name: "number with suffix", resp: "2,3\nOK", channel: -1}, - {name: "basic channel", resp: "0\nOK", channel: -1}, - {name: "out of range", resp: "258\nOK", channel: -1}, + {name: "default rejects bare channel", resp: "2\r\nOK", channel: -1}, + {name: "ML307C prefixed", resp: "+CCHO: 2\r\nOK", profile: ATProfileML307C, channel: 2}, + {name: "ML307C bare", profile: ATProfileML307C, resp: "\r\n2\r\nOK\r\n", channel: 2}, + {name: "terminal stripped", profile: ATProfileML307C, resp: "2", channel: 2}, + {name: "only OK", profile: ATProfileML307C, resp: "OK", channel: -1}, + {name: "bare followed by ERROR", profile: ATProfileML307C, resp: "2\nERROR", channel: -1}, + {name: "command rejected", profile: ATProfileML307C, resp: "+CME ERROR: 3", channel: -1}, + {name: "multiple numbers", profile: ATProfileML307C, resp: "2\n3\nOK", channel: -1}, + {name: "number with suffix", profile: ATProfileML307C, resp: "2,3\nOK", channel: -1}, + {name: "basic channel", profile: ATProfileML307C, resp: "0\nOK", channel: -1}, + {name: "out of range", profile: ATProfileML307C, resp: "258\nOK", channel: -1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - channel, ok := parseCCHO(tt.resp) + channel, ok := parseCCHO(tt.resp, tt.profile) if channel != tt.channel || ok != (tt.channel > 0) { t.Fatalf("parseCCHO(%q) = (%d, %t), want (%d, %t)", tt.resp, channel, ok, tt.channel, tt.channel > 0) } diff --git a/internal/modem/commands.go b/internal/modem/commands.go index 6a7efeeb..64e0ab60 100644 --- a/internal/modem/commands.go +++ b/internal/modem/commands.go @@ -393,7 +393,7 @@ func (m *Manager) openLogicalChannel(aid, leaseOwner, sessionOwner string, class if err != nil { return -1, fmt.Errorf("打开 logical channel 失败: %w", err) } - channel, ok := parseCCHO(resp) + channel, ok := parseCCHO(resp, m.atProfile) if !ok { return -1, fmt.Errorf("解析 logical channel 响应失败: %s", resp) } From 2ef773a0a3c2ab5a9b458ecb894bb8c2fae261a5 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:33:15 +0800 Subject: [PATCH 09/39] test(phone): cover the unsupported mode switch guard --- web/tests/phonePresentation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/tests/phonePresentation.test.ts b/web/tests/phonePresentation.test.ts index 152be52c..1fde683e 100644 --- a/web/tests/phonePresentation.test.ts +++ b/web/tests/phonePresentation.test.ts @@ -253,7 +253,7 @@ test('wifi calling keeps a dedicated start switch under the mode control', () => assert.match(phoneView, /disableVoWiFi\(selectedDevice\.value\)/) assert.match(phoneView, /打开后开始注册。关掉只停服务,仍是 WiFi calling/) assert.match(phoneView, /if \(mode === selectedMode\.value\) \{[\s\S]*if \(mode === 'wifi'\) return/) - assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\)"/) + assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\) \|\| \(!!selectedModeBlocked && !selected\?\.vowifi_enabled\)"/) assert.doesNotMatch(phoneView, /modePending \|\| !!selected\?\.rf_lock/) assert.match(phoneView, /status === 'recovering' \|\| status === 'waiting_identity'/) assert.match(phoneView, /正在恢复英国身份/) From 60ef3172b8122573e217d5c47c0324f2e7e002c8 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:43:24 +0800 Subject: [PATCH 10/39] refactor(modem): centralize AT dialect configuration --- internal/modem/at_parse.go | 10 +-- internal/modem/at_parse_test.go | 2 +- internal/modem/at_profile.go | 141 ++++++++++++++++++++++-------- internal/modem/at_profile_test.go | 8 +- internal/modem/commands.go | 86 +++++++++--------- internal/modem/imei_probe.go | 15 +--- internal/modem/manager.go | 31 ++++--- internal/modem/runtime_role.go | 7 +- 8 files changed, 180 insertions(+), 120 deletions(-) diff --git a/internal/modem/at_parse.go b/internal/modem/at_parse.go index 24933bbd..0fc94086 100644 --- a/internal/modem/at_parse.go +++ b/internal/modem/at_parse.go @@ -555,12 +555,9 @@ func ParseUSBNetMode(resp string) (int, error) { // parseCCHO 解析 AT+CCHO 响应,提取逻辑通道号 // 响应格式: +CCHO: 。ML307C 返回单行裸通道号。 -func parseCCHO(resp string, profile ATProfile) (int, bool) { +func parseCCHO(resp string) (int, bool) { line, ok := findLineWithPrefix(resp, "+CCHO:") if !ok { - if profile == ATProfileML307C { - return parseBareCCHO(resp) - } return -1, false } parts := strings.Split(line, ":") @@ -575,7 +572,10 @@ func parseCCHO(resp string, profile ATProfile) (int, bool) { return -1, false } -func parseBareCCHO(resp string) (int, bool) { +func parseML307CCCHO(resp string) (int, bool) { + if channel, ok := parseCCHO(resp); ok { + return channel, true + } var channel int for _, line := range splitLines(resp) { if line == "" || line == "OK" { diff --git a/internal/modem/at_parse_test.go b/internal/modem/at_parse_test.go index c546ea02..2544171e 100644 --- a/internal/modem/at_parse_test.go +++ b/internal/modem/at_parse_test.go @@ -237,7 +237,7 @@ func TestParseCCHO(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - channel, ok := parseCCHO(tt.resp, tt.profile) + channel, ok := tt.profile.dialect().parseCCHO(tt.resp) if channel != tt.channel || ok != (tt.channel > 0) { t.Fatalf("parseCCHO(%q) = (%d, %t), want (%d, %t)", tt.resp, channel, ok, tt.channel, tt.channel > 0) } diff --git a/internal/modem/at_profile.go b/internal/modem/at_profile.go index 1201010b..3ea16cf5 100644 --- a/internal/modem/at_profile.go +++ b/internal/modem/at_profile.go @@ -13,34 +13,99 @@ const ( ATProfileML307C ) -func (p ATProfile) imeiCommand() string { - if p == ATProfileML307C { - return "AT+CGSN=1" - } - return "AT+CGSN" +type atTextQuery struct { + command string + parse func(string) string } -func (p ATProfile) parseIMEI(resp string) string { - if p == ATProfileML307C { - if line, ok := findLineWithPrefix(resp, "+CGSN:"); ok { - return parseIMEI(strings.TrimPrefix(line, "+CGSN:")) - } +type atRadioQuery struct { + command string + parse func(string) (mode, duplex, band string, channel uint32) +} + +type atCPINPresenceQuery struct { + parse func(string) (bool, error) + isAbsentError func(string) bool +} + +type atOwnedSMSSubmit struct { + promptTimeout time.Duration + finalTimeout time.Duration +} + +type atDialect struct { + imei atTextQuery + firmware atTextQuery + iccid atTextQuery + parseProbeIMEI func(string) string + missingIMEIError error + operatorFormat string + registration string + registrationPrefix string + radio atRadioQuery + radioFallback atRadioQuery + servingCell string + imsStatus string + usbnet string + simStatus string + cpinPresence *atCPINPresenceQuery + parseCCHO func(string) (int, bool) + voiceInit []string + ownedSMSSubmit *atOwnedSMSSubmit +} + +var defaultATDialect = atDialect{ + imei: atTextQuery{"AT+CGSN", parseIMEI}, + firmware: atTextQuery{"AT+CGMR", parseFirmware}, + iccid: atTextQuery{"AT+QCCID", parseQCCID}, + parseProbeIMEI: parseIMEI, + operatorFormat: "AT+COPS=3,2", + registration: "AT+CREG?", + registrationPrefix: "+CREG:", + radio: atRadioQuery{"AT+QNWINFO", parseQNWInfoRadio}, + radioFallback: atRadioQuery{"AT+COPS?", parseCOPSRadio}, + servingCell: "AT+QENG=\"servingcell\"", + imsStatus: "AT+QIMS?", + usbnet: "AT+QCFG=\"usbnet\"?", + simStatus: "AT+QSIMSTAT?", + parseCCHO: parseCCHO, + voiceInit: []string{"AT+CLIP=1", "AT+QPCMV=1,2"}, +} + +var ml307cATDialect = atDialect{ + imei: atTextQuery{"AT+CGSN=1", parseML307CIMEI}, + firmware: atTextQuery{"AT+MSWVER", parseML307CFirmware}, + iccid: atTextQuery{"AT+MCCID", parseMCCID}, + parseProbeIMEI: parseML307CProbeIMEI, + missingIMEIError: errors.New("invalid IMEI response"), + registration: "AT+CEREG?", + registrationPrefix: "+CEREG:", + radio: atRadioQuery{"AT+COPS?", parseCOPSRadio}, + cpinPresence: &atCPINPresenceQuery{parse: parseML307CCPIN, isAbsentError: isML307CNoSIMError}, + parseCCHO: parseML307CCCHO, + ownedSMSSubmit: &atOwnedSMSSubmit{promptTimeout: ml307cSMSPromptTimeout, finalTimeout: ml307cSMSResultTimeout}, +} + +func (profile ATProfile) dialect() *atDialect { + if profile == ATProfileML307C { + return &ml307cATDialect + } + return &defaultATDialect +} + +func parseML307CIMEI(resp string) string { + if line, ok := findLineWithPrefix(resp, "+CGSN:"); ok { + return parseIMEI(strings.TrimPrefix(line, "+CGSN:")) } return parseIMEI(resp) } -func (p ATProfile) firmwareCommand() string { - if p == ATProfileML307C { - return "AT+MSWVER" - } - return "AT+CGMR" +func parseML307CProbeIMEI(resp string) string { + // A serial read can end in the middle of an identifier. + return parseML307CIMEI(resp[:strings.LastIndexAny(resp, "\r\n")+1]) } -func (p ATProfile) parseFirmware(resp string) string { - if p != ATProfileML307C { - return parseFirmware(resp) - } - +func parseML307CFirmware(resp string) string { // MSWVER reports model, firmware version and build on separate lines. var fields []string for _, line := range splitLines(resp) { @@ -55,31 +120,31 @@ func (p ATProfile) parseFirmware(resp string) string { return fields[1] + " / " + fields[2] } -func (p ATProfile) iccidCommand() string { - if p == ATProfileML307C { - return "AT+MCCID" - } - return "AT+QCCID" +func parseMCCID(resp string) string { + return parseICCID(resp, "+MCCID:") } -func (p ATProfile) parseICCID(resp string) string { - if p == ATProfileML307C { - return parseICCID(resp, "+MCCID:") - } - return parseQCCID(resp) +func parseCOPSRadio(resp string) (string, string, string, uint32) { + mode, _ := parseCOPSAct(resp) + return mode, "", "", 0 } +const ( + cpinQuery = "AT+CPIN?" + cpinPrefix = "+CPIN:" +) + var ( errSIMNotInserted = errors.New("SIM not inserted") ErrSIMPINRequired = errors.New("SIM PIN or PUK required") ) func parseML307CCPIN(resp string) (bool, error) { - line, ok := findLineWithPrefix(resp, "+CPIN:") + line, ok := findLineWithPrefix(resp, cpinPrefix) if !ok { return false, errors.New("unrecognized CPIN response") } - state := strings.TrimSpace(strings.TrimPrefix(line, "+CPIN:")) + state := strings.TrimSpace(strings.TrimPrefix(line, cpinPrefix)) if IsSIMPINRequiredState(state) { return false, ErrSIMPINRequired } @@ -103,18 +168,18 @@ func IsSIMPINRequiredState(state string) bool { } } -func (m *Manager) queryML307CSIMInserted() (bool, error) { - resp, err := m.ExecuteATSilent("AT+CPIN?", 2*time.Second) +func (m *Manager) queryCPINSIMPresence(query *atCPINPresenceQuery) (bool, error) { + resp, err := m.ExecuteATSilent(cpinQuery, 2*time.Second) if errors.Is(err, errSIMNotInserted) { - m.cacheML307CSIMState(false, nil) + m.cacheCPINSIMState(false, nil) return false, nil } if err != nil { return false, err } - inserted, err := parseML307CCPIN(resp) + inserted, err := query.parse(resp) if err == nil || errors.Is(err, ErrSIMPINRequired) { - m.cacheML307CSIMState(inserted, err) + m.cacheCPINSIMState(inserted, err) } if errors.Is(err, ErrSIMPINRequired) { m.dispatchSIMStatusURC(nil, "SIM PIN") @@ -122,7 +187,7 @@ func (m *Manager) queryML307CSIMInserted() (bool, error) { return inserted, err } -func (m *Manager) cacheML307CSIMState(inserted bool, err error) { +func (m *Manager) cacheCPINSIMState(inserted bool, err error) { m.infoMu.Lock() defer m.infoMu.Unlock() m.simInserted = inserted diff --git a/internal/modem/at_profile_test.go b/internal/modem/at_profile_test.go index b5734ebf..4ae027a3 100644 --- a/internal/modem/at_profile_test.go +++ b/internal/modem/at_profile_test.go @@ -89,10 +89,10 @@ func TestML307CATQueries(t *testing.T) { } func TestML307CFirmwareParsingRejectsIncompleteReply(t *testing.T) { - if got := ATProfileML307C.parseFirmware("AT+MSWVER\nML307C-DC-CN-MBRH0S00\n+CPIN: READY\nOK"); got != "" { + if got := ATProfileML307C.dialect().firmware.parse("AT+MSWVER\nML307C-DC-CN-MBRH0S00\n+CPIN: READY\nOK"); got != "" { t.Fatalf("incomplete MSWVER reply parsed as %q", got) } - if got := ATProfileDefault.parseFirmware("EC20EFAR06A05M4G\nOK"); got != "EC20EFAR06A05M4G" { + if got := ATProfileDefault.dialect().firmware.parse("EC20EFAR06A05M4G\nOK"); got != "EC20EFAR06A05M4G" { t.Fatalf("default firmware parsed as %q", got) } } @@ -100,11 +100,11 @@ func TestML307CFirmwareParsingRejectsIncompleteReply(t *testing.T) { func TestML307CIMEIParsing(t *testing.T) { profile := ATProfileML307C for _, invalid := range []string{"20200X000000000000", "+CGSN: 4901542032375180", "+CGSN: 490154203237518,0"} { - if imei := profile.parseIMEI(invalid); imei != "" { + if imei := profile.dialect().imei.parse(invalid); imei != "" { t.Fatalf("invalid CGSN response %q parsed as %q", invalid, imei) } } - if imei := profile.parseIMEI("490154203237518"); imei != "490154203237518" { + if imei := profile.dialect().imei.parse("490154203237518"); imei != "490154203237518" { t.Fatalf("bare IMEI parsed as %q", imei) } } diff --git a/internal/modem/commands.go b/internal/modem/commands.go index 64e0ab60..21cd5240 100644 --- a/internal/modem/commands.go +++ b/internal/modem/commands.go @@ -12,35 +12,40 @@ import ( ) func (m *Manager) QueryIMEI() (string, error) { - resp, err := m.ExecuteATSilent(m.atProfile.imeiCommand(), 2*time.Second) + dialect := m.atProfile.dialect() + resp, err := m.ExecuteATSilent(dialect.imei.command, 2*time.Second) if err != nil { return "", err } - imei := m.atProfile.parseIMEI(resp) - if imei == "" && m.atProfile == ATProfileML307C { - return "", errors.New("invalid IMEI response") + imei := dialect.imei.parse(resp) + if imei == "" { + return "", dialect.missingIMEIError } return imei, nil } func (m *Manager) QueryFirmware() (string, error) { - resp, err := m.ExecuteATSilent(m.atProfile.firmwareCommand(), 2*time.Second) + query := m.atProfile.dialect().firmware + resp, err := m.ExecuteATSilent(query.command, 2*time.Second) if err != nil { return "", err } - return m.atProfile.parseFirmware(resp), nil + return query.parse(resp), nil } func (m *Manager) QuerySIMInserted() (bool, error) { - if m.atProfile == ATProfileML307C { - return m.queryML307CSIMInserted() + dialect := m.atProfile.dialect() + if query := dialect.cpinPresence; query != nil { + return m.queryCPINSIMPresence(query) } - if resp, err := m.ExecuteATSilent("AT+QSIMSTAT?", 2*time.Second); err == nil { - if inserted, ok := parseQSIMSTATInserted(resp); ok { - return inserted, nil + if cmd := dialect.simStatus; cmd != "" { + if resp, err := m.ExecuteATSilent(cmd, 2*time.Second); err == nil { + if inserted, ok := parseQSIMSTATInserted(resp); ok { + return inserted, nil + } } } - resp, err := m.ExecuteATSilent("AT+CPIN?", 2*time.Second) + resp, err := m.ExecuteATSilent(cpinQuery, 2*time.Second) if err != nil { return false, err } @@ -59,16 +64,17 @@ func (m *Manager) QueryIMSI() (string, error) { } func (m *Manager) QueryICCID() (string, error) { - resp, err := m.ExecuteATSilent(m.atProfile.iccidCommand(), 2*time.Second) + query := m.atProfile.dialect().iccid + resp, err := m.ExecuteATSilent(query.command, 2*time.Second) if err != nil { return "", err } - return m.atProfile.parseICCID(resp), nil + return query.parse(resp), nil } func (m *Manager) QueryOperator() (string, error) { - if m.atProfile != ATProfileML307C { - _, _ = m.ExecuteATSilent("AT+COPS=3,2", 2*time.Second) + if cmd := m.atProfile.dialect().operatorFormat; cmd != "" { + _, _ = m.ExecuteATSilent(cmd, 2*time.Second) } resp, err := m.ExecuteATSilent("AT+COPS?", 2*time.Second) if err != nil { @@ -78,15 +84,12 @@ func (m *Manager) QueryOperator() (string, error) { } func (m *Manager) QueryRegistration() (int, string, string, string, error) { - command, prefix := "AT+CREG?", "+CREG:" - if m.atProfile == ATProfileML307C { - command, prefix = "AT+CEREG?", "+CEREG:" - } - resp, err := m.ExecuteATSilent(command, 2*time.Second) + dialect := m.atProfile.dialect() + resp, err := m.ExecuteATSilent(dialect.registration, 2*time.Second) if err != nil { return 0, "", "", "", err } - regStatus, lac, cellID, ok := parseRegistration(resp, prefix) + regStatus, lac, cellID, ok := parseRegistration(resp, dialect.registrationPrefix) if !ok { return 0, "", "", "", nil } @@ -114,10 +117,11 @@ func (m *Manager) QueryServingCellLTE() (int, int, error) { } func (m *Manager) QueryServingCellLTEInfo() (ServingCellLTEInfo, error) { - if m.atProfile == ATProfileML307C { + cmd := m.atProfile.dialect().servingCell + if cmd == "" { return ServingCellLTEInfo{}, nil } - resp, err := m.ExecuteATSilent("AT+QENG=\"servingcell\"", 3*time.Second) + resp, err := m.ExecuteATSilent(cmd, 3*time.Second) if err != nil { return ServingCellLTEInfo{}, err } @@ -137,10 +141,11 @@ func (m *Manager) QueryAPN() (string, error) { } func (m *Manager) QueryIMSStatus() (int, error) { - if m.atProfile == ATProfileML307C { + cmd := m.atProfile.dialect().imsStatus + if cmd == "" { return 0, nil } - resp, err := m.ExecuteATSilent("AT+QIMS?", 2*time.Second) + resp, err := m.ExecuteATSilent(cmd, 2*time.Second) if err != nil { return 0, err } @@ -154,19 +159,12 @@ func (m *Manager) QueryNetworkModeAndDuplex() (string, string, error) { } func (m *Manager) QueryNetworkRadio() (string, string, string, uint32, error) { - if m.atProfile == ATProfileML307C { - resp, err := m.ExecuteATSilent("AT+COPS?", 2*time.Second) - if err != nil { - return "", "", "", 0, err - } - mode, _ := parseCOPSAct(resp) - return mode, "", "", 0, nil - } - resp, err := m.ExecuteATSilent("AT+QNWINFO", 2*time.Second) + query := m.atProfile.dialect().radio + resp, err := m.ExecuteATSilent(query.command, 2*time.Second) if err != nil { return "", "", "", 0, err } - mode, duplex, band, channel := parseQNWInfoRadio(resp) + mode, duplex, band, channel := query.parse(resp) return mode, duplex, band, channel, nil } @@ -177,18 +175,19 @@ func (m *Manager) QueryNetworkMode() (string, error) { func (m *Manager) QueryNetworkModeFallbackAndDuplex() (string, string, error) { networkMode, networkDuplex, err := m.QueryNetworkModeAndDuplex() - if m.atProfile == ATProfileML307C || (err == nil && networkMode != "") { + fallback := m.atProfile.dialect().radioFallback + if fallback.command == "" || (err == nil && networkMode != "") { return networkMode, networkDuplex, err } - resp, err2 := m.ExecuteATSilent("AT+COPS?", 2*time.Second) + resp, err2 := m.ExecuteATSilent(fallback.command, 2*time.Second) if err2 != nil { if err != nil { return "", "", err } return "", "", err2 } - mode, _ := parseCOPSAct(resp) - return mode, "", nil + mode, duplex, _, _ := fallback.parse(resp) + return mode, duplex, nil } func (m *Manager) QueryNetworkModeFallback() (string, error) { @@ -326,10 +325,11 @@ func (m *Manager) QueryMSISDN() (string, error) { // QueryUSBNetMode 查询 USBNET 模式 func (m *Manager) QueryUSBNetMode() (int, error) { - if m.atProfile == ATProfileML307C { + cmd := m.atProfile.dialect().usbnet + if cmd == "" { return -1, nil } - resp, err := m.ExecuteATSilent("AT+QCFG=\"usbnet\"?", 2*time.Second) + resp, err := m.ExecuteATSilent(cmd, 2*time.Second) if err != nil { return -1, err } @@ -393,7 +393,7 @@ func (m *Manager) openLogicalChannel(aid, leaseOwner, sessionOwner string, class if err != nil { return -1, fmt.Errorf("打开 logical channel 失败: %w", err) } - channel, ok := parseCCHO(resp, m.atProfile) + channel, ok := m.atProfile.dialect().parseCCHO(resp) if !ok { return -1, fmt.Errorf("解析 logical channel 响应失败: %s", resp) } diff --git a/internal/modem/imei_probe.go b/internal/modem/imei_probe.go index 6cdb1cbf..51c7f8ff 100644 --- a/internal/modem/imei_probe.go +++ b/internal/modem/imei_probe.go @@ -125,14 +125,7 @@ func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout t buf := make([]byte, 1024) var acc strings.Builder - readIMEI := func() string { - reply := acc.String() - if profile == ATProfileML307C { - // A serial read can end in the middle of an identifier. - reply = reply[:strings.LastIndexAny(reply, "\r\n")+1] - } - return profile.parseIMEI(reply) - } + dialect := profile.dialect() write := func(s string) { _, _ = p.Write([]byte(s)) @@ -141,14 +134,14 @@ func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout t // 写入 AT 测试命令与查询 IMEI 的 AT+CGSN 命令 write("AT\r\n") time.Sleep(40 * time.Millisecond) - write(profile.imeiCommand() + "\r\n") + write(dialect.imei.command + "\r\n") // 在指定的截止时间内轮询并解析串口输出内容 for probeCtx.Err() == nil { n, rerr := p.Read(buf) if n > 0 { acc.Write(buf[:n]) - if imei := readIMEI(); imei != "" { + if imei := dialect.parseProbeIMEI(acc.String()); imei != "" { return imei, nil } } @@ -163,7 +156,7 @@ func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout t } // 最终尝试解析一次累积的串口缓冲区 - if imei := readIMEI(); imei != "" { + if imei := dialect.parseProbeIMEI(acc.String()); imei != "" { return imei, nil } if err := probeCtx.Err(); err != nil && !errors.Is(err, context.DeadlineExceeded) { diff --git a/internal/modem/manager.go b/internal/modem/manager.go index a264e12b..571211bb 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -719,10 +719,13 @@ func (m *Manager) handleCommand(req commandRequest) { m.handleFileUpload(req) return } - if m.atProfile == ATProfileML307C && req.smsFinalTimeout > 0 { + dialect := m.atProfile.dialect() + if dialect.ownedSMSSubmit != nil && req.smsFinalTimeout > 0 { m.handleML307CSMS(req) return } + cpinPresence := dialect.cpinPresence + queryingPresence := cpinPresence != nil && req.cmd == cpinQuery startTime := time.Now() // 发送命令 @@ -784,7 +787,7 @@ RespLoop: "resp", logATResponse(req.cmd, strings.Join(fullResponse, " | ")), "cost", time.Since(startTime).Truncate(time.Millisecond).String()) } - if m.atProfile == ATProfileML307C && req.cmd == "AT+CPIN?" && isML307CNoSIMError(line) { + if queryingPresence && cpinPresence.isAbsentError(line) { req.errChan <- errSIMNotInserted } else if req.cmd == "AT+CLCC" { req.errChan <- &clccResponseError{response: strings.Join(fullResponse, "\n"), terminal: line} @@ -813,7 +816,7 @@ RespLoop: req.respChan <- "> " break RespLoop - } else if m.atProfile == ATProfileML307C && req.cmd == "AT+CPIN?" && strings.HasPrefix(line, "+CPIN:") { + } else if queryingPresence && strings.HasPrefix(line, cpinPrefix) { fullResponse = append(fullResponse, line) } else if m.isURC(line) { // 对于确认为 URC 的行,始终分发出去 @@ -1029,7 +1032,8 @@ func (m *Manager) collectDeviceInfo() { imsi = v } } - if simInserted || m.atProfile != ATProfileML307C { + tracksSIMByCPIN := m.atProfile.dialect().cpinPresence != nil + if simInserted || !tracksSIMByCPIN { if v, err := m.QueryICCID(); err == nil { iccid = v } @@ -1083,7 +1087,7 @@ func (m *Manager) collectDeviceInfo() { if operator != "" { m.operator = operator } - if m.atProfile != ATProfileML307C { + if !tracksSIMByCPIN { m.simInserted = simInserted } if signalDBM != -999 { @@ -1302,7 +1306,7 @@ func (m *Manager) RefreshStatus(onAlert func(msg string), onRecover func(msg str // 检查 SIM 卡是否存活 simInserted, simErr := m.QuerySIMInserted() - if m.atProfile == ATProfileML307C && simErr == nil { + if m.atProfile.dialect().cpinPresence != nil && simErr == nil { m.dispatchSIMStatusURC(&simInserted, "") } @@ -1452,8 +1456,8 @@ func (m *Manager) handleURC(line string) { break } } - if m.atProfile == ATProfileML307C && IsSIMPINRequiredState(state) { - m.cacheML307CSIMState(false, ErrSIMPINRequired) + if m.atProfile.dialect().cpinPresence != nil && IsSIMPINRequiredState(state) { + m.cacheCPINSIMState(false, ErrSIMPINRequired) } m.dispatchSIMStatusURC(nil, state) } @@ -2162,14 +2166,15 @@ func (m *Manager) SendSMS(phone, message string) error { // SendSMSWithOptions 使用 PDU 模式发送短信,并允许调用方指定文本编码策略。 func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.SubmitOptions) error { - if m.atProfile == ATProfileML307C { + ownedSubmit := m.atProfile.dialect().ownedSMSSubmit + if ownedSubmit != nil { m.smsStorageMu.Lock() defer m.smsStorageMu.Unlock() } m.SetBusy(true) defer m.SetBusy(false) - if m.atProfile != ATProfileML307C { + if ownedSubmit == nil { logger.Info(fmt.Sprintf("[%s] 准备发送短信 (PDU)", m.cfg.ID), "to", phone) } @@ -2197,9 +2202,9 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit followUp: pduHex + "\x1A", // PDU + Ctrl+Z } - if m.atProfile == ATProfileML307C { - req.timeout = ml307cSMSPromptTimeout - req.smsFinalTimeout = ml307cSMSResultTimeout + if ownedSubmit != nil { + req.timeout = ownedSubmit.promptTimeout + req.smsFinalTimeout = ownedSubmit.finalTimeout if err := m.sendML307CSMSPart(req); err != nil { partErr := fmt.Errorf("发送分片 %d: %w", i+1, err) if i > 0 || errors.Is(err, ErrSMSSubmitUnknown) { diff --git a/internal/modem/runtime_role.go b/internal/modem/runtime_role.go index 62d33826..972ea518 100644 --- a/internal/modem/runtime_role.go +++ b/internal/modem/runtime_role.go @@ -25,11 +25,8 @@ func (m *Manager) initializationCommands() []string { "AT+CMGF=0", "AT+CNMI=2,1,0,0,0", } - if m.role == runtimeRoleSMSAuxiliary || m.atProfile == ATProfileML307C { + if m.role == runtimeRoleSMSAuxiliary { return commands } - return append(commands, - "AT+CLIP=1", - "AT+QPCMV=1,2", - ) + return append(commands, m.atProfile.dialect().voiceInit...) } From 8ec95cb0b2943f1bdbfde62b0aeab2de47218e16 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:43:24 +0800 Subject: [PATCH 11/39] fix(sms): retain uncertain results in command and balance flows --- internal/balance/service.go | 20 ++++++++++------ internal/balance/service_test.go | 35 ++++++++++++++++++++++++++++ internal/notify/commands.go | 17 +++++++++++--- internal/notify/commands_sms_test.go | 28 ++++++++++++++++++++++ 4 files changed, 90 insertions(+), 10 deletions(-) diff --git a/internal/balance/service.go b/internal/balance/service.go index 1b67426a..d1459f8d 100644 --- a/internal/balance/service.go +++ b/internal/balance/service.go @@ -10,6 +10,7 @@ import ( "github.com/google/uuid" "github.com/yibaiba/hideck/internal/carrierquery" + "github.com/yibaiba/hideck/internal/modem" ) type Service struct { @@ -40,19 +41,24 @@ func (s *Service) StartQuery(ctx context.Context, deviceID string) (Query, error if err := s.repo.CreatePending(ctx, query); err != nil { return Query{}, err } - if err := s.send(ctx, snapshot, rule, query.ID); err != nil { - _ = s.repo.MarkFailed(context.Background(), query.ID, err, s.now()) - failed, _, _ := s.repo.Get(context.Background(), query.ID) - return failed, err + sendErr := s.send(ctx, snapshot, rule, query.ID) + // Submission may finish after the caller's deadline. Read the persisted + // result without losing a late acknowledgement or an early reply. + readbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + stored, _, err := s.repo.Get(readbackCtx, query.ID) + if sendErr == nil || (err == nil && stored.State == StateCompleted) { + return stored, err } - stored, _, err := s.repo.Get(ctx, query.ID) - return stored, err + _ = s.repo.MarkFailed(readbackCtx, query.ID, sendErr, s.now()) + failed, _, _ := s.repo.Get(readbackCtx, query.ID) + return failed, sendErr } func (s *Service) send(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule, queryID string) error { switch rule.Transport { case carrierquery.TransportSMS: - if err := s.sendSMS(ctx, snapshot, rule); err != nil { + if err := s.sendSMS(ctx, snapshot, rule); err != nil && !errors.Is(err, modem.ErrSMSSubmitUnknown) { return err } return s.repo.MarkAwaitingReply(context.Background(), queryID, s.now()) diff --git a/internal/balance/service_test.go b/internal/balance/service_test.go index 8d87af32..ad614151 100644 --- a/internal/balance/service_test.go +++ b/internal/balance/service_test.go @@ -10,11 +10,13 @@ import ( "github.com/yibaiba/hideck/internal/carrierquery" appdb "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" ) type fakeGateway struct { snapshot DeviceSnapshot sendErr error + onBackendSMS func() wifiSMS, backendSMS int wifiUSSD, backendUSSD int ussdResponse USSDResponse @@ -27,6 +29,9 @@ func (g *fakeGateway) SendVoWiFiSMS(context.Context, string, string, string) err } func (g *fakeGateway) SendBackendSMS(context.Context, string, string, string) error { g.backendSMS++ + if g.onBackendSMS != nil { + g.onBackendSMS() + } return g.sendErr } func (g *fakeGateway) SendVoWiFiUSSD(context.Context, string, string) (USSDResponse, error) { @@ -117,6 +122,36 @@ func TestStartQueryFailureIsPersistedWithoutRetry(t *testing.T) { } } +func TestSMSQueryWithUnknownSubmissionCanReceiveReply(t *testing.T) { + now := time.Date(2026, 8, 11, 10, 0, 0, 0, time.UTC) + gateway := &fakeGateway{ + snapshot: DeviceSnapshot{DeviceID: "wwan0", ICCID: "iccid-1", MCC: "234", MNC: "10"}, + sendErr: modem.ErrSMSSubmitUnknown, + } + service, store := newTestService(t, gateway, smsTestRule(), now) + request, cancel := context.WithCancel(context.Background()) + defer cancel() + gateway.onBackendSMS = cancel + query, err := service.StartQuery(request, "wwan0") + if err != nil || query.State != StateAwaitingReply { + t.Fatalf("StartQuery() = %+v, %v", query, err) + } + ctx := context.Background() + if _, err := service.StartQuery(ctx, "wwan0"); !errors.Is(err, ErrPendingQuery) || gateway.backendSMS != 1 { + t.Fatalf("pending query retried SMS: calls=%d err=%v", gateway.backendSMS, err) + } + matched, err := service.HandleInboundSMS(ctx, InboundSMS{ + ICCID: "iccid-1", Sender: "giffgaff", Content: "credit 5.00", Time: now.Add(time.Second), + }) + if err != nil || !matched { + t.Fatalf("HandleInboundSMS() = %t, %v", matched, err) + } + stored, _, err := store.Get(ctx, query.ID) + if err != nil || stored.State != StateCompleted || stored.Amount != "5.00" { + t.Fatalf("stored query = %+v, %v", stored, err) + } +} + func TestUSSDQueryUsesSelectedRouteAndPersistsRawResponse(t *testing.T) { for _, test := range []struct { name string diff --git a/internal/notify/commands.go b/internal/notify/commands.go index 2a9e9a23..ee8835d2 100644 --- a/internal/notify/commands.go +++ b/internal/notify/commands.go @@ -80,20 +80,31 @@ func (m *Manager) handleCmdSendSMS(cmdCtx CommandContext, args []string) string ctx = messaging.WithSuppressSendTGSuccess(ctx) routed, sendErr := m.pool.SendRoutedSMS(ctx, worker, phone, message, smscodec.SubmitOptions{}) channel := smsRouteChannelLabel(routed.Via) - if sendErr != nil { + state := routed.Outcome.DeliveryState + unconfirmed := routed.Via == device.RoutedSMSViaCS && + (state == db.SMSDeliveryStateUnknown || state == db.SMSDeliveryStatePartialAck) + if sendErr != nil && !unconfirmed { cmdCtx.Reply(fmt.Sprintf("发送短信 / 失败\n设备 %s\n号码 %s\n通道 %s\n原因 %v", displayName, phone, channel, sendErr)) return } if routed.Via == device.RoutedSMSViaCS { + status := 2 + if unconfirmed { + status = db.SMSStatusSubmitUnconfirmed + } err := db.SaveSMSForIdentity(db.SMSRecord{ Identity: db.SMSIdentity{ICCID: routed.Identity.ICCID, IMSI: routed.Identity.IMSI}, Sender: worker.ID, Recipient: phone, Content: message, - Type: 2, Status: 2, Timestamp: time.Now(), + Type: 2, Status: status, Timestamp: time.Now(), }) if err != nil { - logger.Warn("短信发送成功但入库失败", "device", deviceID, "err", err) + logger.Warn("短信发送记录入库失败", "device", deviceID, "err", err) } } + if unconfirmed { + cmdCtx.Reply(fmt.Sprintf("发送短信 / 提交未完全确认\n设备 %s\n号码 %s\n通道 %s\n结果 %v\n请勿重发整条", displayName, phone, channel, sendErr)) + return + } cmdCtx.Reply(fmt.Sprintf("发送短信 / 完成\n设备 %s\n号码 %s\n通道 %s\n内容 %s", displayName, phone, channel, message)) }() diff --git a/internal/notify/commands_sms_test.go b/internal/notify/commands_sms_test.go index 9e1b0e5f..03994881 100644 --- a/internal/notify/commands_sms_test.go +++ b/internal/notify/commands_sms_test.go @@ -12,6 +12,7 @@ import ( "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/db" "github.com/yibaiba/hideck/internal/device" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/smscodec" ) @@ -72,6 +73,33 @@ func TestHandleCmdSendSMSFallsBackToCSWithoutDoubleSend(t *testing.T) { } } +func TestHandleCmdSendSMSReportsUnknownSubmission(t *testing.T) { + pool, _ := newRoutedSMSTestPool(t) + csCalls := 0 + pool.SetRoutedSMSTestSenders( + func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) { + return messaging.SendOutcome{}, messaging.ErrSMSNotReady + }, + func(string, string, string) error { csCalls++; return modem.ErrSMSSubmitUnknown }, + ) + replies := make(chan string, 1) + manager := &Manager{pool: pool} + _ = manager.handleCmdSendSMS(testCommandContext{replies: replies}, []string{"wwan0", "888", "BAL"}) + select { + case got := <-replies: + if !strings.Contains(got, "提交未完全确认") || !strings.Contains(got, "请勿重发整条") { + t.Fatalf("reply=%q", got) + } + case <-time.After(time.Second): + t.Fatal("command SMS reply was not delivered") + } + var count int64 + err := db.DB.Model(&db.SMS{}).Where("type = ? AND status = ?", 2, db.SMSStatusSubmitUnconfirmed).Count(&count).Error + if csCalls != 1 || err != nil || count != 1 { + t.Fatalf("calls=%d unconfirmed history=%d err=%v", csCalls, count, err) + } +} + func TestHandleCmdSendSMSDoesNotFallbackAfterIMSAccept(t *testing.T) { pool, _ := newRoutedSMSTestPool(t) csCalls := 0 From acc9a2dcd53d3d7f3f37542751b638066bf54a2b Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:44:14 +0800 Subject: [PATCH 12/39] fix(device): keep ML307C rediscovery bound to live identity --- internal/device/discovery_enrichment.go | 13 +- internal/device/ml307c_discovery_test.go | 151 ++++++++++++++++++- internal/device/pool.go | 33 +++- internal/device/pool_bootstrap.go | 62 ++++++-- internal/device/pool_qmi_mode_test.go | 8 +- internal/device/pool_rescan_collect_test.go | 4 +- internal/device/pool_rescan_guard.go | 20 ++- internal/device/pool_rescan_identity_test.go | 2 +- internal/device/pool_rescan_nonqmi_test.go | 2 +- 9 files changed, 258 insertions(+), 37 deletions(-) diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index 3cc98a4e..68b3663e 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -186,11 +186,16 @@ type WorkerDiscoveryInfo struct { USBNetMode *int } +type workerATIdentityReader struct { + worker *Worker + query func() (string, error) +} + type WorkerDiscoveryIndex struct { byControl map[string]WorkerDiscoveryInfo byUSB map[string]WorkerDiscoveryInfo byIface map[string]WorkerDiscoveryInfo - atIdentityByPort map[string]func() (string, error) + atIdentityByPort map[string]workerATIdentityReader } func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) WorkerDiscoveryIndex { @@ -198,7 +203,7 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor byControl: map[string]WorkerDiscoveryInfo{}, byUSB: map[string]WorkerDiscoveryInfo{}, byIface: map[string]WorkerDiscoveryInfo{}, - atIdentityByPort: map[string]func() (string, error){}, + atIdentityByPort: map[string]workerATIdentityReader{}, } for _, worker := range workers { @@ -215,7 +220,7 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor IMEI: strings.TrimSpace(cfg.ModemIMEI), } if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" { - idx.atIdentityByPort[worker.ResolvedATPort()] = worker.Modem.QueryIMEI + idx.atIdentityByPort[worker.ResolvedATPort()] = workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI} } if includeRuntimeStatus && (worker.Modem == nil || worker.Modem.ATProfile() != modem.ATProfileML307C) { status := worker.GetDeviceStatus() @@ -274,7 +279,7 @@ func (idx WorkerDiscoveryIndex) ReadOwnedATIdentity(dev CompatibleModem) (Compat return dev, false } for _, port := range dev.ATPorts { - query := idx.atIdentityByPort[port] + query := idx.atIdentityByPort[port].query if query == nil { continue } diff --git a/internal/device/ml307c_discovery_test.go b/internal/device/ml307c_discovery_test.go index 1fec16e5..82b90ba5 100644 --- a/internal/device/ml307c_discovery_test.go +++ b/internal/device/ml307c_discovery_test.go @@ -6,9 +6,11 @@ import ( "os" "path/filepath" "slices" + "strings" "testing" "time" + "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/modem" ) @@ -35,14 +37,16 @@ func TestML307CDiscoveryAndRebind(t *testing.T) { } const imei = "490154203237518" - owned := WorkerDiscoveryIndex{atIdentityByPort: map[string]func() (string, error){ - "/dev/ttyUSB8": func() (string, error) { return imei, nil }, + owned := WorkerDiscoveryIndex{atIdentityByPort: map[string]workerATIdentityReader{ + "/dev/ttyUSB8": {query: func() (string, error) { return imei, nil }}, }} active, ok := owned.ReadOwnedATIdentity(dev) if !ok || active.IMEI != imei { t.Fatalf("owned IMEI = %q, %v", active.IMEI, ok) } - owned.atIdentityByPort["/dev/ttyUSB8"] = func() (string, error) { return "", errors.New("old tty closed") } + owned.atIdentityByPort["/dev/ttyUSB8"] = workerATIdentityReader{ + query: func() (string, error) { return "", errors.New("old tty closed") }, + } dev.IMEI = imei active, ok = owned.ReadOwnedATIdentity(dev) if !ok || active.IMEI != "" { @@ -82,3 +86,144 @@ func TestML307CDiscoveryAndRebind(t *testing.T) { t.Fatal("Diag alone must not be discovered as an ML307C AT port") } } + +func TestML307CRescanPreservesAndRebindsDiscoveredDevice(t *testing.T) { + const imei = "490154203237518" + const oldPort = "/dev/ttyUSB8" + cfg := config.DeviceConfig{ + ID: "ml307c", DeviceBackend: backend.BackendAT, ESIMTransport: config.ESIMTransportAT, + ModemIMEI: imei, USBPath: "/sys/bus/usb/devices/1-1", ATPort: oldPort, ManagePort: oldPort, + } + original := CompatibleModem{ + USBPath: cfg.USBPath, VendorID: 0x2ecc, ProductID: 0x3012, + ATPort: oldPort, ATPorts: []string{oldPort}, IMEI: imei, Mode: "at", TransportType: backend.BackendAT, + } + other := CompatibleModem{USBPath: "/sys/bus/usb/devices/1-2", ATPort: "/dev/ttyUSB4", Mode: "at"} + candidates := []CompatibleModem{original, other} + prevQMI, prevFallback, prevEnrich := discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn + t.Cleanup(func() { + discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevQMI, prevFallback, prevEnrich + }) + discoverQMIDevicesFn = func() ([]QMIDevice, error) { return nil, nil } + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { return candidates, nil } + resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) { + if dev.ATProfile() != modem.ATProfileML307C { + t.Fatalf("explicit port configuration triggered an unrelated AT probe: %+v", dev) + } + return dev, dev.IMEI + } + + p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}}) + t.Cleanup(p.cancel) + // Use the existing fake health backend so the rescan needs no real AT owner. + worker := &Worker{ID: cfg.ID, Config: cfg, Backend: &workerStatusBackendStub{mode: backend.BackendQMI}} + p.workers[cfg.ID] = worker + if err := p.RescanAndReconnect(); err != nil || p.GetWorker(cfg.ID) != worker { + t.Fatalf("rescan retired an unchanged, healthy ML307C: %v", err) + } + + // The offline-worker recovery must select by IMEI even when another + // ML307C gets the previous USB location and tty number. + delete(p.workers, cfg.ID) + reused := original + reused.IMEI = "490154203237526" + moved := original + moved.USBPath = "/sys/bus/usb/devices/2-1" + moved.ATPort = "/dev/ttyUSB13" + moved.ATPorts = []string{moved.ATPort} + candidates = []CompatibleModem{reused, moved, other} + managed := p.managedDevices() + hardware, _ := p.collectRescanHardware(nil, BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false), configuredDevicesATDiscovery(managed)) + resolved := ResolveDeviceIdentities(hardware, managed) + if len(resolved.Matched) != 1 || len(resolved.Offline) != 0 { + t.Fatalf("rescan did not rediscover an offline ML307C: %+v", resolved) + } + pair := resolved.Matched[0] + rebound := rescanWorkerConfig(pair.Config, pair.Hardware) + if rebound.ModemIMEI != imei || rebound.USBPath != moved.USBPath || rebound.ATPort != moved.ATPort || rebound.ManagePort != moved.ATPort { + t.Fatalf("rescan selected the wrong attachment: %+v", rebound) + } +} + +func TestML307CBootstrapRejectsUnreadableIdentityOnConfiguredPort(t *testing.T) { + dir, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + port := filepath.Join(dir, "ttyUSB8") + if err := os.WriteFile(port, nil, 0o600); err != nil { + t.Fatal(err) + } + alias := filepath.Join(dir, "by-id") + if err := os.Symlink(port, alias); err != nil { + t.Fatal(err) + } + cfg := config.DeviceConfig{ + ID: "ml307c", DeviceBackend: backend.BackendAT, ESIMTransport: config.ESIMTransportAT, + ModemIMEI: "490154203237518", ATPort: alias, ManagePort: alias, + } + + prevFallback, prevEnrich := discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn + t.Cleanup(func() { discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevFallback, prevEnrich }) + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + return []CompatibleModem{ + {USBPath: "/sys/bus/usb/devices/1-1", VendorID: 0x2ecc, ProductID: 0x3012, ATPort: port, ATPorts: []string{port}, Mode: "at"}, + {USBPath: "/sys/bus/usb/devices/1-2", ATPort: "/dev/ttyUSB4", Mode: "at"}, + }, nil + } + probes := 0 + resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) { + if dev.ATProfile() != modem.ATProfileML307C { + t.Fatalf("bootstrap probed an unrelated AT device: %+v", dev) + } + probes++ + return dev, "" + } + + p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}}) + t.Cleanup(p.cancel) + worker, err := p.AddWorkerFromConfig(cfg) + if worker != nil || err == nil || !strings.Contains(err.Error(), "未找到匹配的非 QMI 硬件") || probes != 1 { + t.Fatalf("unverified ML307C port did not block startup: worker=%v err=%v probes=%d", worker, err, probes) + } +} + +func TestML307CRescanKeepsHealthyOwnerWhenIMEIUnavailable(t *testing.T) { + const port = "/dev/ttyUSB8" + const usbPath = "/sys/bus/usb/devices/1-1" + cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: backend.BackendAT, ModemIMEI: "490154203237518"} + p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}}) + t.Cleanup(p.cancel) + workerCfg := cfg + workerCfg.USBPath = usbPath + workerCfg.ATPort = port + m, err := modem.NewWithATProfile(workerCfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + // The unopened manager rejects the identity query; the health stub keeps + // the failure isolated to this single command for the test. + worker := &Worker{ID: cfg.ID, Config: workerCfg, Modem: m, + Backend: &workerStatusBackendStub{mode: backend.BackendQMI}, stop: make(chan struct{})} + p.workers[cfg.ID] = worker + + prevQMI, prevFallback, prevEnrich := discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn + t.Cleanup(func() { + discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevQMI, prevFallback, prevEnrich + }) + discoverQMIDevicesFn = func() ([]QMIDevice, error) { return nil, nil } + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + return []CompatibleModem{{ + USBPath: usbPath, VendorID: 0x2ecc, ProductID: 0x3012, + ATPort: port, ATPorts: []string{port}, Mode: "at", + }}, nil + } + resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) { + t.Fatalf("rescan attempted an independent identity probe on the owned AT port: %+v", dev) + return dev, "" + } + + if err := p.RescanAndReconnect(); err != nil || p.GetWorker(cfg.ID) != worker { + t.Fatalf("rescan retired the healthy owner after its identity query failed: %v", err) + } +} diff --git a/internal/device/pool.go b/internal/device/pool.go index cbc1529e..b6336e4b 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -1950,8 +1950,12 @@ func (p *Pool) RescanAndReconnect() error { return p.rescanAndReconnect(rescanReconnectOptions{}) } -func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scanCompatibleAT bool) []CompatibleModem { - var hardware []CompatibleModem +type ml307cScanCandidate struct { + CompatibleModem + unreadableOwner *Worker +} + +func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scan compatibleATDiscoveryScope) (hardware []CompatibleModem, ml307cCandidates []ml307cScanCandidate) { for i := range discovered { raw := discovered[i] // Paths are attachment hints, never proof that the old worker still @@ -1977,7 +1981,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor }) } - if scanCompatibleAT { + if scan != compatibleATDiscoveryNone { if compatList, err := DiscoverCompatibleModemsFromQMI(discovered); err == nil { seen := map[string]bool{} for _, hw := range hardware { @@ -1986,15 +1990,28 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor } } for _, raw := range compatList { + isML307C := raw.ATProfile() == modem.ATProfileML307C + if scan == compatibleATDiscoveryML307C && !isML307C { + continue + } m, owned := liveWorkerIndex.ReadOwnedATIdentity(raw) imei := m.IMEI if !owned { m, imei = resolveDiscoveredCompatibleModemFn(raw, 1200*time.Millisecond) } - if config.NormalizeIMEI(imei) == "" { + key := config.NormalizeIMEI(imei) + if isML307C { + // Bootstrap must recognize C ports even when IMEI is unreadable. + candidate := ml307cScanCandidate{CompatibleModem: raw} + if owned && key == "" { + candidate.unreadableOwner = liveWorkerIndex.atIdentityByPort[m.ATPort].worker + } + ml307cCandidates = append(ml307cCandidates, candidate) + } + if key == "" { continue } - if seen[config.NormalizeIMEI(imei)] { + if seen[key] { continue } m.IMEI = imei @@ -2002,7 +2019,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor } } } - return hardware + return hardware, ml307cCandidates } func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { @@ -2016,9 +2033,9 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { } liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) managed := p.managedDevices() modemDevices, pcscDevices := partitionManagedDevices(managed) + hardware, ml307cCandidates := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(modemDevices)) resolved := ResolveDeviceIdentities(hardware, modemDevices) if len(resolved.Degraded) > 0 || len(resolved.Unmatched) > 0 { @@ -2029,7 +2046,7 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { } for _, snapshot := range resolved.Offline { - p.reconcileOfflineRescanDevice(opts, snapshot, hardware, managed) + p.reconcileOfflineRescanDevice(opts, snapshot, hardware, ml307cCandidates, managed) } return p.reconcilePCSCReaders(opts, managed, pcscDevices) diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index baf45d7d..2c56c0e5 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "path/filepath" "strings" "sync/atomic" "time" @@ -127,19 +128,50 @@ func resolveDiscoveredCompatibleModem(dev CompatibleModem, timeout time.Duration }) } -func configuredDevicesNeedCompatibleATDiscovery(devices []config.DeviceConfig) bool { +type compatibleATDiscoveryScope uint8 + +const ( + compatibleATDiscoveryNone compatibleATDiscoveryScope = iota + compatibleATDiscoveryML307C + compatibleATDiscoveryAll +) + +func configuredDevicesATDiscovery(devices []config.DeviceConfig) compatibleATDiscoveryScope { + scope := compatibleATDiscoveryNone for _, dev := range devices { - if requiresQMICore(dev) { + if requiresQMICore(dev) || resolvedBackendMode(dev) == backend.BackendPCSC || strings.TrimSpace(dev.ModemIMEI) == "" { continue } - if strings.TrimSpace(dev.ModemIMEI) == "" { - continue + if strings.TrimSpace(dev.ATPort) == "" && strings.TrimSpace(dev.ManagePort) == "" { + return compatibleATDiscoveryAll } - if strings.TrimSpace(dev.ATPort) != "" || strings.TrimSpace(dev.ManagePort) != "" { - continue + if resolvedBackendMode(dev) == backend.BackendAT { + // An enumerated tty is only an attachment hint for an ML307C. + // Other modems with explicit ports keep their existing probe behavior. + scope = compatibleATDiscoveryML307C } + } + return scope +} + +func configuredPortPointsToML307C(cfg config.DeviceConfig, candidates []ml307cScanCandidate) bool { + if usb := strings.TrimSpace(cfg.USBPath); usb != "" && readUSBDeviceIdentity(resolveUSBPathForScan(usb)).isML307C() { return true } + for _, port := range []string{cfg.ATPort, cfg.ManagePort} { + port = strings.TrimSpace(port) + if port == "" { + continue + } + if target, err := filepath.EvalSymlinks(port); err == nil { + port = target + } + for _, hw := range candidates { + if containsPort(hw.ATPorts, port) { + return true + } + } + } return false } @@ -276,9 +308,12 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) configuredIndex := BuildConfiguredDeviceIndex(config.ListDevices()) if !needsQMICore { - scanAT := configuredDevicesNeedCompatibleATDiscovery(config.ListDevices()) || - (resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "") - hardware := p.collectRescanHardware(nil, liveWorkerIndex, scanAT) + scan := configuredDevicesATDiscovery([]config.DeviceConfig{devCfg}) + if scan == compatibleATDiscoveryNone && configuredDevicesATDiscovery(config.ListDevices()) == compatibleATDiscoveryAll { + scan = compatibleATDiscoveryAll + } + atIMEIConfigured := resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "" + hardware, ml307cCandidates := p.collectRescanHardware(nil, liveWorkerIndex, scan) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { @@ -308,8 +343,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI) } } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || - (resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "" && - strings.TrimSpace(devCfg.USBPath) != "" && readUSBDeviceIdentity(resolveUSBPathForScan(devCfg.USBPath)).isML307C()) { + (atIMEIConfigured && configuredPortPointsToML307C(devCfg, ml307cCandidates)) { return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") } } else if hasManagedQMINetwork(devCfg) { @@ -326,7 +360,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) if qmiErr != nil { logger.Debug("QMI 静态路径启动前发现失败", "device", devCfg.ID, "err", qmiErr) } else { - hardware := p.collectRescanHardware(qmiList, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) + scan := compatibleATDiscoveryNone + if configuredDevicesATDiscovery(config.ListDevices()) == compatibleATDiscoveryAll { + scan = compatibleATDiscoveryAll + } + hardware, _ := p.collectRescanHardware(qmiList, liveWorkerIndex, scan) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware diff --git a/internal/device/pool_qmi_mode_test.go b/internal/device/pool_qmi_mode_test.go index 36e20817..6b2095f1 100644 --- a/internal/device/pool_qmi_mode_test.go +++ b/internal/device/pool_qmi_mode_test.go @@ -330,8 +330,8 @@ func TestConfiguredDevicesNeedCompatibleATDiscoverySkipsPureQMI(t *testing.T) { }, } - if configuredDevicesNeedCompatibleATDiscovery(devices) { - t.Fatal("configuredDevicesNeedCompatibleATDiscovery() = true for pure QMI config, want false") + if scope := configuredDevicesATDiscovery(devices); scope != compatibleATDiscoveryNone { + t.Fatalf("configuredDevicesATDiscovery() = %v for pure QMI config, want none", scope) } } @@ -344,8 +344,8 @@ func TestConfiguredDevicesNeedCompatibleATDiscoveryForATMissingPort(t *testing.T }, } - if !configuredDevicesNeedCompatibleATDiscovery(devices) { - t.Fatal("configuredDevicesNeedCompatibleATDiscovery() = false for AT config missing port, want true") + if scope := configuredDevicesATDiscovery(devices); scope != compatibleATDiscoveryAll { + t.Fatalf("configuredDevicesATDiscovery() = %v for AT config missing port, want all", scope) } } diff --git a/internal/device/pool_rescan_collect_test.go b/internal/device/pool_rescan_collect_test.go index 860ed033..31ef2ea6 100644 --- a/internal/device/pool_rescan_collect_test.go +++ b/internal/device/pool_rescan_collect_test.go @@ -31,7 +31,7 @@ func TestCollectRescanHardwarePopulatesIMEIAndPaths(t *testing.T) { discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) + hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices())) if len(hardware) != 1 { t.Fatalf("expected 1 hardware, got %d", len(hardware)) @@ -101,7 +101,7 @@ func TestCollectRescanHardwarePopulatesNonQMIIMEIAndPaths(t *testing.T) { discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) + hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices())) if len(hardware) != 1 { t.Fatalf("expected 1 hardware, got %d", len(hardware)) diff --git a/internal/device/pool_rescan_guard.go b/internal/device/pool_rescan_guard.go index 52ad0fa9..b1533a24 100644 --- a/internal/device/pool_rescan_guard.go +++ b/internal/device/pool_rescan_guard.go @@ -6,6 +6,7 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -87,7 +88,9 @@ func (p *Pool) reconcileHealthyRescanWorker( }) return } - if hw.ATPort == "" || hw.ATPort == worker.Config.ATPort || !opts.allowWorkerMutation(pair.Config.ID) { + usbChanged := hw.ATProfile() == modem.ATProfileML307C && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath + portChanged := hw.ATPort != "" && hw.ATPort != worker.Config.ATPort + if (!usbChanged && !portChanged) || !opts.allowWorkerMutation(pair.Config.ID) { return } logger.Info("检测到设备端口变化,重建 Worker", @@ -209,6 +212,7 @@ func (p *Pool) reconcileOfflineRescanDevice( opts rescanReconnectOptions, snapshot config.DeviceConfig, hardware []CompatibleModem, + ml307cCandidates []ml307cScanCandidate, fallback []config.DeviceConfig, ) { releaseMutation := p.AcquireManagedDeviceMutation(snapshot.ID) @@ -226,9 +230,21 @@ func (p *Pool) reconcileOfflineRescanDevice( if worker == nil { return } + healthy := worker.IsDeviceHealthy() + if healthy && worker.isML307C() && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) { + usb := strings.TrimSpace(worker.Config.USBPath) + port := worker.ResolvedATPort() + for _, candidate := range ml307cCandidates { + if candidate.unreadableOwner == worker && usb != "" && candidate.USBPath == usb && + containsPort(candidate.ATPorts, port) { + // Keep the existing owner until the next scan can verify its IMEI. + return + } + } + } logger.Info("检测到设备离线,清理 Worker 以便后续重建", "device", current.ID, "imei", current.ModemIMEI, - "was_healthy", worker.IsDeviceHealthy()) + "was_healthy", healthy) p.teardownVoWiFiForReconnect(current.ID) if p.lifecycle != nil { p.lifecycle.BeginRecovery(current.ID, LifecyclePhaseUSBWait, "rescan_device_missing", qmiLifecycleRecoveryTTL) diff --git a/internal/device/pool_rescan_identity_test.go b/internal/device/pool_rescan_identity_test.go index 306bdc8c..979e3f9c 100644 --- a/internal/device/pool_rescan_identity_test.go +++ b/internal/device/pool_rescan_identity_test.go @@ -22,7 +22,7 @@ func TestRescanReusedPathsDoNotInheritOldWorkerIMEI(t *testing.T) { {ControlPath: "/dev/cdc-wdm0", USBPath: "/sys/usb/1-1", NetInterface: "wwan0"}, {ControlPath: "/dev/cdc-wdm1", USBPath: "/sys/usb/1-2", NetInterface: "wwan1"}, } - hardware := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false), false) + hardware, _ := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false), compatibleATDiscoveryNone) if len(hardware) != 2 || hardware[0].IMEI != "222222222222222" || hardware[1].IMEI != "111111111111111" { t.Fatalf("identities = %+v", hardware) } diff --git a/internal/device/pool_rescan_nonqmi_test.go b/internal/device/pool_rescan_nonqmi_test.go index 81b99c58..cc9a3fa3 100644 --- a/internal/device/pool_rescan_nonqmi_test.go +++ b/internal/device/pool_rescan_nonqmi_test.go @@ -75,7 +75,7 @@ func TestRescanReconnectsNonQMIDeviceByIMEI(t *testing.T) { // 验证 resolver 把它放进 Matched 而非 Offline discovered, _ := discoverQMIDevicesFn() liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) - hardware := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesNeedCompatibleATDiscovery(config.ListDevices())) + hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices())) managed := config.ListDevices() resolved := ResolveDeviceIdentities(hardware, managed) From 54ab14f5f36cfa4bbe688d2ad38c6e61fdf23e74 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:49:08 +0800 Subject: [PATCH 13/39] fix(sms): recover stored messages and reassemble settled fragments --- internal/device/pool.go | 3 +- internal/device/sms_ml307c.go | 410 +++++++++++++++++++++++++---- internal/device/sms_ml307c_test.go | 180 +++++++++++-- pkg/smscodec/pdu.go | 38 ++- 4 files changed, 558 insertions(+), 73 deletions(-) diff --git a/internal/device/pool.go b/internal/device/pool.go index b6336e4b..ded97662 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -156,7 +156,8 @@ type Worker struct { operatorScanCancel context.CancelFunc operatorScanActive bool - reassembler *smscodec.Reassembler + reassembler *smscodec.Reassembler + ml307cSMSNotices ml307cSMSNotices // 短信工作模式:AT / QMI / VoWiFi(三模完全隔离)。MBIM 网络使用 AT 短信模式。 smsMode smsMode diff --git a/internal/device/sms_ml307c.go b/internal/device/sms_ml307c.go index 72fa730d..08f14073 100644 --- a/internal/device/sms_ml307c.go +++ b/internal/device/sms_ml307c.go @@ -9,6 +9,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" "github.com/yibaiba/hideck/internal/db" @@ -79,9 +80,88 @@ func (owner ml307cSMSOwner) verifyLive() error { return owner.check() } +// A CMTI only proves provenance within the current worker and SIM generation. +type ml307cSMSSlot struct { + store string + index int +} + +type ml307cSMSNotice struct { + owner ml307cSMSOwner + slot ml307cSMSSlot + observedAt time.Time + pdu string // Set under the notice lock after the first successful read. +} + +type ml307cSMSNotices struct { + mu sync.Mutex + slots map[ml307cSMSSlot]*ml307cSMSNotice +} + +func (notices *ml307cSMSNotices) add(notice *ml307cSMSNotice) { + notices.mu.Lock() + defer notices.mu.Unlock() + if notices.slots == nil { + notices.slots = make(map[ml307cSMSSlot]*ml307cSMSNotice) + } + notices.slots[notice.slot] = notice +} + +func (notices *ml307cSMSNotices) snapshot(owner ml307cSMSOwner, store string) map[int]*ml307cSMSNotice { + notices.mu.Lock() + defer notices.mu.Unlock() + var pending map[int]*ml307cSMSNotice + for slot, notice := range notices.slots { + if notice.owner != owner { + if notice.owner.workerLifecycleOwner == owner.workerLifecycleOwner && notice.owner.simGeneration < owner.simGeneration { + delete(notices.slots, slot) + } + } else if slot.store == store { + if pending == nil { + pending = make(map[int]*ml307cSMSNotice) + } + pending[slot.index] = notice + } + } + return pending +} + +func (notices *ml307cSMSNotices) current(notice *ml307cSMSNotice) bool { + notices.mu.Lock() + defer notices.mu.Unlock() + return notices.slots[notice.slot] == notice +} + +func (notices *ml307cSMSNotices) bind(notice *ml307cSMSNotice, pdu string) bool { + notices.mu.Lock() + defer notices.mu.Unlock() + if notice == nil || notices.slots[notice.slot] != notice { + return false + } + if notice.pdu != "" && !strings.EqualFold(notice.pdu, pdu) { + // A previously read slot has been replaced. Only its new CMTI can + // establish provenance for the replacement. + delete(notices.slots, notice.slot) + return false + } + notice.pdu = pdu + return true +} + +func (notices *ml307cSMSNotices) forget(notice *ml307cSMSNotice) { + if notice == nil { + return + } + notices.mu.Lock() + defer notices.mu.Unlock() + if notices.slots[notice.slot] == notice { + delete(notices.slots, notice.slot) + } +} + func (w *Worker) handleML307CStoredSMS(storage, index string) { slot, err := strconv.Atoi(index) - if err != nil || slot < 0 || (storage != "ME" && storage != "SM") { + if err != nil || slot < 0 || slot > 65535 || (storage != "ME" && storage != "SM") { return } // Capture before queuing the work. A delayed URC must keep its original @@ -90,7 +170,11 @@ func (w *Worker) handleML307CStoredSMS(storage, index string) { if err != nil { return } - go w.runML307CSMS(owner, storage, slot) + notice := &ml307cSMSNotice{ + owner: owner, slot: ml307cSMSSlot{store: storage, index: slot}, observedAt: time.Now(), + } + w.ml307cSMSNotices.add(notice) + go w.runML307CSMS(owner, notice) } func (w *Worker) scanML307CSMS() { @@ -101,14 +185,13 @@ func (w *Worker) scanML307CSMS() { if err != nil { return } - w.runML307CSMS(owner, "", 0) + w.runML307CSMS(owner, nil) } -func (w *Worker) runML307CSMS(owner ml307cSMSOwner, storage string, index int) { +func (w *Worker) runML307CSMS(owner ml307cSMSOwner, notice *ml307cSMSNotice) { var notifications []InboundSMS - err := w.readML307CSMSInbox(owner, storage, index, ¬ifications) - if err != nil { - logger.Warn("ML307C 短信收件未完成", "device", w.ID, "storage", storage, "err", err) + if err := w.readML307CSMSInbox(owner, notice, ¬ifications); err != nil { + logger.Warn("ML307C 短信收件未完成", "device", w.ID, "err", err) } for _, inbound := range notifications { w.Pool.notifyInboundSMS(inbound) @@ -118,7 +201,7 @@ func (w *Worker) runML307CSMS(owner ml307cSMSOwner, storage string, index int) { } } -func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, storage string, index int, notifications *[]InboundSMS) error { +func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotice, notifications *[]InboundSMS) error { // The eSIM manager uses the same transition lock. Take it before the // serial inbox lock, matching the lock order used for sending. release, err := w.Pool.AcquireDeviceOperation(w.ID) @@ -145,60 +228,86 @@ func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, storage string, index if err != nil { return err } - if storage != "" { - if err := inbox.Select(storage); err != nil { + if notice != nil { + if !w.ml307cSMSNotices.current(notice) { + return nil + } + if err := inbox.Select(notice.slot.store); err != nil { return err } - record, err := inbox.Read(index) + record, err := inbox.Read(notice.slot.index) if err != nil { return err } if err := owner.verifyLive(); err != nil { return err } - return w.ingestML307CSlot(inbox, owner, state, record, true, notifications) + return w.ingestML307CSlot(inbox, owner, state, record, notice.slot.store == "SM", notice, notifications) } var scanErr error + scanIncomplete := false for _, store := range ml307cSMSStores { if err := inbox.Select(store); err != nil { return errors.Join(scanErr, err) } + // Only notices already observed before this snapshot can identify + // a listed PDU. A newer CMTI may refer to a reused slot. + pending := w.ml307cSMSNotices.snapshot(owner, store) records, err := inbox.List() if err != nil { scanErr = errors.Join(scanErr, err) + scanIncomplete = true continue } if err := owner.verifyLive(); err != nil { return errors.Join(scanErr, err) } for _, record := range records { - if err := w.ingestML307CSlot(inbox, owner, state, record, store == "SM", notifications); err != nil { + notice := pending[record.Index] + delete(pending, record.Index) + if err := w.ingestML307CSlot(inbox, owner, state, record, store == "SM", notice, notifications); err != nil { scanErr = errors.Join(scanErr, err) } } + for _, absent := range pending { + w.ml307cSMSNotices.forget(absent) + } } - if scanErr != nil { + if scanIncomplete { return scanErr } if err := owner.check(); err != nil { - return err + return errors.Join(scanErr, err) + } + recovered, err := state.archiveSettledATFragments(time.Now()) + *notifications = append(*notifications, recovered...) + if err != nil || scanErr != nil { + return errors.Join(scanErr, err) } return state.clearCompletedGroups() }) } -func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notifications *[]InboundSMS) error { +func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notice *ml307cSMSNotice, notifications *[]InboundSMS) error { if !record.Received() { + w.ml307cSMSNotices.forget(notice) return nil } if err := owner.check(); err != nil { return err } + if notice != nil && !w.ml307cSMSNotices.bind(notice, record.PDU) { + return nil + } part, err := decodeATInboxPart(owner.SMSIdentity, record.PDU) if err != nil { return fmt.Errorf("SMS slot %d: %w", record.Index, err) } + if notice != nil { + part.observedAt = notice.observedAt + sourceKnown = true + } stored, inbound, err := state.persist(part, sourceKnown) if err != nil { return fmt.Errorf("persist SMS slot %d: %w", record.Index, err) @@ -212,12 +321,16 @@ func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, s if err := inbox.DeleteMatching(record, owner.verifyLive); err != nil { return fmt.Errorf("delete persisted SMS slot %d: %w", record.Index, err) } + w.ml307cSMSNotices.forget(notice) return nil } type atInboxPart struct { smscodec.ATDeliverSMS - key string + key string + family string + fingerprint [32]byte + observedAt time.Time } func decodeATInboxPart(identity SMSIdentity, pduHex string) (atInboxPart, error) { @@ -229,7 +342,9 @@ func decodeATInboxPart(identity SMSIdentity, pduHex string) (atInboxPart, error) if err != nil || decoded.Sender == "" || decoded.Timestamp.IsZero() { return atInboxPart{}, errors.New("cannot decode stored SMS-DELIVER") } - key := fmt.Sprintf("%ssingle:%x", db.ATSMSInboundPrefix, sha256.Sum256(raw)) + fingerprint := sha256.Sum256(raw) + key := fmt.Sprintf("%ssingle:%x", db.ATSMSInboundPrefix, fingerprint) + var family string concat := decoded.Concat if concat.IsConcat { if concat.Seq < 1 || concat.Seq > concat.Total { @@ -237,14 +352,23 @@ func decodeATInboxPart(identity SMSIdentity, pduHex string) (atInboxPart, error) } group := fmt.Sprintf("%q:%q:%d:%d:%d:%s", identity.IMSI, decoded.Sender, concat.RefBits, concat.Ref, concat.Total, decoded.SCTS) key = fmt.Sprintf("%sparts:%x", db.ATSMSInboundPrefix, sha256.Sum256([]byte(group))) + origin := fmt.Sprintf("%q:%q:%q:%d:%d:%d:%d:%d:%q", identity.IMSI, decoded.Sender, decoded.SMSC, + decoded.PID, decoded.DCS, concat.RefBits, concat.Ref, concat.Total, decoded.ApplicationPorts) + family = fmt.Sprintf("%x", sha256.Sum256([]byte(origin))) + if decoded.ApplicationPorts != "" { + // Application-addressed text needs an exact SCTS and port match. + family = "app-" + family + } } - return atInboxPart{ATDeliverSMS: decoded, key: key}, nil + return atInboxPart{ATDeliverSMS: decoded, key: key, family: family, fingerprint: fingerprint}, nil } type atSMSParts struct { - scope db.SMSInboundFragmentScope - groups map[string][]db.SMSInboundFragment - seen map[string]bool + scope db.SMSInboundFragmentScope + groups map[string][]db.SMSInboundFragment + seen map[string]bool + senders map[string]string + blockedFamilies map[string]bool } func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { @@ -252,7 +376,10 @@ func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { if err != nil { return nil, err } - state := &atSMSParts{scope: scope, groups: make(map[string][]db.SMSInboundFragment), seen: make(map[string]bool)} + state := &atSMSParts{ + scope: scope, groups: make(map[string][]db.SMSInboundFragment), + seen: make(map[string]bool), senders: make(map[string]string), blockedFamilies: make(map[string]bool), + } for _, row := range rows { if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) { state.groups[row.SessionKey] = append(state.groups[row.SessionKey], row) @@ -263,11 +390,21 @@ func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { func (state *atSMSParts) persist(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { if part.Concat.IsConcat { - state.seen[part.key] = true if part.Binary { + state.seen[part.key] = true return false, nil, nil } - return state.persistFragment(part, sourceKnown) + if sourceKnown && part.observedAt.IsZero() { + part.observedAt = time.Now() + } + stored, inbound, err := state.persistFragment(part, sourceKnown) + if err != nil { + // The scan saw an exact piece for this family. If it could + // not be recorded, its older partial groups are insufficient + // evidence for any cross-SCTS assembly in this scan. + state.blockedFamilies[part.family] = true + } + return stored, inbound, err } if smsnotify.ShouldSuppressReceivedSMS(part.Content) { return false, nil, nil @@ -279,26 +416,71 @@ func (state *atSMSParts) persist(part atInboxPart, sourceKnown bool) (bool, *Inb return state.commit(part, part.Content) } -func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { - fragments := state.groups[part.key] - matched := false - for _, saved := range fragments { - if saved.Sequence == part.Concat.Seq { - if saved.Content != part.Content { - return false, nil, db.ErrSMSInboundFragmentCollision +const ( + atSMSPartGroupPrefix = db.ATSMSInboundPrefix + "parts:v2:" + atSMSReassemblyWindow = 2 * time.Minute +) + +func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (string, bool, error) { + // Older fragments only have the legacy exact-SCTS key. It remains valid + // for exact matches, but cannot prove the new metadata for a fuzzy join. + if fragments := state.groups[part.key]; len(fragments) != 0 { + for _, saved := range fragments { + if saved.Sequence == part.Concat.Seq { + if saved.Content != part.Content { + return "", false, db.ErrSMSInboundFragmentCollision + } + return part.key, true, nil } - matched = true - break + } + return part.key, false, nil + } + + prefix := atSMSPartGroupPrefix + part.family + ":" + part.SCTS + ":" + var duplicates, candidates []string + for key, fragments := range state.groups { + if !strings.HasPrefix(key, prefix) { + continue + } + occupied := false + for _, saved := range fragments { + if saved.Sequence == part.Concat.Seq { + occupied = true + if saved.Content == part.Content { + duplicates = append(duplicates, key) + } + break + } + } + if !occupied && len(fragments) < part.Concat.Total { + candidates = append(candidates, key) } } + switch { + case len(duplicates) > 1 || len(duplicates) == 0 && len(candidates) > 1: + return "", false, db.ErrSMSInboundFragmentCollision + case len(duplicates) == 1: + return duplicates[0], true, nil + case len(candidates) == 1: + return candidates[0], false, nil + case sourceKnown: + return fmt.Sprintf("%s%d:%x", prefix, part.observedAt.UnixNano(), part.fingerprint), false, nil + default: + return "", false, nil + } +} + +func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { + key, matched, err := state.fragmentGroup(part, sourceKnown) + if err != nil || key == "" { + return false, nil, err + } + state.seen[key] = true + state.senders[key] = part.Sender + fragments := state.groups[key] if !matched { - // Another part with the exact session key establishes this ME - // fragment's provenance after the worker has restarted. - if !sourceKnown && len(fragments) == 0 { - return false, nil, nil - } scope := state.scope - scope.SessionKey = part.key + scope.SessionKey = key concat := part.Concat result, err := db.SaveSMSInboundFragment(scope, db.SMSInboundFragment{ Sequence: concat.Seq, Reference: concat.Ref, ReferenceBits: concat.RefBits, @@ -308,19 +490,151 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo return false, nil, err } fragments = result.Fragments - state.groups[part.key] = fragments + state.groups[key] = fragments } if len(fragments) < part.Concat.Total { - return true, nil, nil + // Keep the source while other exact groups can still arrive. + return false, nil, nil } + part.key, part.Content, err = completeATMultipart(key, fragments) + if err != nil { + return false, nil, err + } + part.Timestamp = fragments[0].ArrivedAt + return state.commit(part, part.Content) +} + +func (state *atSMSParts) archiveSettledATFragments(now time.Time) ([]InboundSMS, error) { + var notifications []InboundSMS + for _, fragments := range state.settledATFragments(now) { + var sender string + for _, fragment := range fragments { + if sender = state.senders[fragment.SessionKey]; sender != "" { + break + } + } + if sender == "" { + // Sender information is available from an exact PDU in this scan. + continue + } + key, content, err := completeATMultipart(fragments[0].SessionKey, fragments) + if err != nil { + return notifications, err + } + part := atInboxPart{key: key, ATDeliverSMS: smscodec.ATDeliverSMS{Sender: sender, Timestamp: fragments[0].ArrivedAt}} + _, inbound, err := state.commit(part, content) + if err != nil { + return notifications, err + } + if inbound != nil { + notifications = append(notifications, *inbound) + } + // Keep cross-SCTS source slots and exact fragment rows for retry. + } + return notifications, nil +} + +// settledATFragments only identifies candidates. The caller must first finish +// a complete scan and commit a candidate before touching its storage slots. +func (state *atSMSParts) settledATFragments(now time.Time) [][]db.SMSInboundFragment { + type observedGroup struct { + at time.Time + parts []db.SMSInboundFragment + } + families := make(map[string][]observedGroup) + for key, parts := range state.groups { + if len(parts) == 0 || len(parts) >= parts[0].Total { + continue + } + body, ok := strings.CutPrefix(key, atSMSPartGroupPrefix) + if !ok { + continue // Legacy groups lack the SMSC and coding metadata. + } + fields := strings.Split(body, ":") + if len(fields) != 4 || strings.HasPrefix(fields[0], "app-") || state.blockedFamilies[fields[0]] { + continue + } + observed, err := strconv.ParseInt(fields[2], 10, 64) + if err != nil { + continue + } + families[fields[0]] = append(families[fields[0]], observedGroup{time.Unix(0, observed), parts}) + } + + var settled [][]db.SMSInboundFragment + for _, groups := range families { + slices.SortFunc(groups, func(a, b observedGroup) int { return a.at.Compare(b.at) }) + for start := 0; start < len(groups); { + end := start + 1 + for end < len(groups) && groups[end].at.Sub(groups[end-1].at) <= atSMSReassemblyWindow { + end++ + } + window := groups[start:end] + start = end + last := window[len(window)-1].at + if len(window) < 2 || last.Sub(window[0].at) > atSMSReassemblyWindow || now.Sub(last) < atSMSReassemblyWindow { + continue + } + var parts []db.SMSInboundFragment + for _, group := range window { + parts = append(parts, group.parts...) + } + if assembled := uniqueATFragmentSet(parts); assembled != nil { + settled = append(settled, assembled) + } + } + } + return settled +} + +func uniqueATFragmentSet(parts []db.SMSInboundFragment) []db.SMSInboundFragment { + if len(parts) != parts[0].Total { + return nil + } + ordered := make([]db.SMSInboundFragment, len(parts)) + earliest, latest := parts[0].ArrivedAt, parts[0].ArrivedAt + for _, part := range parts { + if part.Total != len(ordered) || part.Sequence < 1 || part.Sequence > len(ordered) || + ordered[part.Sequence-1].Sequence != 0 { + return nil + } + ordered[part.Sequence-1] = part + if part.ArrivedAt.Before(earliest) { + earliest = part.ArrivedAt + } + if part.ArrivedAt.After(latest) { + latest = part.ArrivedAt + } + } + if latest.Sub(earliest) > atSMSReassemblyWindow { + return nil + } + return ordered +} + +func completeATMultipart(key string, fragments []db.SMSInboundFragment) (string, string, error) { var content strings.Builder + var signature strings.Builder + family, _, versioned := strings.Cut(strings.TrimPrefix(key, atSMSPartGroupPrefix), ":") + versioned = versioned && strings.HasPrefix(key, atSMSPartGroupPrefix) for i, fragment := range fragments { - if fragment.Sequence != i+1 || fragment.Total != part.Concat.Total { - return false, nil, db.ErrSMSInboundFragmentCollision + if fragment.Sequence != i+1 || fragment.Total != len(fragments) { + return "", "", db.ErrSMSInboundFragmentCollision } content.WriteString(fragment.Content) + if versioned { + fields := strings.Split(strings.TrimPrefix(fragment.SessionKey, atSMSPartGroupPrefix), ":") + if len(fields) != 4 || fields[0] != family { + return "", "", db.ErrSMSInboundFragmentCollision + } + fmt.Fprintf(&signature, "%s:%q;", fields[1], fragment.Content) + } } - return state.commit(part, content.String()) + if versioned { + // Independent of which part arrived first or which worker read it. + key = fmt.Sprintf("%sparts:complete:v2:%x", db.ATSMSInboundPrefix, sha256.Sum256([]byte(family+":"+signature.String()))) + } + return key, content.String(), nil } func (state *atSMSParts) commit(part atInboxPart, content string) (bool, *InboundSMS, error) { @@ -351,7 +665,11 @@ func (state *atSMSParts) clearCompletedGroups() error { }) { continue } - _, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, key) + completedKey, _, err := completeATMultipart(key, fragments) + if err != nil { + return err + } + _, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, completedKey) if err != nil { return err } diff --git a/internal/device/sms_ml307c_test.go b/internal/device/sms_ml307c_test.go index b46966bd..bde56195 100644 --- a/internal/device/sms_ml307c_test.go +++ b/internal/device/sms_ml307c_test.go @@ -3,6 +3,7 @@ package device import ( "encoding/hex" "testing" + "time" "github.com/yibaiba/hideck/internal/db" ) @@ -11,15 +12,17 @@ func TestML307CStoredSMSPersistence(t *testing.T) { initDevicePhoneNumberTestDB(t) identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} - fragment := func(seq, second byte, ch rune) atInboxPart { + fragment := func(seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart { t.Helper() pdu := []byte{ 0, // default SMSC 0x40, 3, 0x81, 0x77, 0xF7, // SMS-DELIVER, UDHI, sender 777 0, 8, // PID, UCS2 - 0x62, 0x11, 0x91, 0x21, 0, second, 0, // SCTS - 8, 5, 0, 3, 17, 2, seq, byte(ch >> 8), byte(ch), + 0x62, 0x11, 0x91, 0x21, minute, second, 0, // SCTS + byte(8 + len(extraUDH)), byte(5 + len(extraUDH)), 0, 3, 17, 2, seq, } + pdu = append(pdu, extraUDH...) + pdu = append(pdu, byte(ch>>8), byte(ch)) part, err := decodeATInboxPart(identity, hex.EncodeToString(pdu)) if err != nil { t.Fatal(err) @@ -27,6 +30,7 @@ func TestML307CStoredSMSPersistence(t *testing.T) { if !part.Concat.IsConcat || part.Sender != "777" || part.Content != string(ch) { t.Fatalf("unexpected decoded part: %+v", part) } + part.observedAt = observed return part } load := func(scope db.SMSInboundFragmentScope) *atSMSParts { @@ -52,26 +56,35 @@ func TestML307CStoredSMSPersistence(t *testing.T) { } } - a1, a2 := fragment(1, 0, '甲'), fragment(2, 0, '乙') - b1, b2 := fragment(1, 0x10, '丙'), fragment(2, 0x10, '丁') + observed := time.Now() + a1 := fragment(1, 0, 0, '甲', observed) + a2 := fragment(2, 0, 0, '乙', observed.Add(2*time.Second)) + b1 := fragment(1, 0, 0x10, '丙', observed.Add(3*time.Second)) + b2 := fragment(2, 0, 0x10, '丁', observed.Add(time.Second)) state := load(scope) - apply(state, a1, false, false, "") // unknown ME: no history and no delete - apply(state, a1, true, true, "") // CMTI persists the first part before removing its slot + apply(state, a1, false, false, "") // unknown ME: no history and no delete. + apply(state, a1, true, false, "") // CMTI proves provenance, but an incomplete message retains its source slot. - state = load(scope) // new process/worker can see the durable fragment - if state.groups[a1.key][0].Content != "甲" { - t.Fatal("first fragment was not restored") + state = load(scope) + if len(state.groups) != 1 { + t.Fatalf("first fragment was not restored: %+v", state.groups) } - apply(state, b2, true, true, "") // same ref, different SCTS cannot complete A - apply(state, a2, false, true, "甲乙") // the missing tail arrived in ME while HiDeck was offline + apply(state, b2, true, false, "") // Another message reused the ref inside the collection window. + if got := state.settledATFragments(observed.Add(time.Second)); len(got) != 0 { + t.Fatal("merged A1 and B2 before their exact partners arrived") + } + apply(state, a2, true, true, "甲乙") apply(state, b1, true, true, "丙丁") + if got := state.settledATFragments(observed.Add(5 * time.Minute)); len(got) != 0 { + t.Fatal("already complete exact messages must not be merged") + } - state = load(scope) // deletion failed before restart; the PDU is still on ME - apply(state, a2, false, true, "") // matched durable part, no duplicate notification + state = load(scope) + apply(state, a2, false, true, "") // A failed deletion can retry from durable evidence. if err := state.clearCompletedGroups(); err != nil { t.Fatal(err) } - if len(load(scope).groups[a1.key]) != 2 { + if len(load(scope).groups) != 1 { t.Fatal("a scan containing a residual slot retired its fragment rows") } otherDevice := scope @@ -79,16 +92,112 @@ func TestML307CStoredSMSPersistence(t *testing.T) { if err := load(otherDevice).clearCompletedGroups(); err != nil { t.Fatal(err) } - if len(load(scope).groups[a1.key]) != 2 { + if len(load(scope).groups) != 1 { t.Fatal("another module's empty scan retired the original module's fragments") } - if err := load(scope).clearCompletedGroups(); err != nil { // subsequent complete, empty scan + if err := load(scope).clearCompletedGroups(); err != nil { t.Fatal(err) } if len(load(scope).groups) != 0 { t.Fatal("completed fragment groups were not collected") } + // Legacy groups can still finish after upgrade with their original key. + legacy1 := fragment(1, 0x05, 0, '旧', observed) + legacy2 := fragment(2, 0x05, 0, '件', observed) + legacyScope := scope + legacyScope.SessionKey = legacy1.key + if _, err := db.SaveSMSInboundFragment(legacyScope, db.SMSInboundFragment{ + Sequence: 1, Reference: 17, ReferenceBits: 8, Total: 2, Content: legacy1.Content, ArrivedAt: legacy1.Timestamp, + }); err != nil { + t.Fatal(err) + } + apply(load(scope), legacy2, false, true, "旧件") + + observed = observed.Add(5 * time.Minute) + c1 := fragment(1, 0x30, 0x95, '跨', observed) + c2 := fragment(2, 0x40, 0x10, '秒', observed.Add(2*time.Second)) + state = load(scope) + apply(state, c1, true, false, "") + apply(state, c2, false, false, "") // Nearby SCTS alone is insufficient proof for an unknown ME slot. + if len(state.groups) != 2 { + t.Fatal("unknown ME tail was persisted") + } + apply(state, c2, true, false, "") + state = load(scope) // Process restart before the follow-up full scan. + apply(state, c1, false, false, "") + apply(state, c2, false, false, "") + if messages, err := state.archiveSettledATFragments(observed.Add(time.Minute)); err != nil || len(messages) != 0 { + t.Fatalf("cross-minute group settled before its collection window elapsed: %+v, %v", messages, err) + } + got := state.settledATFragments(observed.Add(3 * time.Minute)) + if len(got) != 1 { + t.Fatalf("settled cross-minute groups = %d, want 1", len(got)) + } + key, content, err := completeATMultipart(got[0][0].SessionKey, got[0]) + if err != nil || content != "跨秒" { + t.Fatalf("complete fragment set: %q, %q, %v", key, content, err) + } + messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)) + if err != nil || len(messages) != 1 || messages[0].Content != content { + t.Fatalf("archive after restart: %+v, %v", messages, err) + } + if saved, found, err := db.LookupCompletedReceivedSMS(scope.ICCID, scope.IMSI, key); err != nil || !found || saved.Content != content { + t.Fatalf("archived history: %+v, %v, %v", saved, found, err) + } + state = load(scope) + apply(state, c1, false, false, "") + apply(state, c2, false, false, "") + if messages, err := state.archiveSettledATFragments(observed.Add(4 * time.Minute)); err != nil || len(messages) != 0 { + t.Fatalf("repeat scan notified an archived SMS twice: %+v, %v", messages, err) + } + + // A second possible first part within the same family/window makes the + // entire candidate ambiguous, regardless of how close the older SCTS is. + otherFirst := fragment(1, 0x40, 0, '混', observed.Add(time.Second)) + apply(state, otherFirst, true, false, "") + if got := state.settledATFragments(observed.Add(3 * time.Minute)); len(got) != 0 { + t.Fatal("settled a cross-SCTS group with conflicting sequences") + } + + port1 := fragment(1, 0x55, 0, '端', observed, 4, 2, 0x10, 0x20) + port2 := fragment(2, 0x55, 0, '隔', observed, 4, 2, 0x10, 0x21) + if port1.ApplicationPorts == "" || port1.family == port2.family { + t.Fatal("8-bit source application ports did not distinguish groups") + } + apply(state, port1, true, false, "") + apply(state, port2, true, false, "") + port3 := fragment(1, 0x65, 0, '应', observed, 5, 4, 0x0b, 0x01, 0x0b, 0x03) + port4 := fragment(2, 0x65, 0x10, '离', observed, 5, 4, 0x0b, 0x02, 0x0b, 0x03) + if port3.ApplicationPorts == "" || port3.family == port4.family { + t.Fatal("16-bit destination application ports did not distinguish groups") + } + apply(state, port3, true, false, "") + apply(state, port4, true, false, "") + if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 { + t.Fatalf("application-addressed SMS merged across SCTS: %+v, %v", messages, err) + } + + // A2 is visible in this scan, but its durable write fails. Without that + // evidence the older A1/B2 pair looks unique and must still stay pending. + observed = observed.Add(10 * time.Minute) + x1 := fragment(1, 0x64, 0, '先', observed) + y2 := fragment(2, 0x64, 0x10, '后', observed.Add(time.Second)) + x2 := fragment(2, 0x64, 0, '正', observed.Add(2*time.Second)) + state = load(scope) + apply(state, x1, true, false, "") + apply(state, y2, true, false, "") + if err := db.DB.Exec(`CREATE TRIGGER test_reject_fragment BEFORE INSERT ON sms_inbound_fragment + WHEN NEW.content = '正' BEGIN SELECT RAISE(ABORT, 'test fragment write failure'); END`).Error; err != nil { + t.Fatal(err) + } + if stored, message, err := state.persist(x2, true); err == nil || stored || message != nil { + t.Fatalf("fault injection failed: %v, %+v, %v", stored, message, err) + } + if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 { + t.Fatalf("archive ignored a same-family write failure: %+v, %v", messages, err) + } + swapped := scope swapped.ICCID, swapped.IMSI = "8988110000000000002", "001010123456788" apply(load(swapped), a1, false, false, "") // unknown old ME after a card change @@ -102,3 +211,40 @@ func TestML307CStoredSMSPersistence(t *testing.T) { t.Fatalf("DB failure allowed deleting the slot: %t, %v", stored, err) } } + +func TestML307CStoredSMSNoticeSurvivesReadFailure(t *testing.T) { + w := &Worker{} + slot := ml307cSMSSlot{store: "ME", index: 7} + // With identity still unknown, a notification cannot attest a later card. + w.handleML307CStoredSMS(slot.store, "7") + if len(w.ml307cSMSNotices.slots) != 0 { + t.Fatal("unknown SIM claimed an ME slot") + } + owner := ml307cSMSOwner{simGeneration: 1} + notice := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.ml307cSMSNotices.add(notice) // An unsuccessful CMGR leaves the notification unresolved. + + retry := w.ml307cSMSNotices.snapshot(owner, slot.store)[slot.index] + if retry != notice || !w.ml307cSMSNotices.bind(retry, "001122") { + t.Fatal("periodic list could not recover the pending ME notification") + } + if w.ml307cSMSNotices.bind(retry, "aabbcc") { + t.Fatal("retry accepted a replacement after the original PDU was read") + } + + next := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.ml307cSMSNotices.add(next) + w.ml307cSMSNotices.forget(notice) + if !w.ml307cSMSNotices.bind(next, "aabbcc") { + t.Fatal("old task discarded a newer slot notification") + } + owner.simGeneration++ + if len(w.ml307cSMSNotices.snapshot(owner, slot.store)) != 0 || w.ml307cSMSNotices.bind(next, "aabbcc") { + t.Fatal("new SIM generation inherited an ME notice") + } + latest := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.ml307cSMSNotices.add(latest) + if len(w.ml307cSMSNotices.snapshot(next.owner, slot.store)) != 0 || !w.ml307cSMSNotices.current(latest) { + t.Fatal("an old scan discarded a newer SIM generation's notice") + } +} diff --git a/pkg/smscodec/pdu.go b/pkg/smscodec/pdu.go index d87f0ec5..08f2dac4 100644 --- a/pkg/smscodec/pdu.go +++ b/pkg/smscodec/pdu.go @@ -370,12 +370,16 @@ type ConcatInfo struct { } type ATDeliverSMS struct { - Sender string - Content string - Timestamp time.Time - SCTS string - Concat ConcatInfo - Binary bool + Sender string + Content string + Timestamp time.Time + SCTS string + SMSC string + PID byte + DCS byte + ApplicationPorts string + Concat ConcatInfo + Binary bool } // DecodeATDeliverSMS decodes a full PDU from an AT storage slot, preserving @@ -384,23 +388,36 @@ func DecodeATDeliverSMS(fullPDU []byte) (ATDeliverSMS, error) { if len(fullPDU) == 0 || 1+int(fullPDU[0]) >= len(fullPDU) { return ATDeliverSMS{}, errors.New("invalid SMSC length") } - tpduBytes := fullPDU[1+int(fullPDU[0]):] - _, _, udOffset, _, alphabet, ok := deliverTPDULayout(tpduBytes) + smscEnd := 1 + int(fullPDU[0]) + tpduBytes := fullPDU[smscEnd:] + dcs, _, udOffset, _, alphabet, ok := deliverTPDULayout(tpduBytes) if !ok { return ATDeliverSMS{}, errors.New("invalid SMS-DELIVER TPDU layout") } part := ATDeliverSMS{ SCTS: hex.EncodeToString(tpduBytes[udOffset-8 : udOffset-1]), + SMSC: hex.EncodeToString(fullPDU[:smscEnd]), + PID: tpduBytes[udOffset-10], + DCS: dcs, Binary: alphabet == tpdu.Alpha8Bit, } var err error - part.Sender, part.Content, part.Timestamp, part.Concat, err = DecodeDeliverTPDU(tpduBytes) + var ports udhPorts + part.Sender, part.Content, part.Timestamp, part.Concat, err = decodeDeliverTPDU(tpduBytes, &ports) + if err == nil && (ports.Has8Bit || ports.Has16Bit) { + part.ApplicationPorts = fmt.Sprintf("%t:%d:%d:%t:%d:%d", ports.Has8Bit, ports.DestPort8, ports.SrcPort8, + ports.Has16Bit, ports.DestPort16, ports.SrcPort16) + } return part, err } // DecodeDeliverTPDU 解码下行短信 TPDU,返回发送方号码、文本内容、发送时间、和 concat 分片信息。 // 如果 TPDU 包含 UDH concatenation header(长短信分片),concat.IsConcat 为 true。 func DecodeDeliverTPDU(tpduBytes []byte) (sender string, text string, ts time.Time, concat ConcatInfo, err error) { + return decodeDeliverTPDU(tpduBytes, nil) +} + +func decodeDeliverTPDU(tpduBytes []byte, ports *udhPorts) (sender string, text string, ts time.Time, concat ConcatInfo, err error) { if trimmed, ok := TrimDeliverTPDUToDeclaredLength(tpduBytes); ok { tpduBytes = trimmed } @@ -415,6 +432,9 @@ func DecodeDeliverTPDU(tpduBytes []byte) (sender string, text string, ts time.Ti if err != nil { return "", "", time.Time{}, ConcatInfo{}, err } + if ports != nil { + *ports = parseUDHPorts(t.UDH) + } // 检测 UDH 中的 concatenation 信息(长短信分片标识) if t.UDH != nil { if segments, seqno, mref, ok := t.UDH.ConcatInfo8(); ok && segments > 1 { From 279ed863c2ed6d848205e478da36088935af929a Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:53:56 +0800 Subject: [PATCH 14/39] chore(device): raise default device limit to ten --- internal/device/device_limit.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/device/device_limit.go b/internal/device/device_limit.go index eda679b5..a98d0e2d 100644 --- a/internal/device/device_limit.go +++ b/internal/device/device_limit.go @@ -7,7 +7,7 @@ import ( "github.com/yibaiba/hideck/internal/config" ) -const DefaultFreeDeviceLimit = 5 +const DefaultFreeDeviceLimit = 10 func FreeDeviceLimitReached(count int) bool { return count >= DefaultFreeDeviceLimit From 2a64ac7e13dbf62ae3367d238ad1b92abc31cbad Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 17:57:12 +0800 Subject: [PATCH 15/39] fix(api): keep SMS result writable after modem waits --- internal/api/server_tls.go | 7 ++-- internal/api/sms_send_usecase.go | 17 ++++++++++ internal/api/sms_send_usecase_test.go | 49 +++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/internal/api/server_tls.go b/internal/api/server_tls.go index c266746d..a8f8d804 100644 --- a/internal/api/server_tls.go +++ b/internal/api/server_tls.go @@ -12,8 +12,9 @@ import ( ) const ( - defaultHTTPSAddress = ":7576" - maxServerHeaderBytes = 1 << 20 + defaultHTTPSAddress = ":7576" + maxServerHeaderBytes = 1 << 20 + managedHTTPWriteTimeout = 120 * time.Second ) func (s *Server) serveHTTP() error { @@ -63,7 +64,7 @@ func (s *Server) serveHTTPAndHTTPS(certificate tls.Certificate) error { func newManagedHTTPServer(address string, handler http.Handler) *http.Server { return &http.Server{ Addr: address, Handler: handler, ReadHeaderTimeout: 5 * time.Second, - ReadTimeout: 120 * time.Second, WriteTimeout: 120 * time.Second, + ReadTimeout: 120 * time.Second, WriteTimeout: managedHTTPWriteTimeout, IdleTimeout: 60 * time.Second, MaxHeaderBytes: maxServerHeaderBytes, } } diff --git a/internal/api/sms_send_usecase.go b/internal/api/sms_send_usecase.go index 3102cfef..748837b9 100644 --- a/internal/api/sms_send_usecase.go +++ b/internal/api/sms_send_usecase.go @@ -1,6 +1,7 @@ package api import ( + "errors" "fmt" "net/http" "strings" @@ -54,7 +55,23 @@ func (s *Server) useSendSMS(c businessContext) { partsTotal := 1 deliveryState := "acked" + // A multi-part send can outlast the server's write deadline. Preserve a + // fresh write window for the result without changing modem timeouts. + var responseController *http.ResponseController + if rest, ok := c.(*gin.Context); ok { + controller := http.NewResponseController(rest.Writer) + if err := controller.SetWriteDeadline(time.Time{}); err == nil { + responseController = controller + } else if !errors.Is(err, http.ErrNotSupported) { + logger.Warn("取消短信发送等待写入超时失败", "err", err) + } + } routed, err := s.pool.SendRoutedSMS(businessRequestContext(c), worker, req.Phone, req.Message, sendOpts) + if responseController != nil { + if err := responseController.SetWriteDeadline(time.Now().Add(managedHTTPWriteTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) { + logger.Warn("恢复短信响应写入超时失败", "err", err) + } + } if respondOutboundLimit(c, err) { return } diff --git a/internal/api/sms_send_usecase_test.go b/internal/api/sms_send_usecase_test.go index e457254e..256c3b53 100644 --- a/internal/api/sms_send_usecase_test.go +++ b/internal/api/sms_send_usecase_test.go @@ -7,7 +7,9 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" + "time" "github.com/gin-gonic/gin" "github.com/iniwex5/vowifi-go/runtimehost/messaging" @@ -86,3 +88,50 @@ func TestSendSMSRecordsUnconfirmedSubmission(t *testing.T) { }) } } + +func TestRESTSMSUncertainResultSurvivesWriteTimeout(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + pool := device.NewPool(&config.Config{}) + worker := &device.Worker{ID: "sms-at"} + pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{ + ICCID: "8944000000000000601", IMSI: "234150000000601", + }) + const writeTimeout = 100 * time.Millisecond + var sends atomic.Int32 + pool.SetRoutedSMSTestSenders(nil, func(string, string, string) error { + sends.Add(1) + time.Sleep(3 * writeTimeout) + return &modem.SMSSubmitError{PartsTotal: 3, PartsConfirmed: 2, Err: modem.ErrSMSSubmitUnknown} + }) + + server := &Server{pool: pool} + router := gin.New() + router.POST("/api/sms/send", server.handleSendSMS) + httpServer := httptest.NewUnstartedServer(router) + httpServer.Config.WriteTimeout = writeTimeout + httpServer.Start() + t.Cleanup(httpServer.Close) + client := httpServer.Client() + client.Timeout = 3 * time.Second + + resp, err := client.Post(httpServer.URL+"/api/sms/send", "application/json", strings.NewReader( + `{"device_id":"sms-at","phone":"777","message":"test"}`)) + if err != nil { + t.Fatalf("await SMS submission response: %v", err) + } + defer resp.Body.Close() + var result struct { + DeliveryState string `json:"delivery_state"` + PartsTotal int `json:"parts_total"` + PartsConfirmed int `json:"parts_confirmed"` + Message string `json:"message"` + } + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + t.Fatalf("decode HTTP %d: %v", resp.StatusCode, err) + } + if resp.StatusCode != http.StatusAccepted || result.DeliveryState != db.SMSDeliveryStateUnknown || + result.PartsTotal != 3 || result.PartsConfirmed != 2 || !strings.Contains(result.Message, "请勿重发整条") || sends.Load() != 1 { + t.Fatalf("HTTP %d result=%+v CS sends=%d", resp.StatusCode, result, sends.Load()) + } +} From 2a078864734cfa1a4d95acf343254dbb3c975f6a Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 18:15:39 +0800 Subject: [PATCH 16/39] refactor(device): use a common AT SMS scan entry point --- internal/device/pool_bootstrap.go | 4 ++-- internal/device/sms_ml307c.go | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 2c56c0e5..69132ab4 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -758,7 +758,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) default: } worker.PreWarmCache() - worker.scanML307CSMS() + worker.scanATSMS() // 缓存预热完成后,触发一次状态广播,强制前端 SSE 推流更新最新设备数据 p.broadcastVoWiFiStateChange(worker.ID) }(w) @@ -802,7 +802,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) case <-ticker.C: switch worker.smsMode { case smsModeAT: - worker.scanML307CSMS() + worker.scanATSMS() case smsModeQMI: if worker.QMICore != nil { if err := worker.CheckAllSMSQMI(); err != nil { diff --git a/internal/device/sms_ml307c.go b/internal/device/sms_ml307c.go index 08f14073..6ccf80fe 100644 --- a/internal/device/sms_ml307c.go +++ b/internal/device/sms_ml307c.go @@ -177,8 +177,9 @@ func (w *Worker) handleML307CStoredSMS(storage, index string) { go w.runML307CSMS(owner, notice) } -func (w *Worker) scanML307CSMS() { - if !w.isML307C() || !w.Modem.StoredSMSReceiving() { +// scanATSMS polls the stored inbox when the active AT SMS path enables it. +func (w *Worker) scanATSMS() { + if w.Modem == nil || !w.Modem.StoredSMSReceiving() { return } owner, err := w.ml307cSMSOwner() From e15777e730529e7e141b12f79801caa51de59ce0 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 18:23:01 +0800 Subject: [PATCH 17/39] refactor(device): unify AT discovery and identity rules --- internal/api/device_mgmt.go | 65 +++++++++++----------- internal/api/device_mgmt_discovery_test.go | 41 +++++++++++++- internal/device/at_port_resolver.go | 4 +- internal/device/discovery_compat.go | 6 +- internal/device/discovery_enrichment.go | 43 ++++++++++---- internal/device/ml307c_discovery_test.go | 18 +++++- internal/device/pool.go | 53 +++++++----------- internal/device/pool_at_identity.go | 25 ++++++++- internal/device/pool_bootstrap.go | 31 ++++++----- internal/device/pool_rescan_guard.go | 13 ++--- internal/device/sms_identity.go | 2 +- 11 files changed, 196 insertions(+), 105 deletions(-) diff --git a/internal/api/device_mgmt.go b/internal/api/device_mgmt.go index 96cbbc7c..1b19bd80 100644 --- a/internal/api/device_mgmt.go +++ b/internal/api/device_mgmt.go @@ -1220,41 +1220,42 @@ func (s *Server) useDeviceMgmtDiscovered(c businessContext) { resolvedATPort := strings.TrimSpace(dev.ATPort) imei := strings.TrimSpace(dev.IMEI) - if withIMEI && dev.ATProfile() == modem.ATProfileML307C { - var owned bool - dev, owned = managedIndex.ReadOwnedATIdentity(dev) - if !owned { - dev, _ = enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{ + if withIMEI { + live, handled := managedIndex.ResolveLiveATIdentity(dev, func(raw device.CompatibleModem) (device.CompatibleModem, string) { + return enrichDiscoveredCompatibleModemFn(raw, device.CompatibleModemEnrichOptions{ EnableATProbe: true, ATProbeTimeout: 900 * time.Millisecond, }) - } - resolvedATPort, imei = dev.ATPort, dev.IMEI - } else if withIMEI { - managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface)) - if hasManaged { - if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) { - resolvedATPort = managedMatch.ATPort - } - if imei == "" { - imei = managedMatch.IMEI - } + }) + if handled { + dev = live + resolvedATPort, imei = dev.ATPort, dev.IMEI } else { - probed, discoveredIMEI := enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{ - EnableATProbe: true, - ATProbeTimeout: 900 * time.Millisecond, - EnableQMIIMEIProbe: strings.TrimSpace(dev.ControlPath) != "" && dev.Mode != "mbim", - }) - dev = probed - if resolved := strings.TrimSpace(probed.ATPort); resolved != "" { - resolvedATPort = resolved - } - if imei == "" { - imei = discoveredIMEI - } - // MBIM 设备没有 AT 端口也不支持 QMI,使用 MBIM DeviceCaps 探测 IMEI - if imei == "" && dev.Mode == "mbim" && strings.TrimSpace(dev.ControlPath) != "" { - if mbimIMEI, err := probeIMEIViaMBIMForMgmtFn(dev.ControlPath); err == nil && mbimIMEI != "" { - imei = mbimIMEI + managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface)) + if hasManaged { + if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) { + resolvedATPort = managedMatch.ATPort + } + if imei == "" { + imei = managedMatch.IMEI + } + } else { + probed, discoveredIMEI := enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{ + EnableATProbe: true, + ATProbeTimeout: 900 * time.Millisecond, + EnableQMIIMEIProbe: strings.TrimSpace(dev.ControlPath) != "" && dev.Mode != "mbim", + }) + dev = probed + if resolved := strings.TrimSpace(probed.ATPort); resolved != "" { + resolvedATPort = resolved + } + if imei == "" { + imei = discoveredIMEI + } + // MBIM 设备没有 AT 端口也不支持 QMI,使用 MBIM DeviceCaps 探测 IMEI + if imei == "" && dev.Mode == "mbim" && strings.TrimSpace(dev.ControlPath) != "" { + if mbimIMEI, err := probeIMEIViaMBIMForMgmtFn(dev.ControlPath); err == nil && mbimIMEI != "" { + imei = mbimIMEI + } } } } diff --git a/internal/api/device_mgmt_discovery_test.go b/internal/api/device_mgmt_discovery_test.go index 44f65ed6..6aa6f7b5 100644 --- a/internal/api/device_mgmt_discovery_test.go +++ b/internal/api/device_mgmt_discovery_test.go @@ -10,6 +10,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/gin-gonic/gin" "github.com/yibaiba/hideck/internal/config" @@ -252,11 +253,49 @@ func TestHandleDeviceMgmtDiscoveredExposesPCSCFailure(t *testing.T) { } } +func TestHandleDeviceMgmtDiscoveredReadsLiveATIdentityOnlyOnRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtDiscoveryConfig(t, "server:\n port: \":7575\"\ndevices: []") + if err := config.InitGlobalManager(path); err != nil { + t.Fatal(err) + } + restoreDiscoveryStubs(t) + discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil } + discoverPCSCReadersForMgmtFn = func(context.Context) ([]pcsc.Reader, error) { return nil, nil } + discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) { + return []device.CompatibleModem{{ + USBPath: "/sys/bus/usb/devices/1-1", VendorID: 0x2ecc, ProductID: 0x3012, + ATPort: "/dev/ttyUSB8", ATPorts: []string{"/dev/ttyUSB8"}, Mode: "at", + }}, nil + } + const liveIMEI = "490154203237518" + var calls []device.CompatibleModemEnrichOptions + enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) { + calls = append(calls, opts) + return dev, liveIMEI + } + srv := &Server{pool: device.NewPool(&config.Config{}), configPath: path} + static := requestDiscoveredDevicesWithQuery(t, srv, "") + if len(calls) != 0 || len(static.Devices) != 1 || static.Devices[0].IMEI != "" || static.Devices[0].ATPort != "/dev/ttyUSB8" { + t.Fatalf("static discovery probed or lost the attachment: probes=%d devices=%+v", len(calls), static.Devices) + } + live := requestDiscoveredDevices(t, srv) + if len(calls) != 1 || !calls[0].EnableATProbe || calls[0].ATProbeTimeout != 900*time.Millisecond || calls[0].EnableQMIIMEIProbe || + len(live.Devices) != 1 || live.Devices[0].IMEI != liveIMEI { + t.Fatalf("unexpected live AT discovery: probes=%+v devices=%+v", calls, live.Devices) + } +} + func requestDiscoveredDevices(t *testing.T, srv *Server) discoveredDevicesResponse { + t.Helper() + return requestDiscoveredDevicesWithQuery(t, srv, "?with_imei=1") +} + +func requestDiscoveredDevicesWithQuery(t *testing.T, srv *Server, query string) discoveredDevicesResponse { t.Helper() recorder := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(recorder) - ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered?with_imei=1", nil) + ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered"+query, nil) srv.handleDeviceMgmtDiscovered(ctx) diff --git a/internal/device/at_port_resolver.go b/internal/device/at_port_resolver.go index 84953f49..a1b5076b 100644 --- a/internal/device/at_port_resolver.go +++ b/internal/device/at_port_resolver.go @@ -95,7 +95,7 @@ func ResolveQMIDeviceATPort(dev QMIDevice, timeout time.Duration) (QMIDevice, st // ResolveCompatibleModemATPort 为兼容发现结果解析真实可用的主 AT 口。 // 行为与 QMI 设备一致,同样只允许在该设备自己的 ATPorts 范围内探测。 func ResolveCompatibleModemATPort(dev CompatibleModem, timeout time.Duration) (CompatibleModem, string) { - if dev.ATProfile() == modem.ATProfileML307C { + if atIdentityRulesFor(dev.ATProfile()).verifyLiveIMEI { return ResolveCompatibleModemATPortContext(context.Background(), dev, timeout) } atPort, imei := ResolveATPortForDevice(dev.ATPort, dev.ATPorts, timeout) @@ -113,7 +113,7 @@ func ResolveCompatibleModemATPortContext( timeout time.Duration, ) (CompatibleModem, string) { profile := dev.ATProfile() - if profile == modem.ATProfileML307C { + if atIdentityRulesFor(profile).verifyLiveIMEI { preferred := dev.ATPort dev.ATPort, dev.IMEI = "", "" for _, port := range orderedATPortCandidates(preferred, dev.ATPorts) { diff --git a/internal/device/discovery_compat.go b/internal/device/discovery_compat.go index d0d63f79..ef0f1bd0 100644 --- a/internal/device/discovery_compat.go +++ b/internal/device/discovery_compat.go @@ -33,7 +33,11 @@ type CompatibleModem struct { } func (m CompatibleModem) ATProfile() modem.ATProfile { - if (usbDeviceIdentity{vendorID: m.VendorID, productID: m.ProductID}).isML307C() { + return (usbDeviceIdentity{vendorID: m.VendorID, productID: m.ProductID}).atProfile() +} + +func (id usbDeviceIdentity) atProfile() modem.ATProfile { + if id.isML307C() { return modem.ATProfileML307C } return modem.ATProfileDefault diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index 68b3663e..ad5979b6 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -6,7 +6,6 @@ import ( qmiq "github.com/iniwex5/quectel-qmi-go/pkg/qmi" "github.com/yibaiba/hideck/internal/config" - "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -222,7 +221,7 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" { idx.atIdentityByPort[worker.ResolvedATPort()] = workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI} } - if includeRuntimeStatus && (worker.Modem == nil || worker.Modem.ATProfile() != modem.ATProfileML307C) { + if includeRuntimeStatus && !atIdentityRulesFor(worker.atProfile()).verifyLiveIMEI { status := worker.GetDeviceStatus() if imei := strings.TrimSpace(status.IMEI); imei != "" { info.IMEI = imei @@ -272,24 +271,44 @@ func (idx WorkerDiscoveryIndex) Lookup(controlPath, usbPath, iface string) (Work return WorkerDiscoveryInfo{}, false } -// ReadOwnedATIdentity queries the manager already holding a candidate port. -// A failed query still counts as owned until the old worker is retired. -func (idx WorkerDiscoveryIndex) ReadOwnedATIdentity(dev CompatibleModem) (CompatibleModem, bool) { - if dev.ATProfile() != modem.ATProfileML307C { - return dev, false +// atScanObservation retains a static attachment even if its IMEI could not +// be verified. Only the separate verified modem result can establish identity. +type atScanObservation struct { + usbPath string + atPorts []string + unreadableOwner *Worker +} + +// ResolveLiveATIdentity handles hardware that requires a live AT IMEI. +// The caller retains its cache and transport fallback for other hardware. +func (idx WorkerDiscoveryIndex) ResolveLiveATIdentity(dev CompatibleModem, probe func(CompatibleModem) (CompatibleModem, string)) (CompatibleModem, bool) { + resolved, observation := idx.observeLiveATIdentity(dev, probe) + return resolved, observation != nil +} + +func (idx WorkerDiscoveryIndex) observeLiveATIdentity(dev CompatibleModem, probe func(CompatibleModem) (CompatibleModem, string)) (CompatibleModem, *atScanObservation) { + if !atIdentityRulesFor(dev.ATProfile()).verifyLiveIMEI { + return dev, nil } + observation := &atScanObservation{usbPath: dev.USBPath, atPorts: dev.ATPorts} for _, port := range dev.ATPorts { - query := idx.atIdentityByPort[port].query - if query == nil { + owner := idx.atIdentityByPort[port] + if owner.query == nil { continue } dev.ATPort, dev.IMEI = port, "" - if imei, err := query(); err == nil { + if imei, err := owner.query(); err == nil { dev.IMEI = imei } - return dev, true + if config.NormalizeIMEI(dev.IMEI) == "" { + // Do not open a second reader while the worker owns the port. + observation.unreadableOwner = owner.worker + } + return dev, observation } - return dev, false + resolved, imei := probe(dev) + resolved.IMEI = imei + return resolved, observation } type ConfiguredDeviceIndex struct { diff --git a/internal/device/ml307c_discovery_test.go b/internal/device/ml307c_discovery_test.go index 82b90ba5..8028958a 100644 --- a/internal/device/ml307c_discovery_test.go +++ b/internal/device/ml307c_discovery_test.go @@ -40,7 +40,11 @@ func TestML307CDiscoveryAndRebind(t *testing.T) { owned := WorkerDiscoveryIndex{atIdentityByPort: map[string]workerATIdentityReader{ "/dev/ttyUSB8": {query: func() (string, error) { return imei, nil }}, }} - active, ok := owned.ReadOwnedATIdentity(dev) + unexpectedProbe := func(raw CompatibleModem) (CompatibleModem, string) { + t.Fatal("unexpected independent AT probe") + return raw, "" + } + active, ok := owned.ResolveLiveATIdentity(dev, unexpectedProbe) if !ok || active.IMEI != imei { t.Fatalf("owned IMEI = %q, %v", active.IMEI, ok) } @@ -48,10 +52,20 @@ func TestML307CDiscoveryAndRebind(t *testing.T) { query: func() (string, error) { return "", errors.New("old tty closed") }, } dev.IMEI = imei - active, ok = owned.ReadOwnedATIdentity(dev) + active, ok = owned.ResolveLiveATIdentity(dev, unexpectedProbe) if !ok || active.IMEI != "" { t.Fatalf("stale owned tty = %q, %v", active.IMEI, ok) } + ordinary := dev + ordinary.VendorID, ordinary.ProductID = 0, 0 + if _, handled := owned.ResolveLiveATIdentity(ordinary, unexpectedProbe); handled { + t.Fatal("ordinary AT must retain the caller's existing fallback") + } + if active, handled := (WorkerDiscoveryIndex{}).ResolveLiveATIdentity(dev, func(raw CompatibleModem) (CompatibleModem, string) { + return raw, "" + }); !handled || active.IMEI != "" { + t.Fatalf("unowned failed read retained a cached IMEI: %q, %v", active.IMEI, handled) + } origProbe := probeProfileIMEICachedFn t.Cleanup(func() { probeProfileIMEICachedFn = origProbe }) diff --git a/internal/device/pool.go b/internal/device/pool.go index ded97662..8ed9803a 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -680,7 +680,8 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI defer cancel() } - if w.isML307C() { + strictSIMIdentity := atIdentityRulesFor(w.atProfile()).strictSIMIdentity + if strictSIMIdentity { inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { if errors.Is(err, modem.ErrSIMPINRequired) && (w.Pool == nil || !w.Pool.IsESIMSwitching(w.ID)) { @@ -739,7 +740,7 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI } } } - if w.isML307C() && (iccid == "" || imsi == "") { + if strictSIMIdentity && (iccid == "" || imsi == "") { return liveSIMIdentityRefreshResult{}, errors.New("live_identity_incomplete") } _, snapshotSupported := w.Backend.(liveSIMIdentitySnapshotReader) @@ -762,7 +763,7 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI } } imei := "" - if (iccid == "" || imsi == "") && !w.isML307C() { + if (iccid == "" || imsi == "") && !strictSIMIdentity { if ident, atErr := probeWorkerATIdentity(ctx, w); atErr == nil { if iccid == "" { iccid = strings.TrimSpace(ident.ICCID) @@ -1040,7 +1041,7 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s return } state = strings.ToUpper(strings.TrimSpace(state)) - if owner.worker.isML307C() { + if atIdentityRulesFor(owner.worker.atProfile()).strictSIMIdentity { if modem.IsSIMPINRequiredState(state) { p.handleSIMPINRequired(owner) return @@ -1221,7 +1222,7 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { transition.Unlock() - if w.isML307C() && errors.Is(err, modem.ErrSIMPINRequired) { + if atIdentityRulesFor(w.atProfile()).strictSIMIdentity && errors.Is(err, modem.ErrSIMPINRequired) { p.handleSIMPINRequired(owner) return } @@ -1273,7 +1274,7 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st } p.broadcastVoWiFiStateChange(w.ID) if result.err != nil { - if w.isML307C() && errors.Is(result.err, modem.ErrSIMPINRequired) { + if atIdentityRulesFor(w.atProfile()).strictSIMIdentity && errors.Is(result.err, modem.ErrSIMPINRequired) { p.handleSIMPINRequired(owner) return } @@ -1951,12 +1952,7 @@ func (p *Pool) RescanAndReconnect() error { return p.rescanAndReconnect(rescanReconnectOptions{}) } -type ml307cScanCandidate struct { - CompatibleModem - unreadableOwner *Worker -} - -func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scan compatibleATDiscoveryScope) (hardware []CompatibleModem, ml307cCandidates []ml307cScanCandidate) { +func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scan compatibleATDiscoveryScope) (hardware []CompatibleModem, atObservations []atScanObservation) { for i := range discovered { raw := discovered[i] // Paths are attachment hints, never proof that the old worker still @@ -1990,25 +1986,21 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor seen[k] = true } } + probe := func(dev CompatibleModem) (CompatibleModem, string) { + return resolveDiscoveredCompatibleModemFn(dev, 1200*time.Millisecond) + } for _, raw := range compatList { - isML307C := raw.ATProfile() == modem.ATProfileML307C - if scan == compatibleATDiscoveryML307C && !isML307C { + if scan == compatibleATDiscoveryLiveIdentity && !atIdentityRulesFor(raw.ATProfile()).verifyLiveIMEI { continue } - m, owned := liveWorkerIndex.ReadOwnedATIdentity(raw) + m, observation := liveWorkerIndex.observeLiveATIdentity(raw, probe) imei := m.IMEI - if !owned { - m, imei = resolveDiscoveredCompatibleModemFn(raw, 1200*time.Millisecond) + if observation == nil { + m, imei = probe(raw) + } else { + atObservations = append(atObservations, *observation) } key := config.NormalizeIMEI(imei) - if isML307C { - // Bootstrap must recognize C ports even when IMEI is unreadable. - candidate := ml307cScanCandidate{CompatibleModem: raw} - if owned && key == "" { - candidate.unreadableOwner = liveWorkerIndex.atIdentityByPort[m.ATPort].worker - } - ml307cCandidates = append(ml307cCandidates, candidate) - } if key == "" { continue } @@ -2020,7 +2012,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor } } } - return hardware, ml307cCandidates + return hardware, atObservations } func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { @@ -2036,7 +2028,7 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) managed := p.managedDevices() modemDevices, pcscDevices := partitionManagedDevices(managed) - hardware, ml307cCandidates := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(modemDevices)) + hardware, atObservations := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(modemDevices)) resolved := ResolveDeviceIdentities(hardware, modemDevices) if len(resolved.Degraded) > 0 || len(resolved.Unmatched) > 0 { @@ -2047,7 +2039,7 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error { } for _, snapshot := range resolved.Offline { - p.reconcileOfflineRescanDevice(opts, snapshot, hardware, ml307cCandidates, managed) + p.reconcileOfflineRescanDevice(opts, snapshot, hardware, atObservations, managed) } return p.reconcilePCSCReaders(opts, managed, pcscDevices) @@ -2736,10 +2728,7 @@ func (p *Pool) PersistRuntimeState(worker *Worker) { } // 更新 Device 表 - model := "EC20" - if worker.isML307C() { - model = "ML307C" - } + model := atIdentityRulesFor(worker.atProfile()).model if err := db.UpsertDevice(imei, worker.ID, model, worker.Config.ATPort); err != nil { logger.Warn(fmt.Sprintf("[%s] 更新设备信息失败", worker.ID), "err", err) } diff --git a/internal/device/pool_at_identity.go b/internal/device/pool_at_identity.go index baad0615..80e01a6f 100644 --- a/internal/device/pool_at_identity.go +++ b/internal/device/pool_at_identity.go @@ -12,8 +12,31 @@ import ( var errATIdentityUnavailable = errors.New("at identity unavailable") var errATNoSIM = errors.New("AT modem has no SIM") +type atIdentityRules struct { + verifyLiveIMEI bool + strictSIMIdentity bool + simStatusSource string + model string +} + +func atIdentityRulesFor(profile modem.ATProfile) atIdentityRules { + switch profile { + case modem.ATProfileML307C: + return atIdentityRules{verifyLiveIMEI: true, strictSIMIdentity: true, simStatusSource: "ml307c_sim_status", model: "ML307C"} + default: + return atIdentityRules{model: "EC20"} + } +} + +func (w *Worker) atProfile() modem.ATProfile { + if w == nil || w.Modem == nil { + return modem.ATProfileDefault + } + return w.Modem.ATProfile() +} + func (w *Worker) isML307C() bool { - return w != nil && w.Modem != nil && w.Modem.ATProfile() == modem.ATProfileML307C + return w.atProfile() == modem.ATProfileML307C } var probeATIdentityFn = modem.ProbeATIdentity diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 69132ab4..95372bf3 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -132,7 +132,7 @@ type compatibleATDiscoveryScope uint8 const ( compatibleATDiscoveryNone compatibleATDiscoveryScope = iota - compatibleATDiscoveryML307C + compatibleATDiscoveryLiveIdentity compatibleATDiscoveryAll ) @@ -146,17 +146,20 @@ func configuredDevicesATDiscovery(devices []config.DeviceConfig) compatibleATDis return compatibleATDiscoveryAll } if resolvedBackendMode(dev) == backend.BackendAT { - // An enumerated tty is only an attachment hint for an ML307C. - // Other modems with explicit ports keep their existing probe behavior. - scope = compatibleATDiscoveryML307C + // Profiles that require live identity must verify even an + // explicitly configured tty. Other explicit ports do not expand discovery. + scope = compatibleATDiscoveryLiveIdentity } } return scope } -func configuredPortPointsToML307C(cfg config.DeviceConfig, candidates []ml307cScanCandidate) bool { - if usb := strings.TrimSpace(cfg.USBPath); usb != "" && readUSBDeviceIdentity(resolveUSBPathForScan(usb)).isML307C() { - return true +func configuredPortRequiresLiveATIdentity(cfg config.DeviceConfig, observations []atScanObservation) bool { + if usb := strings.TrimSpace(cfg.USBPath); usb != "" { + profile := readUSBDeviceIdentity(resolveUSBPathForScan(usb)).atProfile() + if atIdentityRulesFor(profile).verifyLiveIMEI { + return true + } } for _, port := range []string{cfg.ATPort, cfg.ManagePort} { port = strings.TrimSpace(port) @@ -166,8 +169,8 @@ func configuredPortPointsToML307C(cfg config.DeviceConfig, candidates []ml307cSc if target, err := filepath.EvalSymlinks(port); err == nil { port = target } - for _, hw := range candidates { - if containsPort(hw.ATPorts, port) { + for _, observation := range observations { + if containsPort(observation.atPorts, port) { return true } } @@ -313,13 +316,13 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) scan = compatibleATDiscoveryAll } atIMEIConfigured := resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "" - hardware, ml307cCandidates := p.collectRescanHardware(nil, liveWorkerIndex, scan) + hardware, atObservations := p.collectRescanHardware(nil, liveWorkerIndex, scan) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware atProfile = hw.ATProfile() - if atProfile == modem.ATProfileML307C { + if atIdentityRulesFor(atProfile).verifyLiveIMEI { devCfg.USBPath = hw.USBPath devCfg.ATPort = hw.ATPort devCfg.ManagePort = hw.ATPort @@ -343,7 +346,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI) } } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || - (atIMEIConfigured && configuredPortPointsToML307C(devCfg, ml307cCandidates)) { + (atIMEIConfigured && configuredPortRequiresLiveATIdentity(devCfg, atObservations)) { return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") } } else if hasManagedQMINetwork(devCfg) { @@ -618,9 +621,9 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) p.scheduleATDisconnectRecovery(owner, reason) }) p.bindModemReadyIndications(w) - if atProfile == modem.ATProfileML307C { + if source := atIdentityRulesFor(atProfile).simStatusSource; source != "" { m.SetSIMStatusHandler(func(inserted *bool, state string) { - p.handleSIMStatusEventForOwner(owner, "ml307c_sim_status", inserted, state) + p.handleSIMStatusEventForOwner(owner, source, inserted, state) }) } } diff --git a/internal/device/pool_rescan_guard.go b/internal/device/pool_rescan_guard.go index b1533a24..2981761b 100644 --- a/internal/device/pool_rescan_guard.go +++ b/internal/device/pool_rescan_guard.go @@ -6,7 +6,6 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" - "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/pkg/logger" ) @@ -88,7 +87,7 @@ func (p *Pool) reconcileHealthyRescanWorker( }) return } - usbChanged := hw.ATProfile() == modem.ATProfileML307C && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath + usbChanged := atIdentityRulesFor(hw.ATProfile()).verifyLiveIMEI && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath portChanged := hw.ATPort != "" && hw.ATPort != worker.Config.ATPort if (!usbChanged && !portChanged) || !opts.allowWorkerMutation(pair.Config.ID) { return @@ -212,7 +211,7 @@ func (p *Pool) reconcileOfflineRescanDevice( opts rescanReconnectOptions, snapshot config.DeviceConfig, hardware []CompatibleModem, - ml307cCandidates []ml307cScanCandidate, + atObservations []atScanObservation, fallback []config.DeviceConfig, ) { releaseMutation := p.AcquireManagedDeviceMutation(snapshot.ID) @@ -231,12 +230,12 @@ func (p *Pool) reconcileOfflineRescanDevice( return } healthy := worker.IsDeviceHealthy() - if healthy && worker.isML307C() && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) { + if healthy && atIdentityRulesFor(worker.atProfile()).verifyLiveIMEI && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) { usb := strings.TrimSpace(worker.Config.USBPath) port := worker.ResolvedATPort() - for _, candidate := range ml307cCandidates { - if candidate.unreadableOwner == worker && usb != "" && candidate.USBPath == usb && - containsPort(candidate.ATPorts, port) { + for _, candidate := range atObservations { + if candidate.unreadableOwner == worker && usb != "" && candidate.usbPath == usb && + containsPort(candidate.atPorts, port) { // Keep the existing owner until the next scan can verify its IMEI. return } diff --git a/internal/device/sms_identity.go b/internal/device/sms_identity.go index 4c6e821e..9a349e32 100644 --- a/internal/device/sms_identity.go +++ b/internal/device/sms_identity.go @@ -108,7 +108,7 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error) } worker.cacheMu.RLock() defer worker.cacheMu.RUnlock() - if worker.isML307C() && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) { + if atIdentityRulesFor(worker.atProfile()).strictSIMIdentity && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) { return smsIdentityCandidate{}, ErrSMSIdentityUnknown } phase := worker.state.Identity.Phase From c0c734a9e15bc4bc685a709a3a5ce50a14f8f2ac Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 19:37:41 +0800 Subject: [PATCH 18/39] fix(device): keep SIM prewarm tied to its worker --- internal/device/pool.go | 5 +---- internal/device/pool_health_ip.go | 3 ++- internal/device/sim_removal_test.go | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/internal/device/pool.go b/internal/device/pool.go index 8ed9803a..0a2f2e6d 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -1192,14 +1192,11 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri return } deviceID := owner.worker.ID - if !p.consumeSIMEventTimer(deviceID, expected) { - return - } releaseMutation := p.AcquireManagedDeviceMutation(deviceID) defer releaseMutation() transition := p.policyTransitionFor(deviceID) transition.Lock() - if !p.workerLifecycleOwnerCurrent(owner) { + if !p.workerLifecycleOwnerCurrent(owner) || !p.consumeSIMEventTimer(deviceID, expected) { transition.Unlock() return } diff --git a/internal/device/pool_health_ip.go b/internal/device/pool_health_ip.go index d57150f1..033c4d3e 100644 --- a/internal/device/pool_health_ip.go +++ b/internal/device/pool_health_ip.go @@ -514,7 +514,8 @@ func (w *Worker) PreWarmCache() { identityErr := w.RefreshIdentityLive(nil, "prewarm") if w.Pool != nil { if errors.Is(identityErr, errATNoSIM) { - w.Pool.confirmSIMRemovedForOwner(w.Pool.captureWorkerLifecycleOwner(w.ID), "ml307c_startup", nil) + owner := workerLifecycleOwner{worker: w, generation: w.generation} + w.Pool.confirmSIMRemovedForOwner(owner, "at_startup", nil) } w.Pool.PersistRuntimeState(w) w.Pool.PersistIdentityState(w) diff --git a/internal/device/sim_removal_test.go b/internal/device/sim_removal_test.go index 5fd1d247..062582b2 100644 --- a/internal/device/sim_removal_test.go +++ b/internal/device/sim_removal_test.go @@ -3,6 +3,7 @@ package device import ( "context" "testing" + "time" "github.com/iniwex5/vowifi-go/runtimehost" "github.com/yibaiba/hideck/internal/cardpolicy" @@ -44,6 +45,29 @@ func TestPhysicalSIMInsertEventRefreshesIdentity(t *testing.T) { } } +func TestStaleSIMConfirmationKeepsCurrentWorkerTimer(t *testing.T) { + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + w := &Worker{ID: "dev", Pool: p} + p.AttachWorkerForTest(w) + + timer := time.NewTimer(time.Hour) + t.Cleanup(func() { timer.Stop() }) + p.simEventMu.Lock() + p.simEventTimers = map[string]*time.Timer{w.ID: timer} + p.simEventMu.Unlock() + + old := &Worker{ID: w.ID, Pool: p} + p.confirmSIMRemovedForOwner(workerLifecycleOwner{worker: old}, "at_startup", nil) + + p.simEventMu.Lock() + current := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if current != timer { + t.Fatal("stale worker consumed the current worker's SIM status timer") + } +} + func TestConfirmedSIMRemovalClearsIdentityAndDatabaseBinding(t *testing.T) { initDevicePhoneNumberTestDB(t) p := NewPool(&config.Config{}) From 289106b9a4ece99fa265fccb3cf9b63059582b38 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 19:37:41 +0800 Subject: [PATCH 19/39] refactor(device): centralize AT device and stored inbox rules --- internal/device/at_device_rules.go | 43 +++++++++ internal/device/at_port_resolver.go | 4 +- internal/device/discovery_compat.go | 6 +- internal/device/discovery_enrichment.go | 4 +- internal/device/pool.go | 14 +-- internal/device/pool_at_identity.go | 27 ------ internal/device/pool_bootstrap.go | 6 +- internal/device/pool_rescan_guard.go | 4 +- .../device/{sms_ml307c.go => sms_at_inbox.go} | 88 +++++++++---------- ...ms_ml307c_test.go => sms_at_inbox_test.go} | 38 ++++---- internal/device/sms_identity.go | 2 +- internal/device/sms_mode_at.go | 4 +- internal/device/usb_at_port_rules.go | 32 +++++-- 13 files changed, 153 insertions(+), 119 deletions(-) create mode 100644 internal/device/at_device_rules.go rename internal/device/{sms_ml307c.go => sms_at_inbox.go} (88%) rename internal/device/{sms_ml307c_test.go => sms_at_inbox_test.go} (89%) diff --git a/internal/device/at_device_rules.go b/internal/device/at_device_rules.go new file mode 100644 index 00000000..34418632 --- /dev/null +++ b/internal/device/at_device_rules.go @@ -0,0 +1,43 @@ +package device + +import "github.com/yibaiba/hideck/internal/modem" + +type atDeviceRules struct { + verifyLiveIMEI bool + strictSIMIdentity bool + simStatusSource string + model string + storedSMSInbox bool + nativeVoiceUnavailableReason string +} + +func atDeviceRulesFor(profile modem.ATProfile) atDeviceRules { + switch profile { + case modem.ATProfileML307C: + return atDeviceRules{ + verifyLiveIMEI: true, + strictSIMIdentity: true, + simStatusSource: "ml307c_sim_status", + model: "ML307C", + storedSMSInbox: true, + nativeVoiceUnavailableReason: "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨", + } + default: + return atDeviceRules{model: "EC20"} + } +} + +func (w *Worker) atDeviceRules() atDeviceRules { + return atDeviceRulesFor(w.atProfile()) +} + +func (w *Worker) atProfile() modem.ATProfile { + if w == nil || w.Modem == nil { + return modem.ATProfileDefault + } + return w.Modem.ATProfile() +} + +func (w *Worker) isML307C() bool { + return w.atProfile() == modem.ATProfileML307C +} diff --git a/internal/device/at_port_resolver.go b/internal/device/at_port_resolver.go index a1b5076b..f2fc92a7 100644 --- a/internal/device/at_port_resolver.go +++ b/internal/device/at_port_resolver.go @@ -95,7 +95,7 @@ func ResolveQMIDeviceATPort(dev QMIDevice, timeout time.Duration) (QMIDevice, st // ResolveCompatibleModemATPort 为兼容发现结果解析真实可用的主 AT 口。 // 行为与 QMI 设备一致,同样只允许在该设备自己的 ATPorts 范围内探测。 func ResolveCompatibleModemATPort(dev CompatibleModem, timeout time.Duration) (CompatibleModem, string) { - if atIdentityRulesFor(dev.ATProfile()).verifyLiveIMEI { + if atDeviceRulesFor(dev.ATProfile()).verifyLiveIMEI { return ResolveCompatibleModemATPortContext(context.Background(), dev, timeout) } atPort, imei := ResolveATPortForDevice(dev.ATPort, dev.ATPorts, timeout) @@ -113,7 +113,7 @@ func ResolveCompatibleModemATPortContext( timeout time.Duration, ) (CompatibleModem, string) { profile := dev.ATProfile() - if atIdentityRulesFor(profile).verifyLiveIMEI { + if atDeviceRulesFor(profile).verifyLiveIMEI { preferred := dev.ATPort dev.ATPort, dev.IMEI = "", "" for _, port := range orderedATPortCandidates(preferred, dev.ATPorts) { diff --git a/internal/device/discovery_compat.go b/internal/device/discovery_compat.go index ef0f1bd0..3198c870 100644 --- a/internal/device/discovery_compat.go +++ b/internal/device/discovery_compat.go @@ -37,8 +37,8 @@ func (m CompatibleModem) ATProfile() modem.ATProfile { } func (id usbDeviceIdentity) atProfile() modem.ATProfile { - if id.isML307C() { - return modem.ATProfileML307C + if layout, ok := id.atOnlyLayout(); ok { + return layout.profile } return modem.ATProfileDefault } @@ -158,7 +158,7 @@ func discoverFallbackOne(usbPath string) (CompatibleModem, bool) { scanUSBPath := resolveUSBPathForScan(usbPath) identity := readUSBDeviceIdentity(scanUSBPath) vid, pid := identity.vendorID, identity.productID - if identity.isML307C() { + if _, ok := identity.atOnlyLayout(); ok { ports, port, _ := discoverATPortsForUSBDevice(scanUSBPath, identity, "at") if port == "" { return CompatibleModem{}, false diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index ad5979b6..35497947 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -221,7 +221,7 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" { idx.atIdentityByPort[worker.ResolvedATPort()] = workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI} } - if includeRuntimeStatus && !atIdentityRulesFor(worker.atProfile()).verifyLiveIMEI { + if includeRuntimeStatus && !worker.atDeviceRules().verifyLiveIMEI { status := worker.GetDeviceStatus() if imei := strings.TrimSpace(status.IMEI); imei != "" { info.IMEI = imei @@ -287,7 +287,7 @@ func (idx WorkerDiscoveryIndex) ResolveLiveATIdentity(dev CompatibleModem, probe } func (idx WorkerDiscoveryIndex) observeLiveATIdentity(dev CompatibleModem, probe func(CompatibleModem) (CompatibleModem, string)) (CompatibleModem, *atScanObservation) { - if !atIdentityRulesFor(dev.ATProfile()).verifyLiveIMEI { + if !atDeviceRulesFor(dev.ATProfile()).verifyLiveIMEI { return dev, nil } observation := &atScanObservation{usbPath: dev.USBPath, atPorts: dev.ATPorts} diff --git a/internal/device/pool.go b/internal/device/pool.go index 0a2f2e6d..e26d1c6b 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -157,7 +157,7 @@ type Worker struct { operatorScanActive bool reassembler *smscodec.Reassembler - ml307cSMSNotices ml307cSMSNotices + storedSMSNotices storedSMSNotices // 短信工作模式:AT / QMI / VoWiFi(三模完全隔离)。MBIM 网络使用 AT 短信模式。 smsMode smsMode @@ -680,7 +680,7 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI defer cancel() } - strictSIMIdentity := atIdentityRulesFor(w.atProfile()).strictSIMIdentity + strictSIMIdentity := w.atDeviceRules().strictSIMIdentity if strictSIMIdentity { inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { @@ -1041,7 +1041,7 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s return } state = strings.ToUpper(strings.TrimSpace(state)) - if atIdentityRulesFor(owner.worker.atProfile()).strictSIMIdentity { + if owner.worker.atDeviceRules().strictSIMIdentity { if modem.IsSIMPINRequiredState(state) { p.handleSIMPINRequired(owner) return @@ -1219,7 +1219,7 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { transition.Unlock() - if atIdentityRulesFor(w.atProfile()).strictSIMIdentity && errors.Is(err, modem.ErrSIMPINRequired) { + if w.atDeviceRules().strictSIMIdentity && errors.Is(err, modem.ErrSIMPINRequired) { p.handleSIMPINRequired(owner) return } @@ -1271,7 +1271,7 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st } p.broadcastVoWiFiStateChange(w.ID) if result.err != nil { - if atIdentityRulesFor(w.atProfile()).strictSIMIdentity && errors.Is(result.err, modem.ErrSIMPINRequired) { + if w.atDeviceRules().strictSIMIdentity && errors.Is(result.err, modem.ErrSIMPINRequired) { p.handleSIMPINRequired(owner) return } @@ -1987,7 +1987,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor return resolveDiscoveredCompatibleModemFn(dev, 1200*time.Millisecond) } for _, raw := range compatList { - if scan == compatibleATDiscoveryLiveIdentity && !atIdentityRulesFor(raw.ATProfile()).verifyLiveIMEI { + if scan == compatibleATDiscoveryLiveIdentity && !atDeviceRulesFor(raw.ATProfile()).verifyLiveIMEI { continue } m, observation := liveWorkerIndex.observeLiveATIdentity(raw, probe) @@ -2725,7 +2725,7 @@ func (p *Pool) PersistRuntimeState(worker *Worker) { } // 更新 Device 表 - model := atIdentityRulesFor(worker.atProfile()).model + model := worker.atDeviceRules().model if err := db.UpsertDevice(imei, worker.ID, model, worker.Config.ATPort); err != nil { logger.Warn(fmt.Sprintf("[%s] 更新设备信息失败", worker.ID), "err", err) } diff --git a/internal/device/pool_at_identity.go b/internal/device/pool_at_identity.go index 80e01a6f..ca2f2180 100644 --- a/internal/device/pool_at_identity.go +++ b/internal/device/pool_at_identity.go @@ -12,33 +12,6 @@ import ( var errATIdentityUnavailable = errors.New("at identity unavailable") var errATNoSIM = errors.New("AT modem has no SIM") -type atIdentityRules struct { - verifyLiveIMEI bool - strictSIMIdentity bool - simStatusSource string - model string -} - -func atIdentityRulesFor(profile modem.ATProfile) atIdentityRules { - switch profile { - case modem.ATProfileML307C: - return atIdentityRules{verifyLiveIMEI: true, strictSIMIdentity: true, simStatusSource: "ml307c_sim_status", model: "ML307C"} - default: - return atIdentityRules{model: "EC20"} - } -} - -func (w *Worker) atProfile() modem.ATProfile { - if w == nil || w.Modem == nil { - return modem.ATProfileDefault - } - return w.Modem.ATProfile() -} - -func (w *Worker) isML307C() bool { - return w.atProfile() == modem.ATProfileML307C -} - var probeATIdentityFn = modem.ProbeATIdentity func probeWorkerATIdentity(ctx context.Context, w *Worker) (modem.ATIdentity, error) { diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 95372bf3..86e07d2c 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -157,7 +157,7 @@ func configuredDevicesATDiscovery(devices []config.DeviceConfig) compatibleATDis func configuredPortRequiresLiveATIdentity(cfg config.DeviceConfig, observations []atScanObservation) bool { if usb := strings.TrimSpace(cfg.USBPath); usb != "" { profile := readUSBDeviceIdentity(resolveUSBPathForScan(usb)).atProfile() - if atIdentityRulesFor(profile).verifyLiveIMEI { + if atDeviceRulesFor(profile).verifyLiveIMEI { return true } } @@ -322,7 +322,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware atProfile = hw.ATProfile() - if atIdentityRulesFor(atProfile).verifyLiveIMEI { + if atDeviceRulesFor(atProfile).verifyLiveIMEI { devCfg.USBPath = hw.USBPath devCfg.ATPort = hw.ATPort devCfg.ManagePort = hw.ATPort @@ -621,7 +621,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) p.scheduleATDisconnectRecovery(owner, reason) }) p.bindModemReadyIndications(w) - if source := atIdentityRulesFor(atProfile).simStatusSource; source != "" { + if source := atDeviceRulesFor(atProfile).simStatusSource; source != "" { m.SetSIMStatusHandler(func(inserted *bool, state string) { p.handleSIMStatusEventForOwner(owner, source, inserted, state) }) diff --git a/internal/device/pool_rescan_guard.go b/internal/device/pool_rescan_guard.go index 2981761b..8a0d3cc9 100644 --- a/internal/device/pool_rescan_guard.go +++ b/internal/device/pool_rescan_guard.go @@ -87,7 +87,7 @@ func (p *Pool) reconcileHealthyRescanWorker( }) return } - usbChanged := atIdentityRulesFor(hw.ATProfile()).verifyLiveIMEI && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath + usbChanged := atDeviceRulesFor(hw.ATProfile()).verifyLiveIMEI && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath portChanged := hw.ATPort != "" && hw.ATPort != worker.Config.ATPort if (!usbChanged && !portChanged) || !opts.allowWorkerMutation(pair.Config.ID) { return @@ -230,7 +230,7 @@ func (p *Pool) reconcileOfflineRescanDevice( return } healthy := worker.IsDeviceHealthy() - if healthy && atIdentityRulesFor(worker.atProfile()).verifyLiveIMEI && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) { + if healthy && worker.atDeviceRules().verifyLiveIMEI && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) { usb := strings.TrimSpace(worker.Config.USBPath) port := worker.ResolvedATPort() for _, candidate := range atObservations { diff --git a/internal/device/sms_ml307c.go b/internal/device/sms_at_inbox.go similarity index 88% rename from internal/device/sms_ml307c.go rename to internal/device/sms_at_inbox.go index 6ccf80fe..c725dbdf 100644 --- a/internal/device/sms_ml307c.go +++ b/internal/device/sms_at_inbox.go @@ -19,42 +19,42 @@ import ( "github.com/yibaiba/hideck/pkg/smscodec" ) -var ml307cSMSStores = [...]string{"ME", "SM"} +var storedSMSStores = [...]string{"ME", "SM"} -type ml307cSMSOwner struct { +type storedSMSOwner struct { workerLifecycleOwner SMSIdentity simGeneration uint64 } -func (w *Worker) ml307cSMSOwner() (ml307cSMSOwner, error) { +func (w *Worker) storedSMSOwner() (storedSMSOwner, error) { w.cacheMu.RLock() id := w.state.Identity w.cacheMu.RUnlock() identity := normalizeSMSIdentity(SMSIdentity{ICCID: id.ICCID, IMSI: id.IMSI}) if !id.Ready || id.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" { - return ml307cSMSOwner{}, ErrSMSIdentityUnknown + return storedSMSOwner{}, ErrSMSIdentityUnknown } - return ml307cSMSOwner{ + return storedSMSOwner{ workerLifecycleOwner: workerLifecycleOwner{worker: w, generation: w.generation}, SMSIdentity: identity, simGeneration: id.Generation, }, nil } -func (owner ml307cSMSOwner) check() error { +func (owner storedSMSOwner) check() error { w := owner.worker if !w.Pool.workerLifecycleOwnerCurrent(owner.workerLifecycleOwner) || w.Pool.IsESIMSwitching(w.ID) || !w.Modem.StoredSMSReceiving() { return ErrSMSIdentityTransitioning } - current, err := w.ml307cSMSOwner() + current, err := w.storedSMSOwner() if err != nil || current != owner { return ErrSMSIdentityTransitioning } return nil } -func (owner ml307cSMSOwner) verifyLive() error { +func (owner storedSMSOwner) verifyLive() error { if err := owner.check(); err != nil { return err } @@ -81,36 +81,36 @@ func (owner ml307cSMSOwner) verifyLive() error { } // A CMTI only proves provenance within the current worker and SIM generation. -type ml307cSMSSlot struct { +type storedSMSSlot struct { store string index int } -type ml307cSMSNotice struct { - owner ml307cSMSOwner - slot ml307cSMSSlot +type storedSMSNotice struct { + owner storedSMSOwner + slot storedSMSSlot observedAt time.Time pdu string // Set under the notice lock after the first successful read. } -type ml307cSMSNotices struct { +type storedSMSNotices struct { mu sync.Mutex - slots map[ml307cSMSSlot]*ml307cSMSNotice + slots map[storedSMSSlot]*storedSMSNotice } -func (notices *ml307cSMSNotices) add(notice *ml307cSMSNotice) { +func (notices *storedSMSNotices) add(notice *storedSMSNotice) { notices.mu.Lock() defer notices.mu.Unlock() if notices.slots == nil { - notices.slots = make(map[ml307cSMSSlot]*ml307cSMSNotice) + notices.slots = make(map[storedSMSSlot]*storedSMSNotice) } notices.slots[notice.slot] = notice } -func (notices *ml307cSMSNotices) snapshot(owner ml307cSMSOwner, store string) map[int]*ml307cSMSNotice { +func (notices *storedSMSNotices) snapshot(owner storedSMSOwner, store string) map[int]*storedSMSNotice { notices.mu.Lock() defer notices.mu.Unlock() - var pending map[int]*ml307cSMSNotice + var pending map[int]*storedSMSNotice for slot, notice := range notices.slots { if notice.owner != owner { if notice.owner.workerLifecycleOwner == owner.workerLifecycleOwner && notice.owner.simGeneration < owner.simGeneration { @@ -118,7 +118,7 @@ func (notices *ml307cSMSNotices) snapshot(owner ml307cSMSOwner, store string) ma } } else if slot.store == store { if pending == nil { - pending = make(map[int]*ml307cSMSNotice) + pending = make(map[int]*storedSMSNotice) } pending[slot.index] = notice } @@ -126,13 +126,13 @@ func (notices *ml307cSMSNotices) snapshot(owner ml307cSMSOwner, store string) ma return pending } -func (notices *ml307cSMSNotices) current(notice *ml307cSMSNotice) bool { +func (notices *storedSMSNotices) current(notice *storedSMSNotice) bool { notices.mu.Lock() defer notices.mu.Unlock() return notices.slots[notice.slot] == notice } -func (notices *ml307cSMSNotices) bind(notice *ml307cSMSNotice, pdu string) bool { +func (notices *storedSMSNotices) bind(notice *storedSMSNotice, pdu string) bool { notices.mu.Lock() defer notices.mu.Unlock() if notice == nil || notices.slots[notice.slot] != notice { @@ -148,7 +148,7 @@ func (notices *ml307cSMSNotices) bind(notice *ml307cSMSNotice, pdu string) bool return true } -func (notices *ml307cSMSNotices) forget(notice *ml307cSMSNotice) { +func (notices *storedSMSNotices) forget(notice *storedSMSNotice) { if notice == nil { return } @@ -159,22 +159,22 @@ func (notices *ml307cSMSNotices) forget(notice *ml307cSMSNotice) { } } -func (w *Worker) handleML307CStoredSMS(storage, index string) { +func (w *Worker) handleStoredSMS(storage, index string) { slot, err := strconv.Atoi(index) if err != nil || slot < 0 || slot > 65535 || (storage != "ME" && storage != "SM") { return } // Capture before queuing the work. A delayed URC must keep its original // worker and SIM generation across eSIM and physical card changes. - owner, err := w.ml307cSMSOwner() + owner, err := w.storedSMSOwner() if err != nil { return } - notice := &ml307cSMSNotice{ - owner: owner, slot: ml307cSMSSlot{store: storage, index: slot}, observedAt: time.Now(), + notice := &storedSMSNotice{ + owner: owner, slot: storedSMSSlot{store: storage, index: slot}, observedAt: time.Now(), } - w.ml307cSMSNotices.add(notice) - go w.runML307CSMS(owner, notice) + w.storedSMSNotices.add(notice) + go w.receiveStoredSMS(owner, notice) } // scanATSMS polls the stored inbox when the active AT SMS path enables it. @@ -182,17 +182,17 @@ func (w *Worker) scanATSMS() { if w.Modem == nil || !w.Modem.StoredSMSReceiving() { return } - owner, err := w.ml307cSMSOwner() + owner, err := w.storedSMSOwner() if err != nil { return } - w.runML307CSMS(owner, nil) + w.receiveStoredSMS(owner, nil) } -func (w *Worker) runML307CSMS(owner ml307cSMSOwner, notice *ml307cSMSNotice) { +func (w *Worker) receiveStoredSMS(owner storedSMSOwner, notice *storedSMSNotice) { var notifications []InboundSMS - if err := w.readML307CSMSInbox(owner, notice, ¬ifications); err != nil { - logger.Warn("ML307C 短信收件未完成", "device", w.ID, "err", err) + if err := w.readStoredSMSInbox(owner, notice, ¬ifications); err != nil { + logger.Warn("AT 短信收件未完成", "device", w.ID, "err", err) } for _, inbound := range notifications { w.Pool.notifyInboundSMS(inbound) @@ -202,7 +202,7 @@ func (w *Worker) runML307CSMS(owner ml307cSMSOwner, notice *ml307cSMSNotice) { } } -func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotice, notifications *[]InboundSMS) error { +func (w *Worker) readStoredSMSInbox(owner storedSMSOwner, notice *storedSMSNotice, notifications *[]InboundSMS) error { // The eSIM manager uses the same transition lock. Take it before the // serial inbox lock, matching the lock order used for sending. release, err := w.Pool.AcquireDeviceOperation(w.ID) @@ -230,7 +230,7 @@ func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotic return err } if notice != nil { - if !w.ml307cSMSNotices.current(notice) { + if !w.storedSMSNotices.current(notice) { return nil } if err := inbox.Select(notice.slot.store); err != nil { @@ -243,18 +243,18 @@ func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotic if err := owner.verifyLive(); err != nil { return err } - return w.ingestML307CSlot(inbox, owner, state, record, notice.slot.store == "SM", notice, notifications) + return w.ingestStoredSMSSlot(inbox, owner, state, record, notice.slot.store == "SM", notice, notifications) } var scanErr error scanIncomplete := false - for _, store := range ml307cSMSStores { + for _, store := range storedSMSStores { if err := inbox.Select(store); err != nil { return errors.Join(scanErr, err) } // Only notices already observed before this snapshot can identify // a listed PDU. A newer CMTI may refer to a reused slot. - pending := w.ml307cSMSNotices.snapshot(owner, store) + pending := w.storedSMSNotices.snapshot(owner, store) records, err := inbox.List() if err != nil { scanErr = errors.Join(scanErr, err) @@ -267,12 +267,12 @@ func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotic for _, record := range records { notice := pending[record.Index] delete(pending, record.Index) - if err := w.ingestML307CSlot(inbox, owner, state, record, store == "SM", notice, notifications); err != nil { + if err := w.ingestStoredSMSSlot(inbox, owner, state, record, store == "SM", notice, notifications); err != nil { scanErr = errors.Join(scanErr, err) } } for _, absent := range pending { - w.ml307cSMSNotices.forget(absent) + w.storedSMSNotices.forget(absent) } } if scanIncomplete { @@ -290,15 +290,15 @@ func (w *Worker) readML307CSMSInbox(owner ml307cSMSOwner, notice *ml307cSMSNotic }) } -func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notice *ml307cSMSNotice, notifications *[]InboundSMS) error { +func (w *Worker) ingestStoredSMSSlot(inbox *modem.SMSInbox, owner storedSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notice *storedSMSNotice, notifications *[]InboundSMS) error { if !record.Received() { - w.ml307cSMSNotices.forget(notice) + w.storedSMSNotices.forget(notice) return nil } if err := owner.check(); err != nil { return err } - if notice != nil && !w.ml307cSMSNotices.bind(notice, record.PDU) { + if notice != nil && !w.storedSMSNotices.bind(notice, record.PDU) { return nil } part, err := decodeATInboxPart(owner.SMSIdentity, record.PDU) @@ -322,7 +322,7 @@ func (w *Worker) ingestML307CSlot(inbox *modem.SMSInbox, owner ml307cSMSOwner, s if err := inbox.DeleteMatching(record, owner.verifyLive); err != nil { return fmt.Errorf("delete persisted SMS slot %d: %w", record.Index, err) } - w.ml307cSMSNotices.forget(notice) + w.storedSMSNotices.forget(notice) return nil } diff --git a/internal/device/sms_ml307c_test.go b/internal/device/sms_at_inbox_test.go similarity index 89% rename from internal/device/sms_ml307c_test.go rename to internal/device/sms_at_inbox_test.go index bde56195..17c7dfd7 100644 --- a/internal/device/sms_ml307c_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -8,7 +8,7 @@ import ( "github.com/yibaiba/hideck/internal/db" ) -func TestML307CStoredSMSPersistence(t *testing.T) { +func TestATStoredSMSPersistence(t *testing.T) { initDevicePhoneNumberTestDB(t) identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} @@ -212,39 +212,39 @@ func TestML307CStoredSMSPersistence(t *testing.T) { } } -func TestML307CStoredSMSNoticeSurvivesReadFailure(t *testing.T) { +func TestATStoredSMSNoticeSurvivesReadFailure(t *testing.T) { w := &Worker{} - slot := ml307cSMSSlot{store: "ME", index: 7} + slot := storedSMSSlot{store: "ME", index: 7} // With identity still unknown, a notification cannot attest a later card. - w.handleML307CStoredSMS(slot.store, "7") - if len(w.ml307cSMSNotices.slots) != 0 { + w.handleStoredSMS(slot.store, "7") + if len(w.storedSMSNotices.slots) != 0 { t.Fatal("unknown SIM claimed an ME slot") } - owner := ml307cSMSOwner{simGeneration: 1} - notice := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} - w.ml307cSMSNotices.add(notice) // An unsuccessful CMGR leaves the notification unresolved. + owner := storedSMSOwner{simGeneration: 1} + notice := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.storedSMSNotices.add(notice) // An unsuccessful CMGR leaves the notification unresolved. - retry := w.ml307cSMSNotices.snapshot(owner, slot.store)[slot.index] - if retry != notice || !w.ml307cSMSNotices.bind(retry, "001122") { + retry := w.storedSMSNotices.snapshot(owner, slot.store)[slot.index] + if retry != notice || !w.storedSMSNotices.bind(retry, "001122") { t.Fatal("periodic list could not recover the pending ME notification") } - if w.ml307cSMSNotices.bind(retry, "aabbcc") { + if w.storedSMSNotices.bind(retry, "aabbcc") { t.Fatal("retry accepted a replacement after the original PDU was read") } - next := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} - w.ml307cSMSNotices.add(next) - w.ml307cSMSNotices.forget(notice) - if !w.ml307cSMSNotices.bind(next, "aabbcc") { + next := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.storedSMSNotices.add(next) + w.storedSMSNotices.forget(notice) + if !w.storedSMSNotices.bind(next, "aabbcc") { t.Fatal("old task discarded a newer slot notification") } owner.simGeneration++ - if len(w.ml307cSMSNotices.snapshot(owner, slot.store)) != 0 || w.ml307cSMSNotices.bind(next, "aabbcc") { + if len(w.storedSMSNotices.snapshot(owner, slot.store)) != 0 || w.storedSMSNotices.bind(next, "aabbcc") { t.Fatal("new SIM generation inherited an ME notice") } - latest := &ml307cSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} - w.ml307cSMSNotices.add(latest) - if len(w.ml307cSMSNotices.snapshot(next.owner, slot.store)) != 0 || !w.ml307cSMSNotices.current(latest) { + latest := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()} + w.storedSMSNotices.add(latest) + if len(w.storedSMSNotices.snapshot(next.owner, slot.store)) != 0 || !w.storedSMSNotices.current(latest) { t.Fatal("an old scan discarded a newer SIM generation's notice") } } diff --git a/internal/device/sms_identity.go b/internal/device/sms_identity.go index 9a349e32..b75d9e45 100644 --- a/internal/device/sms_identity.go +++ b/internal/device/sms_identity.go @@ -108,7 +108,7 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error) } worker.cacheMu.RLock() defer worker.cacheMu.RUnlock() - if atIdentityRulesFor(worker.atProfile()).strictSIMIdentity && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) { + if worker.atDeviceRules().strictSIMIdentity && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) { return smsIdentityCandidate{}, ErrSMSIdentityUnknown } phase := worker.state.Identity.Phase diff --git a/internal/device/sms_mode_at.go b/internal/device/sms_mode_at.go index 765ac669..028ee1cb 100644 --- a/internal/device/sms_mode_at.go +++ b/internal/device/sms_mode_at.go @@ -15,8 +15,8 @@ func configureWorkerATSMS(w *Worker) { } w.Modem.SetNewSMSHandler(nil) w.Modem.SetDisableURCRead(false) - if w.isML307C() { - w.Modem.SetStoredSMSHandler(w.handleML307CStoredSMS) + if w.atDeviceRules().storedSMSInbox { + w.Modem.SetStoredSMSHandler(w.handleStoredSMS) return } w.Modem.SetSMSReadinessCheck(func() error { diff --git a/internal/device/usb_at_port_rules.go b/internal/device/usb_at_port_rules.go index 7ee8af22..2c922a43 100644 --- a/internal/device/usb_at_port_rules.go +++ b/internal/device/usb_at_port_rules.go @@ -1,6 +1,10 @@ package device -import "strings" +import ( + "strings" + + "github.com/yibaiba/hideck/internal/modem" +) const ( cmIoTVendorID = 0x2ecc @@ -29,8 +33,22 @@ type usbDeviceIdentity struct { productID uint16 } -func (id usbDeviceIdentity) isML307C() bool { - return id.vendorID == cmIoTVendorID && id.productID == ml307cProductID +// usbATOnlyLayout describes USB compositions managed only through an AT port. +type usbATOnlyLayout struct { + profile modem.ATProfile + preferredInterface int + alternateInterface int +} + +func (id usbDeviceIdentity) atOnlyLayout() (usbATOnlyLayout, bool) { + if id.vendorID == cmIoTVendorID && id.productID == ml307cProductID { + return usbATOnlyLayout{ + profile: modem.ATProfileML307C, + preferredInterface: 2, + alternateInterface: 3, + }, true + } + return usbATOnlyLayout{}, false } type usbATPortRule struct { @@ -40,8 +58,8 @@ type usbATPortRule struct { } func usbATPortRuleFor(identity usbDeviceIdentity, mode string) (usbATPortRule, bool) { - if identity.isML307C() { - return usbInterfaceATPortRule(2), true + if layout, ok := identity.atOnlyLayout(); ok { + return usbInterfaceATPortRule(layout.preferredInterface), true } mode = strings.ToLower(strings.TrimSpace(mode)) if identity.vendorID == qualcommVendorID && mode == "qmi" { @@ -118,10 +136,10 @@ func supportsStaticQuectelATInterface(mode string) bool { func discoverATPortsForUSBDevice(usbPath string, identity usbDeviceIdentity, mode string) (ports []string, bestPort, imei string) { portScan := scanATPortsForUSBDevice(usbPath) - if identity.isML307C() { + if layout, ok := identity.atOnlyLayout(); ok { var atOnly usbATPortScan for _, port := range portScan.interfaceOrdered { - if port.interfaceNumber == 2 || port.interfaceNumber == 3 { + if port.interfaceNumber == layout.preferredInterface || port.interfaceNumber == layout.alternateInterface { atOnly.interfaceOrdered = append(atOnly.interfaceOrdered, port) atOnly.candidates = append(atOnly.candidates, port.path) } From 096f01d07964609d99ddbab441a73834b2b06e1a Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 19:41:19 +0800 Subject: [PATCH 20/39] fix(device): retire only the matching SIM event timer --- internal/device/pool.go | 8 +++++++- internal/device/sim_removal_test.go | 17 +++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/internal/device/pool.go b/internal/device/pool.go index e26d1c6b..7d007127 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -1192,14 +1192,20 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri return } deviceID := owner.worker.ID + if expected != nil && !p.consumeSIMEventTimer(deviceID, expected) { + return + } releaseMutation := p.AcquireManagedDeviceMutation(deviceID) defer releaseMutation() transition := p.policyTransitionFor(deviceID) transition.Lock() - if !p.workerLifecycleOwnerCurrent(owner) || !p.consumeSIMEventTimer(deviceID, expected) { + if !p.workerLifecycleOwnerCurrent(owner) { transition.Unlock() return } + if expected == nil { + p.consumeSIMEventTimer(deviceID, nil) + } if p.IsESIMSwitching(deviceID) { transition.Unlock() logger.Info("SIM 状态变化发生在 eSIM 切换中,跳过 VoWiFi 自动停止", "device", deviceID, "source", source) diff --git a/internal/device/sim_removal_test.go b/internal/device/sim_removal_test.go index 062582b2..810407d5 100644 --- a/internal/device/sim_removal_test.go +++ b/internal/device/sim_removal_test.go @@ -57,15 +57,28 @@ func TestStaleSIMConfirmationKeepsCurrentWorkerTimer(t *testing.T) { p.simEventTimers = map[string]*time.Timer{w.ID: timer} p.simEventMu.Unlock() - old := &Worker{ID: w.ID, Pool: p} - p.confirmSIMRemovedForOwner(workerLifecycleOwner{worker: old}, "at_startup", nil) + old := workerLifecycleOwner{worker: &Worker{ID: w.ID, Pool: p}} + oldTimer := time.NewTimer(time.Hour) + t.Cleanup(func() { oldTimer.Stop() }) + p.confirmSIMRemovedForOwner(old, "at_startup", nil) + p.confirmSIMRemovedForOwner(old, "sim_event", oldTimer) p.simEventMu.Lock() current := p.simEventTimers[w.ID] + p.simEventTimers[w.ID] = oldTimer p.simEventMu.Unlock() if current != timer { t.Fatal("stale worker consumed the current worker's SIM status timer") } + + // An expired callback can still consume the exact timer it was scheduled for. + p.confirmSIMRemovedForOwner(old, "sim_event", oldTimer) + p.simEventMu.Lock() + current = p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if current != nil { + t.Fatal("expired callback left its own timer registered") + } } func TestConfirmedSIMRemovalClearsIdentityAndDatabaseBinding(t *testing.T) { From 8e80bf7ad31d8cf8d26794def7a9c2aa560176d0 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 19:41:19 +0800 Subject: [PATCH 21/39] refactor(phone): validate the effective phone mode --- internal/api/card_policy.go | 17 +++-- internal/api/card_policy_test.go | 76 ++++++++++++++++----- internal/api/modem_voice.go | 14 ++-- internal/api/route_adapters.go | 104 +++++++++++++---------------- internal/device/at_device_rules.go | 12 +--- internal/device/phone_mode.go | 17 +++-- internal/device/phone_mode_test.go | 3 +- 7 files changed, 137 insertions(+), 106 deletions(-) diff --git a/internal/api/card_policy.go b/internal/api/card_policy.go index af65760e..de4d6098 100644 --- a/internal/api/card_policy.go +++ b/internal/api/card_policy.go @@ -20,7 +20,6 @@ const cardPolicySavedMWIClearFailedCode = "card_policy_saved_mwi_clear_failed" type cardPolicyStore interface { Get(string) (db.CardPolicy, error) - Resolve(string) (db.CardPolicy, error) Upsert(db.CardPolicy) error ClearMWIRejections(string) (bool, error) } @@ -39,10 +38,6 @@ func (databaseCardPolicyStore) Get(iccid string) (db.CardPolicy, error) { return db.GetCardPolicy(iccid) } -func (databaseCardPolicyStore) Resolve(iccid string) (db.CardPolicy, error) { - return db.ResolveCardPolicy(iccid) -} - func (databaseCardPolicyStore) Upsert(policy db.CardPolicy) error { return db.UpsertCardPolicy(policy) } @@ -76,8 +71,11 @@ func (s *Server) patchCardPolicyForDeviceChecked(deviceID string, mutate func(*d if iccid == "" { return "", false, errCardPolicyIdentityUnavailable } - p, err := s.cardPolicyStore().Resolve(iccid) - if err != nil { + p, err := s.cardPolicyStore().Get(iccid) + if errors.Is(err, db.ErrCardPolicyNotFound) { + // Keep the default in memory until the mutation has been validated. + p = db.DefaultCardPolicy(iccid) + } else if err != nil { return iccid, false, fmt.Errorf("获取卡策略失败: %w", err) } if err := mutate(&p); err != nil { @@ -370,10 +368,11 @@ func writeCardPolicyMutationError(c businessContext, err error) { return } status := http.StatusInternalServerError + var unsupportedMode *device.PhoneModeUnsupportedError switch { - case errors.Is(err, errCardPolicyIdentityUnavailable): + case errors.Is(err, errCardPolicyIdentityUnavailable), errors.Is(err, errModemVoiceCallActive): status = http.StatusConflict - case errors.Is(err, device.ErrML307CNativeVoiceUnavailable): + case errors.As(err, &unsupportedMode): status = http.StatusUnprocessableEntity } c.JSON(status, gin.H{"status": "error", "message": err.Error()}) diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go index e543fd8a..fa45ba6d 100644 --- a/internal/api/card_policy_test.go +++ b/internal/api/card_policy_test.go @@ -25,7 +25,6 @@ import ( type cardPolicyStoreStub struct { policy db.CardPolicy getErr error - resolveErr error upsertErr error cleared []string remembered bool @@ -51,10 +50,6 @@ func (s *cardPolicyStoreStub) Get(string) (db.CardPolicy, error) { return s.policy, s.getErr } -func (s *cardPolicyStoreStub) Resolve(string) (db.CardPolicy, error) { - return s.policy, s.resolveErr -} - func (s *cardPolicyStoreStub) Upsert(policy db.CardPolicy) error { s.policy = policy return s.upsertErr @@ -527,19 +522,19 @@ func TestApplyNetworkAndVoWiFiInterlock(t *testing.T) { } wifiPhone := db.CardPolicy{PhoneMode: "wifi", NetworkEnabled: true} - applyVoWiFiEnableToCardPolicy(&wifiPhone) + applyVoWiFiEnableToCardPolicy(&wifiPhone, wifiPhone.PhoneMode) if !wifiPhone.VoWiFiEnabled || !wifiPhone.AirplaneEnabled || wifiPhone.NetworkEnabled { t.Fatalf("开 WiFi calling 应锁定飞行并关流量: %+v", wifiPhone) } cellPhone := db.CardPolicy{PhoneMode: "cellular", DataStrategy: "on_demand", AirplaneEnabled: true} - applyVoWiFiEnableToCardPolicy(&cellPhone) + applyVoWiFiEnableToCardPolicy(&cellPhone, cellPhone.PhoneMode) if !cellPhone.VoWiFiEnabled || cellPhone.AirplaneEnabled || cellPhone.NetworkEnabled { t.Fatalf("开蜂窝软件电话应驻网且默认不开流量: %+v", cellPhone) } voltePhone := db.CardPolicy{PhoneMode: "volte", AirplaneEnabled: true, NetworkEnabled: false} - applyVoWiFiEnableToCardPolicy(&voltePhone) + applyVoWiFiEnableToCardPolicy(&voltePhone, voltePhone.PhoneMode) if !voltePhone.VoWiFiEnabled || voltePhone.AirplaneEnabled || voltePhone.NetworkEnabled { t.Fatalf("开 VoLTE 应驻网且不强制开上网流量: %+v", voltePhone) } @@ -607,21 +602,29 @@ func TestPutCardPolicyAirplaneField(t *testing.T) { } } -func TestML307CPhoneModePatchUsesEffectivePolicy(t *testing.T) { +func TestPhoneModePatchUsesEffectivePolicy(t *testing.T) { gin.SetMode(gin.TestMode) for _, tc := range []struct { - name, imsi, workerMode, storedMode, body string - wantEnabled bool + name, imsi, workerMode, storedMode, body string + wantEnabled, defaultProfile, missingPolicy bool }{ {name: "native VoLTE", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"volte"}`}, {name: "direct dial", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"modem_voice"}`}, {name: "China software fallback", imsi: "460011234567890", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"wifi"}`}, {name: "stored VoLTE ahead of worker", imsi: "530010000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`}, {name: "stored WiFi ahead of worker", imsi: "530010000000001", workerMode: "volte", storedMode: "wifi", body: `{"enabled":true}`, wantEnabled: true}, + {name: "default profile honors stored WiFi over worker cellular", imsi: "530010000000001", workerMode: "cellular", storedMode: "wifi", body: `{"enabled":true}`, wantEnabled: true, defaultProfile: true}, + {name: "Lebara projects stored VoLTE to WiFi", imsi: "234870000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`, wantEnabled: true}, + {name: "explicit Lebara VoLTE remains unsupported", imsi: "234870000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true,"mode":"volte"}`}, + {name: "unsupported mode on a card without a saved policy", imsi: "530010000000001", workerMode: "wifi", body: `{"enabled":true,"mode":"volte"}`, missingPolicy: true}, } { t.Run(tc.name, func(t *testing.T) { - cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: "at", ATPort: "/dev/test-ml307c", PhoneMode: tc.workerMode} - manager, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + cfg := config.DeviceConfig{ID: "test-phone", DeviceBackend: "at", ATPort: "/dev/test-phone", PhoneMode: tc.workerMode, DataStrategy: "on_demand"} + profile := modem.ATProfileML307C + if tc.defaultProfile { + profile = modem.ATProfileDefault + } + manager, err := modem.NewWithATProfile(cfg, profile) if err != nil { t.Fatal(err) } @@ -630,27 +633,31 @@ func TestML307CPhoneModePatchUsesEffectivePolicy(t *testing.T) { host.LifecycleControllerForTest().TestRun = func(context.Context, vowifihost.LifecycleCommand) error { return nil } setNestedPrivateField(t, pool, []string{"vowifiHost"}, host) w := &device.Worker{ID: cfg.ID, Config: cfg, Modem: manager} - policy := db.CardPolicy{ICCID: "8986012345678901234", PhoneMode: tc.storedMode, Source: "auto"} + policy := db.CardPolicy{ICCID: "8986012345678901234", PhoneMode: tc.storedMode, DataStrategy: "always", Source: "auto"} setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, policy.ICCID) setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, tc.imsi) injectWorker(pool, w) store := &cardPolicyStoreStub{policy: policy} + if tc.missingPolicy { + store.getErr = db.ErrCardPolicyNotFound + } s := &Server{pool: pool, cardPolicies: store} r := gin.New() r.PATCH("/api/devices/:device_id/vowifi", s.handleDeviceVoWiFiPatch) rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPatch, "/api/devices/ml307c/vowifi", strings.NewReader(tc.body)) + req := httptest.NewRequest(http.MethodPatch, "/api/devices/"+cfg.ID+"/vowifi", strings.NewReader(tc.body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(rec, req) if tc.wantEnabled { if rec.Code != http.StatusOK || !store.policy.VoWiFiEnabled || !w.Config.VoWiFiEnabled || - w.Config.PhoneMode != tc.storedMode || !w.Config.AirplaneEnabled { + store.policy.PhoneMode != tc.storedMode || w.Config.PhoneMode != device.PhoneModeWiFi || + w.Config.DataStrategy != policy.DataStrategy || !w.Config.AirplaneEnabled || w.Config.NetworkEnabled { t.Fatalf("code=%d body=%s policy=%+v worker=%+v", rec.Code, rec.Body.String(), store.policy, w.Config) } return } - if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), device.ErrML307CNativeVoiceUnavailable.Error()) { + if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨") { t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) } if store.policy != policy || w.Config != cfg { @@ -710,6 +717,41 @@ func TestLebaraUKRFLockRejectsNetworkAndCellular(t *testing.T) { } } +func TestLebaraUKRFLockProjectsSavedCellularModeOnPhoneEnable(t *testing.T) { + gin.SetMode(gin.TestMode) + + iccid := "8944000000000000087" + policy := db.CardPolicy{ICCID: iccid, PhoneMode: device.PhoneModeCellular, DataStrategy: "always", AirplaneEnabled: true} + store := &cardPolicyStoreStub{policy: policy} + pool := device.NewPool(&config.Config{}) + host := vowifihost.NewManager() + host.LifecycleControllerForTest().TestRun = func(context.Context, vowifihost.LifecycleCommand) error { return nil } + setNestedPrivateField(t, pool, []string{"vowifiHost"}, host) + w := &device.Worker{ID: "lebara", Config: config.DeviceConfig{ID: "lebara", PhoneMode: device.PhoneModeWiFi, AirplaneEnabled: true}} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, iccid) + setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "234870000000001") + injectWorker(pool, w) + + s := &Server{pool: pool, cardPolicies: store} + r := gin.New() + r.PATCH("/api/devices/:device_id/vowifi", s.handleDeviceVoWiFiPatch) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPatch, "/api/devices/lebara/vowifi", strings.NewReader(`{"enabled":true}`)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) + } + if got := store.policy; got.PhoneMode != policy.PhoneMode || got.DataStrategy != policy.DataStrategy || + !got.VoWiFiEnabled || !got.AirplaneEnabled || got.NetworkEnabled { + t.Fatalf("unexpected saved policy: %+v", got) + } + if got := w.Config; got.PhoneMode != device.PhoneModeWiFi || !got.VoWiFiEnabled || !got.AirplaneEnabled || got.NetworkEnabled { + t.Fatalf("unexpected runtime policy: %+v", got) + } +} + func TestLebaraUKRFLockClassificationErrorBlocksNetworkMutation(t *testing.T) { gin.SetMode(gin.TestMode) openTestDB(t) diff --git a/internal/api/modem_voice.go b/internal/api/modem_voice.go index b0f25fda..5d877fed 100644 --- a/internal/api/modem_voice.go +++ b/internal/api/modem_voice.go @@ -1,20 +1,20 @@ package api import ( - "net/http" + "errors" - "github.com/gin-gonic/gin" "github.com/yibaiba/hideck/internal/device" ) -func (s *Server) allowModemVoiceModeChange(c businessContext, id, nextMode string) bool { +var errModemVoiceCallActive = errors.New("请先挂断模组直拨通话,再切换或关闭电话服务") + +func (s *Server) checkModemVoiceModeChange(id, nextMode string) error { if s.pool == nil || s.pool.ModemVoiceController() == nil { - return true + return nil } controller := s.pool.ModemVoiceController() if controller.ActiveCall(id) == nil || nextMode == device.PhoneModeModemVoice { - return true + return nil } - c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "请先挂断模组直拨通话,再切换或关闭电话服务"}) - return false + return errModemVoiceCallActive } diff --git a/internal/api/route_adapters.go b/internal/api/route_adapters.go index 70d62c11..f3561881 100644 --- a/internal/api/route_adapters.go +++ b/internal/api/route_adapters.go @@ -128,58 +128,51 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { } if *req.Enabled { - // 落库:置 vowifi_enabled=true。若带 mode/data_strategy 则一并落库。 w := s.pool.GetWorker(deviceID) - mode := normalizePhoneMode(req.Mode) - if req.Mode == nil && w != nil { - mode = w.Config.PhoneMode - } - if !s.allowModemVoiceModeChange(c, deviceID, mode) { - return - } - strategy := normalizeDataStrategy(req.DataStrategy) - forceVoLTE := false - if device.WorkerSoftwareIMSBlocked(w) && !device.IsModemVoiceMode(mode) { - mode = device.PhoneModeVoLTE - forceVoLTE = true - } - useStoredMode := req.Mode == nil && !forceVoLTE && w.CheckPhoneModeSupported(device.PhoneModeVoLTE) != nil - validateMode := func() error { + var mode, strategy string + if _, _, err := s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error { + db.NormalizeCardPolicy(p) + mode = p.PhoneMode + if req.Mode != nil { + mode = normalizePhoneMode(req.Mode) + } + softwareIMSBlocked := device.WorkerSoftwareIMSBlocked(w) + if softwareIMSBlocked && !device.IsModemVoiceMode(mode) { + mode = device.PhoneModeVoLTE + } + var rfPolicyErr error + keepSavedMode := false + if device.PhoneModeCampsOnCell(mode) { + class, err := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID) + switch { + case err != nil: + rfPolicyErr = fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err) + case class.IsLebara && req.Mode == nil && !softwareIMSBlocked: + // Lebara projects the saved mode to WiFi while its RF lock is active. + mode = device.PhoneModeWiFi + keepSavedMode = true + case class.IsLebara: + rfPolicyErr = device.ErrLebaraUKRFLocked + } + } + if err := s.checkModemVoiceModeChange(deviceID, mode); err != nil { + return err + } if err := w.CheckPhoneModeSupported(mode); err != nil { return err } - if device.PhoneModeCampsOnCell(mode) { - class, err := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID) - if err != nil { - return fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err) - } - if class.IsLebara { - return device.ErrLebaraUKRFLocked - } - } - return nil - } - if !useStoredMode { - if err := validateMode(); err != nil { - writeCardPolicyMutationError(c, err) - return - } - } - if _, _, err := s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error { - if req.Mode != nil || forceVoLTE { - p.PhoneMode = mode - } else if useStoredMode { - mode = p.PhoneMode - if err := validateMode(); err != nil { - return err - } + if rfPolicyErr != nil { + return rfPolicyErr } + strategy = p.DataStrategy if req.DataStrategy != nil { - p.DataStrategy = strategy - } else if useStoredMode { - strategy = p.DataStrategy + strategy = normalizeDataStrategy(req.DataStrategy) } - applyVoWiFiEnableToCardPolicy(p) + if !keepSavedMode { + p.PhoneMode = mode + } + p.DataStrategy = strategy + applyVoWiFiEnableToCardPolicy(p, mode) return nil }); err != nil { writeCardPolicyMutationError(c, err) @@ -197,12 +190,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { if prevStrategy == "" { prevStrategy = "on_demand" } - if req.Mode != nil || forceVoLTE || useStoredMode { - w.Config.PhoneMode = mode - } - if req.DataStrategy != nil || useStoredMode { - w.Config.DataStrategy = strategy - } + w.Config.PhoneMode = mode + w.Config.DataStrategy = strategy } s.pool.SetWorkerVoWiFiPolicy(deviceID, true) if w := s.pool.GetWorker(deviceID); w != nil && device.IsModemVoiceMode(w.Config.PhoneMode) { @@ -245,8 +234,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { }) return } - modeChanged := (req.Mode != nil || useStoredMode) && mode != prevMode - strategyChanged := (req.DataStrategy != nil || useStoredMode) && strategy != prevStrategy + modeChanged := mode != prevMode + strategyChanged := strategy != prevStrategy if s.pool.IsVoWiFiActive(deviceID) && (modeChanged || strategyChanged) { if err := s.pool.RestartVoWiFi(deviceID); err != nil { c.JSON(http.StatusInternalServerError, gin.H{ @@ -268,7 +257,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) { } // 落库:仅清 vowifi_enabled=false,保留 airplane_enabled(用户飞行意图)。 - if !s.allowModemVoiceModeChange(c, deviceID, "") { + if err := s.checkModemVoiceModeChange(deviceID, ""); err != nil { + writeCardPolicyMutationError(c, err) return } // 关闭 VoWiFi 后 DisableVoWiFi 会按当前卡策略重投影:之前是飞行则回飞行,否则回在线。 @@ -319,19 +309,19 @@ func applyNetworkEnableToCardPolicy(p *db.CardPolicy) { } // applyVoWiFiEnableToCardPolicy 按通话方式联动射频和流量。 -func applyVoWiFiEnableToCardPolicy(p *db.CardPolicy) { +func applyVoWiFiEnableToCardPolicy(p *db.CardPolicy, mode string) { if p == nil { return } p.VoWiFiEnabled = true - if p.PhoneMode == "cellular" { + if mode == device.PhoneModeCellular { p.AirplaneEnabled = false if p.DataStrategy == "always" { p.NetworkEnabled = true } return } - if p.PhoneMode == "volte" || p.PhoneMode == "modem_voice" { + if device.UsesModemPhoneControl(mode) { p.AirplaneEnabled = false return } diff --git a/internal/device/at_device_rules.go b/internal/device/at_device_rules.go index 34418632..94ec0467 100644 --- a/internal/device/at_device_rules.go +++ b/internal/device/at_device_rules.go @@ -28,16 +28,8 @@ func atDeviceRulesFor(profile modem.ATProfile) atDeviceRules { } func (w *Worker) atDeviceRules() atDeviceRules { - return atDeviceRulesFor(w.atProfile()) -} - -func (w *Worker) atProfile() modem.ATProfile { if w == nil || w.Modem == nil { - return modem.ATProfileDefault + return atDeviceRulesFor(modem.ATProfileDefault) } - return w.Modem.ATProfile() -} - -func (w *Worker) isML307C() bool { - return w.atProfile() == modem.ATProfileML307C + return atDeviceRulesFor(w.Modem.ATProfile()) } diff --git a/internal/device/phone_mode.go b/internal/device/phone_mode.go index d4bc2001..d2273ca2 100644 --- a/internal/device/phone_mode.go +++ b/internal/device/phone_mode.go @@ -11,7 +11,13 @@ import ( var ErrModemVoiceSoftwareIMS = errors.New("模组直拨模式不使用软件 IMS") -var ErrML307CNativeVoiceUnavailable = errors.New("ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨") +type PhoneModeUnsupportedError struct { + Reason string +} + +func (e *PhoneModeUnsupportedError) Error() string { + return e.Reason +} const ( PhoneModeWiFi = "wifi" @@ -70,11 +76,12 @@ func WorkerSoftwareIMSBlocked(w *Worker) bool { return false } -// CheckPhoneModeSupported applies ML307C's native voice limit, including SIMs -// whose carrier policy requires native call control. +// CheckPhoneModeSupported checks native call control when selected or required +// by the SIM's software IMS policy. func (w *Worker) CheckPhoneModeSupported(mode string) error { - if w.isML307C() && (UsesModemPhoneControl(mode) || WorkerSoftwareIMSBlocked(w)) { - return ErrML307CNativeVoiceUnavailable + if reason := w.atDeviceRules().nativeVoiceUnavailableReason; reason != "" && + (UsesModemPhoneControl(mode) || WorkerSoftwareIMSBlocked(w)) { + return &PhoneModeUnsupportedError{Reason: reason} } return nil } diff --git a/internal/device/phone_mode_test.go b/internal/device/phone_mode_test.go index 87621af6..d62baa22 100644 --- a/internal/device/phone_mode_test.go +++ b/internal/device/phone_mode_test.go @@ -107,7 +107,8 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { t.Fatalf("card policy changed or still enables recovery: %+v", resolver.pol) } if tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular { - if err := p.EnableVoWiFi(w.ID); !errors.Is(err, ErrML307CNativeVoiceUnavailable) { + var unsupported *PhoneModeUnsupportedError + if err := p.EnableVoWiFi(w.ID); !errors.As(err, &unsupported) { t.Fatalf("direct software IMS start error = %v", err) } if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() { From 60658cb4be208ddb611a054e2b13f569ec3958e6 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:09:43 +0800 Subject: [PATCH 22/39] fix(phone): restore WiFi using the effective card policy --- internal/device/modem_voice_mode_test.go | 8 ++--- internal/device/phone_mode_test.go | 37 +++++++++++++++++++++-- internal/device/policy_apply.go | 14 ++++----- internal/device/policy_projection.go | 32 ++++++++++++-------- internal/device/policy_projection_test.go | 29 +++++++++++------- internal/device/pool_vowifi_reconcile.go | 10 +++--- internal/device/volte_start_test.go | 4 +-- 7 files changed, 85 insertions(+), 49 deletions(-) diff --git a/internal/device/modem_voice_mode_test.go b/internal/device/modem_voice_mode_test.go index ca8592b6..520dd8f9 100644 --- a/internal/device/modem_voice_mode_test.go +++ b/internal/device/modem_voice_mode_test.go @@ -15,9 +15,7 @@ func TestModemVoicePolicyKeepsExplicitModeAndDoesNotForceData(t *testing.T) { w := &Worker{ID: "test"} w.state.Identity.IMSI = imsi pol := cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice, DataStrategy: "always"} - if err := applyPolicyToWorker(w, pol); err != nil { - t.Fatal(err) - } + applyTestCardPolicy(t, w, pol) if w.Config.PhoneMode != PhoneModeModemVoice || w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() { t.Fatalf("unexpected projection: %+v", w.Config) } @@ -28,9 +26,7 @@ func TestModemVoicePolicyKeepsExplicitModeAndDoesNotForceData(t *testing.T) { func TestModemVoiceCannotOverrideLebaraRadioLock(t *testing.T) { w := &Worker{ID: "test"} w.state.Identity.IMSI = "234870000000001" - if err := applyPolicyToWorker(w, cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice}); err != nil { - t.Fatal(err) - } + applyTestCardPolicy(t, w, cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice}) if !w.Config.AirplaneEnabled || w.Config.NetworkEnabled || !w.cellularRadioIsSuppressed() || w.Config.PhoneMode != PhoneModeWiFi { t.Fatalf("radio lock bypassed: %+v", w.Config) } diff --git a/internal/device/phone_mode_test.go b/internal/device/phone_mode_test.go index d62baa22..7befbae1 100644 --- a/internal/device/phone_mode_test.go +++ b/internal/device/phone_mode_test.go @@ -103,7 +103,7 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { } else if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() { t.Fatalf("unsupported voice mode changed radio state: %v", radio.setCalls) } - if resolver.pol != pol || p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test") { + if resolver.pol != pol || p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test", LebaraUKClass{}) { t.Fatalf("card policy changed or still enables recovery: %+v", resolver.pol) } if tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular { @@ -138,7 +138,7 @@ func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) { if !w.Config.VoWiFiEnabled || !w.Config.AirplaneEnabled || w.Config.PhoneMode != PhoneModeWiFi { t.Fatalf("WiFi policy changed: %+v", w.Config) } - if !p.currentCardPolicyAllowsVoWiFi(w, w.CurrentICCID(), "test") { + if !p.currentCardPolicyAllowsVoWiFi(w, w.CurrentICCID(), "test", LebaraUKClass{}) { t.Fatal("One NZ lost software IMS recovery") } select { @@ -151,6 +151,39 @@ func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) { } } +func TestML307CLebaraSavedVoLTERecoversEffectiveWiFi(t *testing.T) { + p := newDesiredVoWiFiTestPool(t, "ml307c", false, "234870000000001") + t.Cleanup(p.cancel) + w := p.GetWorker("ml307c") + w.Modem = newML307CPhoneTestModem(t, w.ID) + pol := cardpolicy.Policy{ + ICCID: w.CurrentICCID(), PhoneMode: PhoneModeVoLTE, VoWiFiEnabled: true, + } + resolver := &stubPolicyResolver{pol: pol} + p.SetPolicyResolver(resolver) + commands := make(chan vowifihost.LifecycleCommand, 1) + p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, command vowifihost.LifecycleCommand) error { + commands <- command + return nil + } + if result := p.resolveAndApplyPolicy(w, "test"); !result.Applied || result.Err != nil { + t.Fatalf("apply policy: %+v", result) + } + if !w.Config.VoWiFiEnabled || !w.Config.AirplaneEnabled || w.Config.NetworkEnabled || + w.Config.PhoneMode != PhoneModeWiFi || resolver.pol != pol { + t.Fatalf("effective config = %+v, saved policy = %+v", w.Config, resolver.pol) + } + class, err := ClassifyWorkerLebaraUK(w) + if err != nil || !class.IsLebara || !p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test", class) { + t.Fatalf("saved native mode blocked effective WiFi recovery: %+v, %v", class, err) + } + select { + case <-commands: + case <-time.After(time.Second): + t.Fatal("WiFi recovery was not scheduled") + } +} + func newML307CPhoneTestModem(t *testing.T, id string) *modem.Manager { t.Helper() m, err := modem.NewWithATProfile(config.DeviceConfig{ID: id, DeviceBackend: "at", ATPort: "/dev/test-ml307c"}, modem.ATProfileML307C) diff --git a/internal/device/policy_apply.go b/internal/device/policy_apply.go index 0c09f523..2c3d23c4 100644 --- a/internal/device/policy_apply.go +++ b/internal/device/policy_apply.go @@ -54,11 +54,12 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if err := validate(); err != nil { return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err} } - // Apply the unsupported mode as phone-off for this worker only. Keep the - // card's saved mode and explicit radio and network settings. - if worker.CheckPhoneModeSupported(pol.PhoneMode) != nil { - pol.VoWiFiEnabled = false + class, err := ClassifyWorkerLebaraUK(worker) + if err != nil { + logger.Warn("识别 Lebara UK 射频策略失败", "device", worker.ID, "iccid", iccid, "err", err) + return policyApplyResult{ICCID: iccid, Reason: "apply_failed", Err: err} } + pol = effectiveCardPhonePolicy(worker, pol, class) // Finish the old call before projecting a policy that disallows new calls. // Failed hangup leaves the current session and policy available for retry. var finishNativeTransition func() @@ -98,10 +99,7 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if err := validate(); err != nil { return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err} } - if err := applyPolicyToWorker(worker, pol); err != nil { - logger.Warn("投影卡策略失败", "device", worker.ID, "iccid", iccid, "err", err) - return policyApplyResult{ICCID: iccid, Reason: "apply_failed", Err: err} - } + applyPolicyToWorker(worker, pol, class) effective := worker.Config logger.Info("已投影卡策略", "device", worker.ID, "iccid", iccid, "network", effective.NetworkEnabled, "vowifi", effective.VoWiFiEnabled, diff --git a/internal/device/policy_projection.go b/internal/device/policy_projection.go index 8fa899cd..fafad453 100644 --- a/internal/device/policy_projection.go +++ b/internal/device/policy_projection.go @@ -42,15 +42,23 @@ func shouldEnterAirplaneOnDeviceBind(cfg config.DeviceConfig) bool { return shouldSuppressCellularRadio(cfg) } -// applyPolicyToWorker 把卡策略投影进 worker.Config 的运行时有效字段。 -// 不在此触发 re-apply,仅做纯投影,便于单测。 -func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error { - if w == nil { - return nil +// effectiveCardPhonePolicy applies the RF lock before checking the mode. +func effectiveCardPhonePolicy(w *Worker, p cardpolicy.Policy, class LebaraUKClass) cardpolicy.Policy { + if class.IsLebara { + p.PhoneMode = PhoneModeWiFi + p.AirplaneEnabled = true + p.NetworkEnabled = false } - class, err := ClassifyWorkerLebaraUK(w) - if err != nil { - return fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err) + if w.CheckPhoneModeSupported(p.PhoneMode) != nil { + p.VoWiFiEnabled = false + } + return p +} + +// applyPolicyToWorker projects the effective policy without persisting it. +func applyPolicyToWorker(w *Worker, p cardpolicy.Policy, class LebaraUKClass) { + if w == nil { + return } w.Config.NetworkEnabled = p.NetworkEnabled w.Config.VoWiFiEnabled = p.VoWiFiEnabled @@ -69,7 +77,9 @@ func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error { w.Config.NetworkEnabled = false } } - forceSoftwareIMSBlockedToVoLTE(w, p) + if !class.IsLebara { + forceSoftwareIMSBlockedToVoLTE(w, p) + } w.Config.IPVersion = strings.TrimSpace(p.IPVersion) if w.Config.IPVersion == "" { w.Config.IPVersion = "v4" @@ -78,11 +88,7 @@ func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error { w.Config.SMSEnabled = true // SMS 恒开 // 用投影后的有效网络开关。WiFi calling 已强制关流量,启动失败不得借此把射频拉回来。 w.restoreNetworkAfterVoWiFi = w.Config.NetworkEnabled - if class.IsLebara { - applyLebaraUKRFLock(w) - } w.setCellularRadioSuppressed(shouldSuppressCellularRadio(w.Config)) - return nil } func withConnectHoldRF(cfg config.DeviceConfig) config.DeviceConfig { diff --git a/internal/device/policy_projection_test.go b/internal/device/policy_projection_test.go index 9874d9f2..6d460557 100644 --- a/internal/device/policy_projection_test.go +++ b/internal/device/policy_projection_test.go @@ -15,9 +15,18 @@ import ( "github.com/yibaiba/hideck/pkg/logger" ) +func applyTestCardPolicy(t *testing.T, w *Worker, pol cardpolicy.Policy) { + t.Helper() + class, err := ClassifyWorkerLebaraUK(w) + if err != nil { + t.Fatal(err) + } + applyPolicyToWorker(w, effectiveCardPhonePolicy(w, pol, class), class) +} + func TestApplyPolicyCellularAirplaneKeepsSoftwarePhone(t *testing.T) { w := &Worker{ID: "wwan0"} - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", AirplaneEnabled: true, NetworkEnabled: true, DataStrategy: "on_demand", }) @@ -33,7 +42,7 @@ func TestApplyPolicyChinaUnicomForcesNativeVoLTE(t *testing.T) { w := &Worker{ID: "wwan1"} w.state.Identity.NativeMCC = "460" w.state.Identity.IMSI = "460011234567890" - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand", }) if w.Config.PhoneMode != PhoneModeVoLTE { @@ -46,7 +55,7 @@ func TestApplyPolicyChinaUnicomForcesNativeVoLTE(t *testing.T) { func TestApplyPolicyVoLTECampsWithoutForcingData(t *testing.T) { w := &Worker{ID: "wwan1"} - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", VoWiFiEnabled: true, PhoneMode: "volte", }) if w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() { @@ -59,14 +68,14 @@ func TestApplyPolicyVoLTECampsWithoutForcingData(t *testing.T) { func TestApplyPolicyCellularIdleKeepsCamped(t *testing.T) { w := &Worker{ID: "wwan0"} - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand", }) if w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() { t.Fatalf("蜂窝未开流量应保持驻网: %+v suppressed=%v", w.Config, w.cellularRadioIsSuppressed()) } - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand", NetworkEnabled: true, }) if w.Config.AirplaneEnabled || !w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() { @@ -82,9 +91,7 @@ func TestApplyPolicyLocksLebaraUKRadioWithoutRewritingIntent(t *testing.T) { ICCID: "8944000000000000087", AirplaneEnabled: false, NetworkEnabled: true, PhoneMode: "cellular", VoWiFiEnabled: true, DataStrategy: "always", } - if err := applyPolicyToWorker(w, pol); err != nil { - t.Fatal(err) - } + applyTestCardPolicy(t, w, pol) if !w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.Config.PhoneMode != "wifi" { t.Fatalf("Lebara 运行时应锁射频: %+v", w.Config) } @@ -125,7 +132,7 @@ func TestResolveAndApplyPolicyKeepsLebaraUKRadioOff(t *testing.T) { func TestApplyPolicyDoesNotLockBareVodafoneNL(t *testing.T) { w := &Worker{ID: "wwan-nl"} w.state.Identity.IMSI = "204040000000001" - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", AirplaneEnabled: false, NetworkEnabled: true, PhoneMode: "cellular", }) if w.Config.AirplaneEnabled || !w.Config.NetworkEnabled || w.Config.PhoneMode != "cellular" { @@ -135,7 +142,7 @@ func TestApplyPolicyDoesNotLockBareVodafoneNL(t *testing.T) { func TestApplyPolicyProjectsFields(t *testing.T) { w := &Worker{ID: "wwan0"} - applyPolicyToWorker(w, cardpolicy.Policy{ + applyTestCardPolicy(t, w, cardpolicy.Policy{ ICCID: "x", NetworkEnabled: true, VoWiFiEnabled: true, AirplaneEnabled: true, IPVersion: "v4v6", APN: "ims", }) @@ -293,7 +300,7 @@ func TestInitialCellularRadioSuppressionWaitsForLiveCardPolicy(t *testing.T) { w := &Worker{ID: "wwan0"} w.setCellularRadioSuppressed(p.initialCellularRadioSuppression(w.Config)) - applyPolicyToWorker(w, cardpolicy.Policy{ICCID: "123", NetworkEnabled: true}) + applyTestCardPolicy(t, w, cardpolicy.Policy{ICCID: "123", NetworkEnabled: true}) if w.cellularRadioIsSuppressed() { t.Fatal("在线卡策略投影后必须解除蜂窝驻网抑制") } diff --git a/internal/device/pool_vowifi_reconcile.go b/internal/device/pool_vowifi_reconcile.go index 3360a487..8dad1986 100644 --- a/internal/device/pool_vowifi_reconcile.go +++ b/internal/device/pool_vowifi_reconcile.go @@ -125,9 +125,6 @@ func (p *Pool) shouldReconcileVoWiFiForReason(w *Worker, reason string) bool { logger.Warn("VoWiFi 目标态恢复跳过:SIM 身份未就绪", "event", "VOWIFI_DESIRED_RECOVER_SKIPPED_IDENTITY", "device", deviceID) return false } - if !p.currentCardPolicyAllowsVoWiFi(w, status.ICCID, reason) { - return false - } mcc, _, _ := vowifiProfileMCCMNC(status) if mcc != "" && carrier.IsVoWiFiBlockedMCC(mcc) { p.clearDesiredVoWiFiRecoverState(deviceID) @@ -147,7 +144,7 @@ func (p *Pool) shouldReconcileVoWiFiForReason(w *Worker, reason string) bool { "device", deviceID, "imsi", class.LiveIMSI) return false } - return true + return p.currentCardPolicyAllowsVoWiFi(w, status.ICCID, reason, class) } func (p *Pool) stopLebaraUKFlippedVoWiFi(w *Worker, class LebaraUKClass) { @@ -181,7 +178,7 @@ func (p *Pool) isWorkerRebuilding(deviceID string) bool { return rebuilding } -func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason string) bool { +func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason string, class LebaraUKClass) bool { if p == nil || w == nil { return false } @@ -223,11 +220,12 @@ func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason stri "err", err) return false } + pol = effectiveCardPhonePolicy(w, pol, class) if UsesModemPhoneControl(pol.PhoneMode) || UsesModemPhoneControl(w.Config.PhoneMode) { p.clearDesiredVoWiFiRecoverState(deviceID) return false } - if w.CheckPhoneModeSupported(pol.PhoneMode) != nil || !pol.VoWiFiEnabled { + if !pol.VoWiFiEnabled { p.clearDesiredVoWiFiRecoverState(deviceID) // logger.Info("VoWiFi 目标态恢复跳过:当前卡策略未开启 VoWiFi", // "event", "VOWIFI_DESIRED_RECOVER_SKIPPED_CARD_POLICY", diff --git a/internal/device/volte_start_test.go b/internal/device/volte_start_test.go index aec7ba79..fdb9c839 100644 --- a/internal/device/volte_start_test.go +++ b/internal/device/volte_start_test.go @@ -61,9 +61,7 @@ func TestNativeStartCanceledDuringReadinessCannotOutliveHandoff(t *testing.T) { if err := p.stopNativeVoLTEForModemVoice(port.worker.ID); err != nil { t.Fatal(err) } - if err := applyPolicyToWorker(port.worker, cardpolicy.Policy{PhoneMode: PhoneModeModemVoice, VoWiFiEnabled: true}); err != nil { - t.Fatal(err) - } + applyTestCardPolicy(t, port.worker, cardpolicy.Policy{PhoneMode: PhoneModeModemVoice, VoWiFiEnabled: true}) // Readiness must stop without waiting for the backend to become ready. select { case err := <-done: From 63667bc7e01fbc7c0ff16d92b481c87cbaf4e4d3 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:09:43 +0800 Subject: [PATCH 23/39] fix(device): select the AT profile for legacy port bindings --- internal/device/discovery_enrichment.go | 15 ++++--- internal/device/ml307c_discovery_test.go | 50 ++++++++++++++++++++++++ internal/device/pool_bootstrap.go | 36 ++++++++++++++++- 3 files changed, 95 insertions(+), 6 deletions(-) diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index 35497947..94ec7513 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -291,11 +291,7 @@ func (idx WorkerDiscoveryIndex) observeLiveATIdentity(dev CompatibleModem, probe return dev, nil } observation := &atScanObservation{usbPath: dev.USBPath, atPorts: dev.ATPorts} - for _, port := range dev.ATPorts { - owner := idx.atIdentityByPort[port] - if owner.query == nil { - continue - } + if port, owner := idx.ownedATPort(dev.ATPorts); port != "" { dev.ATPort, dev.IMEI = port, "" if imei, err := owner.query(); err == nil { dev.IMEI = imei @@ -311,6 +307,15 @@ func (idx WorkerDiscoveryIndex) observeLiveATIdentity(dev CompatibleModem, probe return resolved, observation } +func (idx WorkerDiscoveryIndex) ownedATPort(ports []string) (string, workerATIdentityReader) { + for _, port := range ports { + if owner := idx.atIdentityByPort[port]; owner.query != nil { + return port, owner + } + } + return "", workerATIdentityReader{} +} + type ConfiguredDeviceIndex struct { byControl map[string]string byUSB map[string]string diff --git a/internal/device/ml307c_discovery_test.go b/internal/device/ml307c_discovery_test.go index 8028958a..64e8cf93 100644 --- a/internal/device/ml307c_discovery_test.go +++ b/internal/device/ml307c_discovery_test.go @@ -15,6 +15,56 @@ import ( "github.com/yibaiba/hideck/internal/modem" ) +func TestConfiguredATPortSelectsDialectWithoutIMEI(t *testing.T) { + port := filepath.Join(t.TempDir(), "ttyUSB8") + if err := os.WriteFile(port, nil, 0o600); err != nil { + t.Fatal(err) + } + alias := filepath.Join(filepath.Dir(port), "by-id") + if err := os.Symlink(port, alias); err != nil { + t.Fatal(err) + } + realPort, err := filepath.EvalSymlinks(port) + if err != nil { + t.Fatal(err) + } + original := discoverFallbackModemsFn + t.Cleanup(func() { discoverFallbackModemsFn = original }) + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + return []CompatibleModem{{ + VendorID: cmIoTVendorID, ProductID: ml307cProductID, ATPorts: []string{realPort}, + }}, nil + } + configured, ok := configuredATDevice(config.DeviceConfig{ManagePort: alias}) + if !ok || configured.ATProfile() != modem.ATProfileML307C || configured.ATPort != realPort { + t.Fatalf("aliased legacy port = %+v, %t", configured, ok) + } + if got, ok := configuredATDevice(config.DeviceConfig{ATPort: "/dev/ttyUSB2", ManagePort: alias}); ok { + t.Fatalf("unmatched AT port selected %+v", got) + } + + // Simulate the same modem already managed over its other AT interface. + const managedPort = "/dev/ttyUSB9" + devices := discoverFallbackModemsFn + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + found, _ := devices() + found[0].ATPorts = append(found[0].ATPorts, managedPort) + return found, nil + } + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + managed := config.DeviceConfig{ID: "active", DeviceBackend: "at", ATPort: managedPort} + m, err := modem.NewWithATProfile(managed, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + p.AttachWorkerForTest(&Worker{ID: managed.ID, Pool: p, Config: managed, Modem: m}) + _, err = p.AddWorkerFromConfig(config.DeviceConfig{ID: "duplicate", DeviceBackend: "at", ManagePort: alias}) + if err == nil || !strings.Contains(err.Error(), "已由现有设备接管") { + t.Fatalf("startup over a second AT interface returned %v", err) + } +} + func TestML307CDiscoveryAndRebind(t *testing.T) { usbPath := filepath.Join(t.TempDir(), "1-1") for _, node := range []string{"1-1:1.2/ttyUSB8", "1-1:1.3/ttyUSB2", "1-1:1.4/ttyUSB3"} { diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 86e07d2c..9821d4bf 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -178,6 +178,29 @@ func configuredPortRequiresLiveATIdentity(cfg config.DeviceConfig, observations return false } +// configuredATDevice finds the explicitly selected port before a legacy config +// has learned its IMEI. Keep the real port for runtime ownership checks. +func configuredATDevice(cfg config.DeviceConfig) (CompatibleModem, bool) { + port := strings.TrimSpace(cfg.ATPort) + if port == "" { + port = strings.TrimSpace(cfg.ManagePort) + } + if port == "" { + return CompatibleModem{}, false + } + port = resolveUSBPathForScan(port) + devices, err := discoverFallbackModemsFn() + if err == nil { + for _, dev := range devices { + if containsPort(dev.ATPorts, port) { + dev.ATPort = port + return dev, true + } + } + } + return CompatibleModem{}, false +} + type qmiBootstrapDiscoveryCache struct { loaded bool list []QMIDevice @@ -345,7 +368,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) devCfg.ModemIMEI = resolved.Matched[0].BackfillIMEI logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI) } - } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || + } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ManagePort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || (atIMEIConfigured && configuredPortRequiresLiveATIdentity(devCfg, atObservations)) { return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") } @@ -420,6 +443,17 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) } backendMode := resolvedBackendMode(devCfg) + if backendMode == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) == "" && atProfile == modem.ATProfileDefault { + if hw, ok := configuredATDevice(devCfg); ok { + atProfile = hw.ATProfile() + if atDeviceRulesFor(atProfile).verifyLiveIMEI { + if port, _ := liveWorkerIndex.ownedATPort(hw.ATPorts); port != "" { + return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port) + } + devCfg.USBPath, devCfg.ATPort, devCfg.ManagePort = hw.USBPath, hw.ATPort, hw.ATPort + } + } + } m, err := newWorkerModem(devCfg, backendMode, atProfile) if err != nil { return nil, fmt.Errorf("初始化 Modem 失败: %w", err) From 332f2ea2461f35edac130aefa1dbf6fdc8dd68ec Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:09:43 +0800 Subject: [PATCH 24/39] fix(sms): require observed groups for cross-SCTS recovery --- internal/device/sms_at_inbox.go | 14 ++++++-------- internal/device/sms_at_inbox_test.go | 3 +++ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index c725dbdf..7bf86af0 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -508,16 +508,14 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo func (state *atSMSParts) archiveSettledATFragments(now time.Time) ([]InboundSMS, error) { var notifications []InboundSMS for _, fragments := range state.settledATFragments(now) { - var sender string - for _, fragment := range fragments { - if sender = state.senders[fragment.SessionKey]; sender != "" { - break - } - } - if sender == "" { - // Sender information is available from an exact PDU in this scan. + // Each group must have an exact PDU in the current scan. A DB-only + // group can outlive its source slots and must not complete a new SMS. + if slices.ContainsFunc(fragments, func(fragment db.SMSInboundFragment) bool { + return state.senders[fragment.SessionKey] == "" + }) { continue } + sender := state.senders[fragments[0].SessionKey] key, content, err := completeATMultipart(fragments[0].SessionKey, fragments) if err != nil { return notifications, err diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index 17c7dfd7..a91c2828 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -126,6 +126,9 @@ func TestATStoredSMSPersistence(t *testing.T) { apply(state, c2, true, false, "") state = load(scope) // Process restart before the follow-up full scan. apply(state, c1, false, false, "") + if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 { + t.Fatalf("archived a cross-SCTS SMS using a DB-only group: %+v, %v", messages, err) + } apply(state, c2, false, false, "") if messages, err := state.archiveSettledATFragments(observed.Add(time.Minute)); err != nil || len(messages) != 0 { t.Fatalf("cross-minute group settled before its collection window elapsed: %+v, %v", messages, err) From fd81d9c5e0328e816681a975412ba96e81804196 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:34:40 +0800 Subject: [PATCH 25/39] fix(sms): preserve AT inbox provenance and durable deduplication --- internal/db/db.go | 4 ++ internal/db/sms_at_receipt.go | 36 +++++++++++ internal/db/sms_at_receipt_test.go | 73 +++++++++++++++++++++ internal/db/sms_fragment_reconcile.go | 36 ++++++----- internal/db/sms_inbound_fragment.go | 41 ++++++------ internal/device/sms_at_inbox.go | 32 ++++++--- internal/device/sms_at_inbox_test.go | 93 ++++++++++++++++++++++++++- 7 files changed, 268 insertions(+), 47 deletions(-) create mode 100644 internal/db/sms_at_receipt.go create mode 100644 internal/db/sms_at_receipt_test.go diff --git a/internal/db/db.go b/internal/db/db.go index 465c72bc..f5e93c00 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -172,6 +172,7 @@ func Init(dbPath string) error { &SMSDelivery{}, &SMSDeliveryPart{}, &SMSInboundFragment{}, + &atSMSReceipt{}, &CommandExecution{}, &CommandEvent{}, &BalanceQuery{}, @@ -218,6 +219,9 @@ func Init(dbPath string) error { if err := ensureSMSFragmentSessionUniqueIndex(DB); err != nil { return err } + if err := backfillATSMSReceipts(DB); err != nil { + return err + } if err := MigrateCardPolicyCanonicalICCID(DB); err != nil { return err } diff --git a/internal/db/sms_at_receipt.go b/internal/db/sms_at_receipt.go new file mode 100644 index 00000000..8ca6dd5e --- /dev/null +++ b/internal/db/sms_at_receipt.go @@ -0,0 +1,36 @@ +package db + +import ( + "errors" + "strings" + + "gorm.io/gorm" +) + +// atSMSReceipt keeps the receive session after its user-visible history is removed. +type atSMSReceipt struct { + ICCID string `gorm:"column:iccid;primaryKey"` + IMSI string `gorm:"column:imsi"` + SessionKey string `gorm:"column:session_key;primaryKey"` +} + +func (atSMSReceipt) TableName() string { return "sms_at_receipt" } + +func backfillATSMSReceipts(database *gorm.DB) error { + return database.Exec(`INSERT INTO sms_at_receipt (iccid, imsi, session_key) + SELECT iccid, imsi, fragment_session_key FROM sms + WHERE type = 1 AND incomplete = false AND fragment_session_key GLOB ? + ON CONFLICT (iccid, session_key) DO NOTHING`, ATSMSInboundPrefix+"*").Error +} + +func HasATSMSReceipt(iccid, imsi, sessionKey string) (bool, error) { + if DB == nil { + return false, errors.New("database not initialized") + } + var row atSMSReceipt + err := DB.Where("iccid = ? AND imsi = ? AND session_key = ?", CanonicalICCID(iccid), strings.TrimSpace(imsi), sessionKey).Take(&row).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return false, nil + } + return err == nil, err +} diff --git a/internal/db/sms_at_receipt_test.go b/internal/db/sms_at_receipt_test.go new file mode 100644 index 00000000..a5e71776 --- /dev/null +++ b/internal/db/sms_at_receipt_test.go @@ -0,0 +1,73 @@ +package db + +import ( + "path/filepath" + "testing" + "time" +) + +func TestATSMSReceiptsBackfillExistingHistory(t *testing.T) { + previousDB := DB + path := filepath.Join(t.TempDir(), "receipt.db") + if err := Init(path); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + closeSMSFragmentTestDB(t) + DB = previousDB + }) + legacy := SMS{ + ICCID: "8944100000000000088", IMSI: "234150000000088", Peer: "+10086", + Sender: "+10086", Content: "legacy", Timestamp: time.Now(), Type: 1, + FragmentSessionKey: ATSMSInboundPrefix + "legacy", + } + // Write directly to emulate a version that persisted no receipt. + if err := DB.Create(&legacy).Error; err != nil { + t.Fatal(err) + } + closeSMSFragmentTestDB(t) + if err := Init(path); err != nil { + t.Fatal(err) + } + if _, _, _, err := DeleteSMSByID(legacy.ID); err != nil { + t.Fatal(err) + } + input := ReceivedMultipartSMS{ + ICCID: legacy.ICCID, IMSI: legacy.IMSI, Sender: legacy.Sender, Content: legacy.Content, + Timestamp: legacy.Timestamp, FragmentSessionKey: legacy.FragmentSessionKey, + } + for _, imsi := range []string{legacy.IMSI, "234150000000089"} { + input.IMSI = imsi + result, err := SaveReceivedMultipartSMS(input) + if err != nil || !result.Duplicate || result.Created { + t.Fatalf("backfilled duplicate for %s: %+v, %v", imsi, result, err) + } + } + if found, err := HasATSMSReceipt(input.ICCID, input.IMSI, input.FragmentSessionKey); err != nil || found { + t.Fatalf("different IMSI acquired deletion evidence: %v, %v", found, err) + } +} + +func TestATSMSReceiptRollsBackWhenHistoryWriteFails(t *testing.T) { + openTestDB(t) + input := ReceivedMultipartSMS{ + ICCID: "8944100000000000088", IMSI: "234150000000088", Sender: "+10086", + Timestamp: time.Now(), Content: "retry", FragmentSessionKey: ATSMSInboundPrefix + "write-failure", + } + if err := DB.Exec(`CREATE TRIGGER reject_at_sms BEFORE INSERT ON sms + BEGIN SELECT RAISE(ABORT, 'test SMS write failure'); END`).Error; err != nil { + t.Fatal(err) + } + if result, err := SaveReceivedMultipartSMS(input); err == nil || result.Created { + t.Fatalf("fault injection: %+v, %v", result, err) + } + if found, err := HasATSMSReceipt(input.ICCID, input.IMSI, input.FragmentSessionKey); err != nil || found { + t.Fatalf("failed history write left a receipt: %v, %v", found, err) + } + if err := DB.Exec("DROP TRIGGER reject_at_sms").Error; err != nil { + t.Fatal(err) + } + if result, err := SaveReceivedMultipartSMS(input); err != nil || !result.Created { + t.Fatalf("retry: %+v, %v", result, err) + } +} diff --git a/internal/db/sms_fragment_reconcile.go b/internal/db/sms_fragment_reconcile.go index 8e8c4f66..640037c7 100644 --- a/internal/db/sms_fragment_reconcile.go +++ b/internal/db/sms_fragment_reconcile.go @@ -6,6 +6,7 @@ import ( "time" "gorm.io/gorm" + "gorm.io/gorm/clause" ) const ( @@ -60,21 +61,6 @@ func compactSQLiteDefinition(definition string) string { return strings.ToLower(strings.Join(strings.Fields(definition), "")) } -// LookupCompletedReceivedSMS finds an already committed receive session without -// creating history for a storage slot with unknown provenance. -func LookupCompletedReceivedSMS(iccid, imsi, sessionKey string) (SMS, bool, error) { - if DB == nil { - return SMS{}, false, errors.New("database not initialized") - } - var row SMS - err := DB.Where("iccid = ? AND imsi = ? AND fragment_session_key = ? AND incomplete = ?", CanonicalICCID(iccid), imsi, sessionKey, false). - First(&row).Error - if errors.Is(err, gorm.ErrRecordNotFound) { - return SMS{}, false, nil - } - return row, err == nil, err -} - func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSResult, error) { if DB == nil { return ReceivedMultipartSMSResult{}, errors.New("database not initialized") @@ -84,6 +70,8 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR return ReceivedMultipartSMSResult{}, err } var result ReceivedMultipartSMSResult + recordATReceipt := !normalized.Incomplete && strings.HasPrefix(normalized.FragmentSessionKey, ATSMSInboundPrefix) + receipt := atSMSReceipt{ICCID: normalized.ICCID, IMSI: normalized.IMSI, SessionKey: normalized.FragmentSessionKey} smsPublicationMu.Lock() defer smsPublicationMu.Unlock() err = DB.Transaction(func(tx *gorm.DB) error { @@ -93,6 +81,16 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR normalized.ICCID, normalized.FragmentSessionKey, ).First(&existing).Error if errors.Is(findErr, gorm.ErrRecordNotFound) { + if recordATReceipt { + insert := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&receipt) + if insert.Error != nil { + return insert.Error + } + if insert.RowsAffected == 0 { + result.Duplicate = true + return nil + } + } created, createErr := createReceivedMultipartSMS(tx, normalized) result = created return createErr @@ -102,7 +100,13 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR } reconciled, reconcileErr := reconcileReceivedMultipartSMS(tx, existing, normalized) result = reconciled - return reconcileErr + if reconcileErr != nil { + return reconcileErr + } + if recordATReceipt && existing.IMSI == normalized.IMSI { + return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&receipt).Error + } + return nil }) if err == nil && (result.Created || result.Reconciled) { publishIncomingSMSByID(result.SMSID) diff --git a/internal/db/sms_inbound_fragment.go b/internal/db/sms_inbound_fragment.go index f645f5d3..6d6c4771 100644 --- a/internal/db/sms_inbound_fragment.go +++ b/internal/db/sms_inbound_fragment.go @@ -20,26 +20,27 @@ type SMSInboundFragmentScope struct { } type SMSInboundFragment struct { - ID uint `gorm:"primaryKey"` - DeviceID string `gorm:"column:device_id;index"` - ICCID string `gorm:"column:iccid"` - IMSI string `gorm:"column:imsi;index"` - SessionKey string `gorm:"column:session_key"` - Sequence int `gorm:"column:sequence"` - Reference int `gorm:"column:reference"` - ReferenceBits int `gorm:"column:reference_bits"` - Total int `gorm:"column:total"` - Content string `gorm:"column:content"` - ArrivedAt time.Time `gorm:"column:arrived_at;index"` - RPMR int `gorm:"column:rp_mr"` - CallID string `gorm:"column:call_id"` - ToURI string `gorm:"column:to_uri"` - ServiceCenter string `gorm:"column:service_center"` - AckSent bool `gorm:"column:ack_sent"` - AckSentAt time.Time `gorm:"column:ack_sent_at"` - DegradedAt time.Time `gorm:"column:degraded_at;index"` - CreatedAt time.Time `gorm:"column:created_at"` - UpdatedAt time.Time `gorm:"column:updated_at"` + ID uint `gorm:"primaryKey"` + DeviceID string `gorm:"column:device_id;index"` + ICCID string `gorm:"column:iccid"` + IMSI string `gorm:"column:imsi;index"` + SessionKey string `gorm:"column:session_key"` + Sequence int `gorm:"column:sequence"` + Reference int `gorm:"column:reference"` + ReferenceBits int `gorm:"column:reference_bits"` + Total int `gorm:"column:total"` + Content string `gorm:"column:content"` + PDUFingerprint string `gorm:"column:pdu_fingerprint"` + ArrivedAt time.Time `gorm:"column:arrived_at;index"` + RPMR int `gorm:"column:rp_mr"` + CallID string `gorm:"column:call_id"` + ToURI string `gorm:"column:to_uri"` + ServiceCenter string `gorm:"column:service_center"` + AckSent bool `gorm:"column:ack_sent"` + AckSentAt time.Time `gorm:"column:ack_sent_at"` + DegradedAt time.Time `gorm:"column:degraded_at;index"` + CreatedAt time.Time `gorm:"column:created_at"` + UpdatedAt time.Time `gorm:"column:updated_at"` } func (SMSInboundFragment) TableName() string { return "sms_inbound_fragment" } diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index 7bf86af0..d8913a43 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -411,8 +411,9 @@ func (state *atSMSParts) persist(part atInboxPart, sourceKnown bool) (bool, *Inb return false, nil, nil } if !sourceKnown { - saved, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, part.key) - return found && strings.TrimSpace(part.Content) == saved.Content, nil, err + // The single-part session key already hashes the full PDU. + found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, part.key) + return found, nil, err } return state.commit(part, part.Content) } @@ -423,18 +424,31 @@ const ( ) func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (string, bool, error) { + fingerprint := hex.EncodeToString(part.fingerprint[:]) + matches := func(saved db.SMSInboundFragment) bool { + if sourceKnown { + return saved.Content == part.Content + } + return saved.PDUFingerprint == fingerprint + } // Older fragments only have the legacy exact-SCTS key. It remains valid // for exact matches, but cannot prove the new metadata for a fuzzy join. if fragments := state.groups[part.key]; len(fragments) != 0 { for _, saved := range fragments { if saved.Sequence == part.Concat.Seq { - if saved.Content != part.Content { + if matches(saved) { + return part.key, true, nil + } + if sourceKnown { return "", false, db.ErrSMSInboundFragmentCollision } - return part.key, true, nil + break } } - return part.key, false, nil + if sourceKnown { + return part.key, false, nil + } + return "", false, nil } prefix := atSMSPartGroupPrefix + part.family + ":" + part.SCTS + ":" @@ -447,13 +461,14 @@ func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (stri for _, saved := range fragments { if saved.Sequence == part.Concat.Seq { occupied = true - if saved.Content == part.Content { + if matches(saved) { duplicates = append(duplicates, key) } break } } - if !occupied && len(fragments) < part.Concat.Total { + // An ME slot with no CMTI can retry only an already persisted PDU. + if sourceKnown && !occupied && len(fragments) < part.Concat.Total { candidates = append(candidates, key) } } @@ -486,6 +501,7 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo result, err := db.SaveSMSInboundFragment(scope, db.SMSInboundFragment{ Sequence: concat.Seq, Reference: concat.Ref, ReferenceBits: concat.RefBits, Total: concat.Total, Content: part.Content, ArrivedAt: part.Timestamp, + PDUFingerprint: hex.EncodeToString(part.fingerprint[:]), }) if err != nil { return false, nil, err @@ -668,7 +684,7 @@ func (state *atSMSParts) clearCompletedGroups() error { if err != nil { return err } - _, found, err := db.LookupCompletedReceivedSMS(state.scope.ICCID, state.scope.IMSI, completedKey) + found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, completedKey) if err != nil { return err } diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index a91c2828..46f6317b 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -1,7 +1,9 @@ package device import ( + "context" "encoding/hex" + "path/filepath" "testing" "time" @@ -9,7 +11,28 @@ import ( ) func TestATStoredSMSPersistence(t *testing.T) { - initDevicePhoneNumberTestDB(t) + dbPath := filepath.Join(t.TempDir(), "at-sms.db") + open := func() { + t.Helper() + if err := db.Init(dbPath); err != nil { + t.Fatal(err) + } + } + closeDB := func() { + t.Helper() + sqlDB, err := db.DB.DB() + if err != nil { + t.Fatal(err) + } + if err := sqlDB.Close(); err != nil { + t.Fatal(err) + } + } + open() + t.Cleanup(func() { + closeDB() + db.DB = nil + }) identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} fragment := func(seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart { @@ -56,6 +79,13 @@ func TestATStoredSMSPersistence(t *testing.T) { } } + lookupHistory := func(key string) (db.SMS, bool, error) { + var row db.SMS + query := db.DB.Where("iccid = ? AND imsi = ? AND fragment_session_key = ?", scope.ICCID, scope.IMSI, key). + Limit(1).Find(&row) + return row, query.RowsAffected == 1, query.Error + } + observed := time.Now() a1 := fragment(1, 0, 0, '甲', observed) a2 := fragment(2, 0, 0, '乙', observed.Add(2*time.Second)) @@ -69,6 +99,22 @@ func TestATStoredSMSPersistence(t *testing.T) { if len(state.groups) != 1 { t.Fatalf("first fragment was not restored: %+v", state.groups) } + // A stale ME slot from another SIM can have the same sender, reference, + // SCTS and total as this SIM's pending first part. + otherSIM := scope + otherSIM.ICCID = "8988110000000000003" + staleTail := fragment(2, 0, 0, '异', observed) + apply(load(otherSIM), staleTail, true, false, "") + apply(state, staleTail, false, false, "") + if len(state.groups) != 1 { + t.Fatal("unknown ME tail created another group") + } + for _, group := range state.groups { + if len(group) != 1 { + t.Fatal("unknown ME tail filled a pending sequence") + } + } + apply(state, b2, true, false, "") // Another message reused the ref inside the collection window. if got := state.settledATFragments(observed.Add(time.Second)); len(got) != 0 { t.Fatal("merged A1 and B2 before their exact partners arrived") @@ -79,6 +125,33 @@ func TestATStoredSMSPersistence(t *testing.T) { t.Fatal("already complete exact messages must not be merged") } + state = load(scope) + // A different, unrecognised UDH IE leaves the decoded text and all + // grouping metadata equal but changes the raw PDU. + differentPDU := fragment(2, 0, 0, '乙', observed, 0x70, 1, 0x01) + if differentPDU.family != a2.family || differentPDU.key != a2.key || differentPDU.fingerprint == a2.fingerprint { + t.Fatalf("raw mismatch fixture: %+v", differentPDU) + } + apply(state, differentPDU, false, false, "") + exactKey := "" + for key, group := range state.groups { + if group[0].Content == a1.Content { + var err error + exactKey, _, err = completeATMultipart(key, group) + if err != nil { + t.Fatal(err) + } + } + } + exact, found, err := lookupHistory(exactKey) + if err != nil || !found { + t.Fatalf("exact archived SMS: %+v, %v, %v", exact, found, err) + } + if _, _, _, err := db.DeleteSMSByID(exact.ID); err != nil { + t.Fatal(err) + } + closeDB() + open() state = load(scope) apply(state, a2, false, true, "") // A failed deletion can retry from durable evidence. if err := state.clearCompletedGroups(); err != nil { @@ -112,7 +185,10 @@ func TestATStoredSMSPersistence(t *testing.T) { }); err != nil { t.Fatal(err) } - apply(load(scope), legacy2, false, true, "旧件") + apply(load(scope), legacy2, false, false, "") + apply(load(scope), legacy1, false, false, "") + apply(load(scope), legacy2, true, true, "旧件") + apply(load(scope), legacy1, false, false, "") // No raw PDU hash on the pre-upgrade row. observed = observed.Add(5 * time.Minute) c1 := fragment(1, 0x30, 0x95, '跨', observed) @@ -145,15 +221,26 @@ func TestATStoredSMSPersistence(t *testing.T) { if err != nil || len(messages) != 1 || messages[0].Content != content { t.Fatalf("archive after restart: %+v, %v", messages, err) } - if saved, found, err := db.LookupCompletedReceivedSMS(scope.ICCID, scope.IMSI, key); err != nil || !found || saved.Content != content { + saved, found, err := lookupHistory(key) + if err != nil || !found || saved.Content != content { t.Fatalf("archived history: %+v, %v, %v", saved, found, err) } + if err := db.DeleteArchivedRecords(context.Background(), db.DB, db.ArchiveDeleteRequest{SMSIDs: []uint{saved.ID}}); err != nil { + t.Fatal(err) + } + closeDB() + open() state = load(scope) apply(state, c1, false, false, "") apply(state, c2, false, false, "") if messages, err := state.archiveSettledATFragments(observed.Add(4 * time.Minute)); err != nil || len(messages) != 0 { t.Fatalf("repeat scan notified an archived SMS twice: %+v, %v", messages, err) } + for _, deletedKey := range []string{exactKey, key} { + if _, found, err := lookupHistory(deletedKey); err != nil || found { + t.Fatalf("repeat scan recreated a removed history row: %s, %v, %v", deletedKey, found, err) + } + } // A second possible first part within the same family/window makes the // entire candidate ambiguous, regardless of how close the older SCTS is. From 12519e481f01eaea6ae742ae70d7684936ea73e3 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:35:58 +0800 Subject: [PATCH 26/39] fix(device): confirm SIM PIN state before retiring phone runtimes --- internal/device/pool.go | 53 ++++++++++++------ internal/device/sim_removal.go | 22 ++++++-- internal/device/sim_removal_test.go | 87 ++++++++++++++++++++++++++++- internal/modem/at_profile.go | 3 - internal/modem/at_profile_test.go | 17 ++++++ internal/modem/manager.go | 11 ++-- 6 files changed, 161 insertions(+), 32 deletions(-) diff --git a/internal/device/pool.go b/internal/device/pool.go index 7d007127..e5fcae30 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -664,6 +664,10 @@ func (w *Worker) RefreshIdentityLive(ctx context.Context, reason string) error { } func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSIMIdentityRefreshResult, error) { + return w.refreshIdentityLiveWithPresence(ctx, reason, false) +} + +func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason string, presenceConfirmed bool) (liveSIMIdentityRefreshResult, error) { if w == nil { return liveSIMIdentityRefreshResult{}, fmt.Errorf("worker_nil") } @@ -681,11 +685,15 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI } strictSIMIdentity := w.atDeviceRules().strictSIMIdentity - if strictSIMIdentity { + if strictSIMIdentity && !presenceConfirmed { + generation := w.SIMIdentityGeneration() inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { if errors.Is(err, modem.ErrSIMPINRequired) && (w.Pool == nil || !w.Pool.IsESIMSwitching(w.ID)) { - w.markSIMPINRequired() + if w.markSIMPINRequired(generation) && w.Pool != nil { + owner := workerLifecycleOwner{worker: w, generation: w.generation} + w.Pool.handleSIMStatusEventForOwner(owner, reason, nil, "SIM PIN") + } } return liveSIMIdentityRefreshResult{}, err } @@ -1041,11 +1049,9 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s return } state = strings.ToUpper(strings.TrimSpace(state)) + pinHint := false if owner.worker.atDeviceRules().strictSIMIdentity { - if modem.IsSIMPINRequiredState(state) { - p.handleSIMPINRequired(owner) - return - } + pinHint = modem.IsSIMPINRequiredState(state) if insertedHint != nil { if *insertedHint && !owner.worker.SIMIdentityConvergenceMatches("", 0) { return @@ -1058,7 +1064,7 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s return } } - } else if state != "READY" && state != "SIM REMOVED" && state != "SIM NOT INSERTED" { + } else if !pinHint && state != "READY" && state != "SIM REMOVED" && state != "SIM NOT INSERTED" { return } } else if (insertedHint != nil && *insertedHint) || state == "READY" { @@ -1071,11 +1077,16 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s p.simEventTimers = make(map[string]*time.Timer) } if timer := p.simEventTimers[deviceID]; timer != nil { + // A pending status check will already detect a live PIN lock. + if pinHint { + p.simEventMu.Unlock() + return + } timer.Stop() } var timer *time.Timer timer = time.AfterFunc(1500*time.Millisecond, func() { - p.confirmSIMRemovedForOwner(owner, source, timer) + p.confirmSIMStatusForOwner(owner, source, timer, pinHint) }) p.simEventTimers[deviceID] = timer p.simEventMu.Unlock() @@ -1188,6 +1199,10 @@ func (p *Pool) confirmSIMRemovedAndStopVoWiFi(deviceID, source string) { } func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source string, expected *time.Timer) { + p.confirmSIMStatusForOwner(owner, source, expected, false) +} + +func (p *Pool) confirmSIMStatusForOwner(owner workerLifecycleOwner, source string, expected *time.Timer, pinHint bool) { if p == nil || owner.worker == nil { return } @@ -1222,17 +1237,23 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri } ctx, cancel := context.WithTimeout(baseCtx, 3*time.Second) defer cancel() + generation := w.SIMIdentityGeneration() inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { - transition.Unlock() if w.atDeviceRules().strictSIMIdentity && errors.Is(err, modem.ErrSIMPINRequired) { - p.handleSIMPINRequired(owner) + p.handleConfirmedSIMPINRequired(owner, generation) + transition.Unlock() return } + transition.Unlock() logger.Warn("SIM 拔卡确认失败,跳过 VoWiFi 自动停止", "device", deviceID, "source", source, "err", err) return } if inserted { + if pinHint && !w.SIMIdentityConvergenceMatches("", 0) { + transition.Unlock() + return + } result := p.refreshConfirmedSIMInsertion(owner) transition.Unlock() p.finishConfirmedSIMInsertion(owner, source, result) @@ -1262,7 +1283,7 @@ type simInsertionRefreshResult struct { func (p *Pool) refreshConfirmedSIMInsertion(owner workerLifecycleOwner) simInsertionRefreshResult { w := owner.worker previous := currentSIMOwnership(w) - _, err := p.refreshWorkerIdentityState(w, "sim_status_inserted") + _, err := p.refreshWorkerIdentityState(w, "sim_status_inserted", true) return simInsertionRefreshResult{ current: p.workerLifecycleOwnerCurrent(owner), identityChanged: err == nil && currentSIMOwnership(w) != previous, @@ -1277,10 +1298,6 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st } p.broadcastVoWiFiStateChange(w.ID) if result.err != nil { - if w.atDeviceRules().strictSIMIdentity && errors.Is(result.err, modem.ErrSIMPINRequired) { - p.handleSIMPINRequired(owner) - return - } logger.Warn("SIM 插入后刷新身份失败", "device", w.ID, "source", source, "err", result.err) return } @@ -1661,7 +1678,7 @@ func (p *Pool) refreshIdentityAndApplyCardPolicy(worker *Worker, reason string) if worker == nil { return liveSIMIdentityRefreshResult{}, nil } - result, identityErr := p.refreshWorkerIdentityState(worker, reason) + result, identityErr := p.refreshWorkerIdentityState(worker, reason, false) refreshErr := identityErr if p != nil { @@ -1679,12 +1696,12 @@ func (p *Pool) refreshIdentityAndApplyCardPolicy(worker *Worker, reason string) return result, refreshErr } -func (p *Pool) refreshWorkerIdentityState(worker *Worker, reason string) (liveSIMIdentityRefreshResult, error) { +func (p *Pool) refreshWorkerIdentityState(worker *Worker, reason string, presenceConfirmed bool) (liveSIMIdentityRefreshResult, error) { if worker == nil { return liveSIMIdentityRefreshResult{}, fmt.Errorf("worker_nil") } _ = worker.RefreshRuntime(nil, reason) - result, err := worker.refreshIdentityLive(nil, reason) + result, err := worker.refreshIdentityLiveWithPresence(nil, reason, presenceConfirmed) if p != nil { p.PersistRuntimeState(worker) p.PersistIdentityState(worker) diff --git a/internal/device/sim_removal.go b/internal/device/sim_removal.go index 5c5cba92..ee764e4c 100644 --- a/internal/device/sim_removal.go +++ b/internal/device/sim_removal.go @@ -38,26 +38,33 @@ func (w *Worker) markSIMRemoved(reason string) { w.cacheMu.Unlock() } -func (w *Worker) markSIMPINRequired() { +func (w *Worker) markSIMPINRequired(generation uint64) bool { now := time.Now() w.cacheMu.Lock() defer w.cacheMu.Unlock() + if w.state.Identity.Generation != generation { + return false + } if w.state.Identity.LastError == modem.ErrSIMPINRequired.Error() && !w.state.Identity.Ready { - return + return true } w.markSIMIdentityDegradedLocked("sim_pin_required", modem.ErrSIMPINRequired, now) w.state.Identity.Generation++ w.state.Runtime.SimInserted = false w.state.Meta.RuntimeUpdatedAt = now + return true } -func (p *Pool) handleSIMPINRequired(owner workerLifecycleOwner) { +// Caller holds the device policy transition lock. +func (p *Pool) handleConfirmedSIMPINRequired(owner workerLifecycleOwner, generation uint64) { if !p.workerLifecycleOwnerCurrent(owner) || p.IsESIMSwitching(owner.worker.ID) { return } w := owner.worker - w.markSIMPINRequired() - if err := p.retirePhoneRuntimesForSIMChange(owner); err != nil { + if !w.markSIMPINRequired(generation) { + return + } + if err := p.retirePhoneRuntimesForSIMChangeLocked(owner); err != nil { logger.Warn("SIM PIN 锁定后停止电话业务失败", "device", w.ID, "err", err) } p.broadcastVoWiFiStateChange(w.ID) @@ -71,9 +78,14 @@ func (p *Pool) retirePhoneRuntimesForSIMChange(owner workerLifecycleOwner) error transition := p.policyTransitionFor(deviceID) transition.Lock() defer transition.Unlock() + return p.retirePhoneRuntimesForSIMChangeLocked(owner) +} + +func (p *Pool) retirePhoneRuntimesForSIMChangeLocked(owner workerLifecycleOwner) error { if !p.workerLifecycleOwnerCurrent(owner) { return errPolicyOwnerChanged } + deviceID := owner.worker.ID p.stopNativeVoLTE(deviceID, "sim_identity_changed") if err := p.stopModemVoice(deviceID); err != nil { return fmt.Errorf("stop modem voice: %w", err) diff --git a/internal/device/sim_removal_test.go b/internal/device/sim_removal_test.go index 810407d5..9d82c9b4 100644 --- a/internal/device/sim_removal_test.go +++ b/internal/device/sim_removal_test.go @@ -177,13 +177,97 @@ func TestConfirmedSIMRemovalCancelsStartingVoWiFi(t *testing.T) { type ml307cSIMBackendStub struct { workerStartupIdentityBackendStub - simErr error + simErr error + onSIMQuery func() } func (s *ml307cSIMBackendStub) IsSimInserted(context.Context) (bool, error) { + if s.onSIMQuery != nil { + s.onSIMQuery() + } return s.simErr == nil, s.simErr } +func confirmScheduledSIMPIN(t *testing.T, p *Pool, owner workerLifecycleOwner) { + t.Helper() + p.simEventMu.Lock() + timer := p.simEventTimers[owner.worker.ID] + p.simEventMu.Unlock() + if timer == nil { + t.Fatal("PIN event did not schedule a SIM status check") + } + if !timer.Stop() { + t.Fatal("SIM status check ran before the test could confirm it") + } + p.confirmSIMStatusForOwner(owner, "test", timer, true) +} + +func TestML307CDelayedPINKeepsCurrentSIMAndCall(t *testing.T) { + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"} + m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + be := &ml307cSIMBackendStub{} + be.liveICCID, be.liveIMSI = "card-new", "imsi-new" + w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be} + p.AttachWorkerForTest(w) + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"}) + w.state.Identity.Generation++ + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}) + w.state.Identity.Generation++ + before := currentSIMOwnership(w) + owner := p.captureWorkerLifecycleOwner(w.ID) + + instance := &runtimehost.Instance{} + p.voWiFiRuntimeStore().SetInstance(w.ID, instance) + t.Cleanup(func() { p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil) }) + stops := 0 + p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, _ vowifihost.LifecycleCommand) error { + stops++ + return nil + } + + p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN") + confirmScheduledSIMPIN(t, p, owner) + if got := currentSIMOwnership(w); got != before || w.SIMIdentityConvergenceMatches("", 0) { + t.Fatalf("stale PIN changed ready SIM ownership: before=%+v after=%+v", before, got) + } + if stops != 0 { + t.Fatalf("stale PIN stopped an active runtime %d times", stops) + } + + p.switchMu.Lock() + p.switchingDevices[w.ID] = true + p.switchMu.Unlock() + be.simErr = modem.ErrSIMPINRequired + p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN") + confirmScheduledSIMPIN(t, p, owner) + if got := currentSIMOwnership(w); got != before || stops != 0 { + t.Fatalf("PIN during eSIM switch changed SIM ownership or stopped calls: before=%+v after=%+v stops=%d", before, got, stops) + } + p.switchMu.Lock() + delete(p.switchingDevices, w.ID) + p.switchMu.Unlock() + + // A separate live identity refresh can publish a new generation while + // the PIN confirmation reads the backend. + be.onSIMQuery = func() { + w.cacheMu.Lock() + defer w.cacheMu.Unlock() + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-newer", IMSI: "imsi-newer"}) + w.state.Identity.Generation++ + } + p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN") + confirmScheduledSIMPIN(t, p, owner) + if got := currentSIMOwnership(w); got.iccid != "card-newer" || got.generation != before.generation+1 || + w.SIMIdentityConvergenceMatches("", 0) || stops != 0 { + t.Fatalf("old PIN result affected a newer SIM generation: ownership=%+v stops=%d", got, stops) + } +} + func TestML307CPINRecoveryRetriesIdentityOnRepeatedReady(t *testing.T) { p := NewPool(&config.Config{}) t.Cleanup(func() { _ = p.Shutdown() }) @@ -208,6 +292,7 @@ func TestML307CPINRecoveryRetriesIdentityOnRepeatedReady(t *testing.T) { } p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PUK") + confirmScheduledSIMPIN(t, p, owner) select { case command := <-commands: if command.Kind != vowifihost.LifecycleCommandDisable { diff --git a/internal/modem/at_profile.go b/internal/modem/at_profile.go index 3ea16cf5..dc523b81 100644 --- a/internal/modem/at_profile.go +++ b/internal/modem/at_profile.go @@ -181,9 +181,6 @@ func (m *Manager) queryCPINSIMPresence(query *atCPINPresenceQuery) (bool, error) if err == nil || errors.Is(err, ErrSIMPINRequired) { m.cacheCPINSIMState(inserted, err) } - if errors.Is(err, ErrSIMPINRequired) { - m.dispatchSIMStatusURC(nil, "SIM PIN") - } return inserted, err } diff --git a/internal/modem/at_profile_test.go b/internal/modem/at_profile_test.go index 4ae027a3..deb7d480 100644 --- a/internal/modem/at_profile_test.go +++ b/internal/modem/at_profile_test.go @@ -4,6 +4,7 @@ import ( "errors" "slices" "testing" + "time" "github.com/yibaiba/hideck/internal/config" ) @@ -77,9 +78,25 @@ func TestML307CATQueries(t *testing.T) { if ready, err := m.QuerySIMInserted(); !ready || err != nil || !m.IsSimInserted() { t.Fatalf("ready CPIN = %v, %v", ready, err) } + simEvents := make(chan string, 2) + m.SetSIMStatusHandler(func(_ *bool, state string) { simEvents <- state }) + m.handleURC("+CPIN: SIM PIN") + select { + case state := <-simEvents: + if state != "SIM PIN" || !m.IsSimInserted() { + t.Fatalf("PIN URC changed confirmed readiness: event=%q ready=%v", state, m.IsSimInserted()) + } + case <-time.After(time.Second): + t.Fatal("PIN URC was not dispatched") + } if ready, err := m.QuerySIMInserted(); ready || !errors.Is(err, ErrSIMPINRequired) || m.IsSimInserted() { t.Fatalf("locked CPIN = %v, %v", ready, err) } + select { + case state := <-simEvents: + t.Fatalf("live PIN query requeued a SIM callback: %q", state) + case <-time.After(50 * time.Millisecond): + } if ready, err := m.QuerySIMInserted(); ready || err != nil { t.Fatalf("absent CPIN = %v, %v", ready, err) } diff --git a/internal/modem/manager.go b/internal/modem/manager.go index 571211bb..91a4031a 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -1306,8 +1306,12 @@ func (m *Manager) RefreshStatus(onAlert func(msg string), onRecover func(msg str // 检查 SIM 卡是否存活 simInserted, simErr := m.QuerySIMInserted() - if m.atProfile.dialect().cpinPresence != nil && simErr == nil { - m.dispatchSIMStatusURC(&simInserted, "") + if m.atProfile.dialect().cpinPresence != nil { + if errors.Is(simErr, ErrSIMPINRequired) { + m.dispatchSIMStatusURC(nil, "SIM PIN") + } else if simErr == nil { + m.dispatchSIMStatusURC(&simInserted, "") + } } if v, err := m.QueryOperator(); err == nil { @@ -1456,9 +1460,6 @@ func (m *Manager) handleURC(line string) { break } } - if m.atProfile.dialect().cpinPresence != nil && IsSIMPINRequiredState(state) { - m.cacheCPINSIMState(false, ErrSIMPINRequired) - } m.dispatchSIMStatusURC(nil, state) } From f134a02ae637430bf381301b1ec39afd3bfe3ed8 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:35:58 +0800 Subject: [PATCH 27/39] fix(device): verify IMEI on the opened AT runtime port --- internal/device/at_port_resolver.go | 4 +- internal/device/discovery_enrichment.go | 10 +- internal/device/ml307c_discovery_test.go | 133 ++++++++++++++++++- internal/device/pool_bootstrap.go | 71 +++++----- internal/modem/imei_cache_test.go | 10 +- internal/modem/imei_probe.go | 98 +++++++++++--- internal/modem/imei_probe_test.go | 157 +++++++++++++++++++++++ internal/modem/manager.go | 16 ++- 8 files changed, 431 insertions(+), 68 deletions(-) create mode 100644 internal/modem/imei_probe_test.go diff --git a/internal/device/at_port_resolver.go b/internal/device/at_port_resolver.go index f2fc92a7..09de2dd1 100644 --- a/internal/device/at_port_resolver.go +++ b/internal/device/at_port_resolver.go @@ -11,7 +11,7 @@ import ( // probeIMEICachedFn 允许测试替换底层 IMEI 探测实现。 var probeIMEICachedFn = modem.ProbeIMEICached var probeIMEICachedContextFn = modem.ProbeIMEICachedContext -var probeProfileIMEICachedFn = modem.ATProfile.ProbeIMEICached +var probeProfileIMEIFn = modem.ATProfile.ProbeIMEI // orderedATPortCandidates 按“单设备定界”规则生成探测顺序。 // 只允许在当前设备自己的 ATPorts 集合内排序和前置候选口; @@ -117,7 +117,7 @@ func ResolveCompatibleModemATPortContext( preferred := dev.ATPort dev.ATPort, dev.IMEI = "", "" for _, port := range orderedATPortCandidates(preferred, dev.ATPorts) { - imei, err := probeProfileIMEICachedFn(profile, ctx, port, timeout) + imei, err := probeProfileIMEIFn(profile, ctx, port, timeout) if err == nil && imei != "" { dev.ATPort, dev.IMEI = port, imei return dev, imei diff --git a/internal/device/discovery_enrichment.go b/internal/device/discovery_enrichment.go index 94ec7513..a7d7d79d 100644 --- a/internal/device/discovery_enrichment.go +++ b/internal/device/discovery_enrichment.go @@ -219,7 +219,10 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor IMEI: strings.TrimSpace(cfg.ModemIMEI), } if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" { - idx.atIdentityByPort[worker.ResolvedATPort()] = workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI} + port := worker.ResolvedATPort() + owner := workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI} + idx.atIdentityByPort[port] = owner + idx.atIdentityByPort[resolveUSBPathForScan(port)] = owner } if includeRuntimeStatus && !worker.atDeviceRules().verifyLiveIMEI { status := worker.GetDeviceStatus() @@ -312,6 +315,11 @@ func (idx WorkerDiscoveryIndex) ownedATPort(ports []string) (string, workerATIde if owner := idx.atIdentityByPort[port]; owner.query != nil { return port, owner } + if canonical := resolveUSBPathForScan(port); canonical != port { + if owner := idx.atIdentityByPort[canonical]; owner.query != nil { + return port, owner + } + } } return "", workerATIdentityReader{} } diff --git a/internal/device/ml307c_discovery_test.go b/internal/device/ml307c_discovery_test.go index 64e8cf93..81a3d425 100644 --- a/internal/device/ml307c_discovery_test.go +++ b/internal/device/ml307c_discovery_test.go @@ -117,10 +117,10 @@ func TestML307CDiscoveryAndRebind(t *testing.T) { t.Fatalf("unowned failed read retained a cached IMEI: %q, %v", active.IMEI, handled) } - origProbe := probeProfileIMEICachedFn - t.Cleanup(func() { probeProfileIMEICachedFn = origProbe }) + origProbe := probeProfileIMEIFn + t.Cleanup(func() { probeProfileIMEIFn = origProbe }) var probed []string - probeProfileIMEICachedFn = func(profile modem.ATProfile, _ context.Context, port string, _ time.Duration) (string, error) { + probeProfileIMEIFn = func(profile modem.ATProfile, _ context.Context, port string, _ time.Duration) (string, error) { if profile != modem.ATProfileML307C { t.Fatalf("IMEI probe profile = %v", profile) } @@ -244,10 +244,19 @@ func TestML307CBootstrapRejectsUnreadableIdentityOnConfiguredPort(t *testing.T) return dev, "" } + prevStart := startWorkerModem + t.Cleanup(func() { startWorkerModem = prevStart }) + startWorkerModem = func(m *modem.Manager, expected string) error { + if m.ATProfile() != modem.ATProfileML307C || m.ATPort() != port || expected != cfg.ModemIMEI { + t.Fatalf("unreadable discovered port lost its startup identity gate: port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected) + } + return errors.New("无法验证") + } + p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}}) t.Cleanup(p.cancel) worker, err := p.AddWorkerFromConfig(cfg) - if worker != nil || err == nil || !strings.Contains(err.Error(), "未找到匹配的非 QMI 硬件") || probes != 1 { + if worker != nil || err == nil || !strings.Contains(err.Error(), "无法验证") || probes != 1 { t.Fatalf("unverified ML307C port did not block startup: worker=%v err=%v probes=%d", worker, err, probes) } } @@ -291,3 +300,119 @@ func TestML307CRescanKeepsHealthyOwnerWhenIMEIUnavailable(t *testing.T) { t.Fatalf("rescan retired the healthy owner after its identity query failed: %v", err) } } + +func TestBootstrapExplicitATIMEI(t *testing.T) { + const expectedIMEI = "490154203237518" + dir, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + port := filepath.Join(dir, "ttyUSB8") + if err := os.WriteFile(port, nil, 0o600); err != nil { + t.Fatal(err) + } + alias := filepath.Join(dir, "by-id") + if err := os.Symlink(port, alias); err != nil { + t.Fatal(err) + } + + prevFallback, prevLive, prevStart := discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem + t.Cleanup(func() { + discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem = prevFallback, prevLive, prevStart + }) + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + // The original ML307C is gone. An ordinary modem now has the same tty and USB path. + return []CompatibleModem{{ + USBPath: dir, VendorID: 0x2c7c, ProductID: 0x0125, + Mode: "at", ATPort: port, ATPorts: []string{port}, + }}, nil + } + probeProfileIMEIFn = func(modem.ATProfile, context.Context, string, time.Duration) (string, error) { + t.Fatal("explicit AT fallback opened a serial handle before manager startup") + return "", nil + } + + for _, tc := range []struct { + name, expected, wantError string + owned bool + }{ + {name: "same tty different vendor", expected: expectedIMEI, wantError: "实时 IMEI 与配置不匹配"}, + {name: "legacy configuration", wantError: "打开串口"}, + {name: "owned tty alias", expected: expectedIMEI, wantError: "已由现有设备接管", owned: true}, + } { + t.Run(tc.name, func(t *testing.T) { + startWorkerModem = func(m *modem.Manager, expected string) error { + if tc.owned || m.ATProfile() != modem.ATProfileDefault || m.ATPort() != alias || expected != tc.expected { + t.Fatalf("manager port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected) + } + return errors.New(tc.wantError) + } + + cfg := config.DeviceConfig{ID: "target", DeviceBackend: backend.BackendAT, ModemIMEI: tc.expected, USBPath: dir, ManagePort: alias} + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + if tc.owned { + existing := config.DeviceConfig{ID: "active", DeviceBackend: backend.BackendAT, ATPort: alias} + m, err := modem.New(existing) + if err != nil { + t.Fatal(err) + } + p.AttachWorkerForTest(&Worker{ID: existing.ID, Pool: p, Config: existing, Modem: m}) + } + worker, err := p.AddWorkerFromConfig(cfg) + if worker != nil || err == nil || !strings.Contains(err.Error(), tc.wantError) || p.GetWorker(cfg.ID) != nil { + t.Fatalf("worker=%v err=%v, want %q", worker, err, tc.wantError) + } + }) + } +} + +func TestBootstrapDiscoveryProbesOnceBeforeOpen(t *testing.T) { + const imei = "490154203237518" + port := filepath.Join(t.TempDir(), "ttyUSB8") + if err := os.WriteFile(port, nil, 0o600); err != nil { + t.Fatal(err) + } + cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: backend.BackendAT, ModemIMEI: imei} + prevFallback, prevLive, prevStart := discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem + t.Cleanup(func() { + discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem = prevFallback, prevLive, prevStart + }) + discoverFallbackModemsFn = func() ([]CompatibleModem, error) { + return []CompatibleModem{{ + USBPath: filepath.Dir(port), VendorID: cmIoTVendorID, ProductID: ml307cProductID, + Mode: "at", ATPort: port, ATPorts: []string{port}, + }}, nil + } + probes := 0 + probeProfileIMEIFn = func(profile modem.ATProfile, _ context.Context, path string, _ time.Duration) (string, error) { + probes++ + if profile != modem.ATProfileML307C || path != port { + t.Fatalf("probe profile = %v, path = %q", profile, path) + } + return imei, nil + } + + startWorkerModem = func(m *modem.Manager, expected string) error { + if m.ATPort() != port || m.ATProfile() != modem.ATProfileML307C || expected != imei { + t.Fatalf("strict discovery lost its startup identity gate: port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected) + } + return errors.New("实时 IMEI 与配置不匹配") + } + + for _, tc := range []struct{ name, path string }{ + {name: "explicit path", path: port}, + {name: "IMEI only"}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg.ATPort = tc.path + probes = 0 + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + worker, err := p.AddWorkerFromConfig(cfg) + if worker != nil || err == nil || !strings.Contains(err.Error(), "实时 IMEI 与配置不匹配") || probes != 1 { + t.Fatalf("worker=%v err=%v probes=%d, want startup to reach identity gate after one discovery probe", worker, err, probes) + } + }) + } +} diff --git a/internal/device/pool_bootstrap.go b/internal/device/pool_bootstrap.go index 9821d4bf..b4bcf364 100644 --- a/internal/device/pool_bootstrap.go +++ b/internal/device/pool_bootstrap.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "os" - "path/filepath" "strings" "sync/atomic" "time" @@ -154,37 +153,16 @@ func configuredDevicesATDiscovery(devices []config.DeviceConfig) compatibleATDis return scope } -func configuredPortRequiresLiveATIdentity(cfg config.DeviceConfig, observations []atScanObservation) bool { - if usb := strings.TrimSpace(cfg.USBPath); usb != "" { - profile := readUSBDeviceIdentity(resolveUSBPathForScan(usb)).atProfile() - if atDeviceRulesFor(profile).verifyLiveIMEI { - return true - } +func configuredATPort(cfg config.DeviceConfig) string { + if port := strings.TrimSpace(cfg.ATPort); port != "" { + return port } - for _, port := range []string{cfg.ATPort, cfg.ManagePort} { - port = strings.TrimSpace(port) - if port == "" { - continue - } - if target, err := filepath.EvalSymlinks(port); err == nil { - port = target - } - for _, observation := range observations { - if containsPort(observation.atPorts, port) { - return true - } - } - } - return false + return strings.TrimSpace(cfg.ManagePort) } -// configuredATDevice finds the explicitly selected port before a legacy config -// has learned its IMEI. Keep the real port for runtime ownership checks. +// configuredATDevice finds which USB device owns the explicitly selected port. func configuredATDevice(cfg config.DeviceConfig) (CompatibleModem, bool) { - port := strings.TrimSpace(cfg.ATPort) - if port == "" { - port = strings.TrimSpace(cfg.ManagePort) - } + port := configuredATPort(cfg) if port == "" { return CompatibleModem{}, false } @@ -269,6 +247,8 @@ type apduArbiterAwareTransport interface { SetAPDUArbiter(arbiter *apduarbiter.Arbiter) } +var startWorkerModem = (*modem.Manager).StartWithExpectedIMEI + func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) { p.mu.Lock() if _, exists := p.workers[devCfg.ID]; exists { @@ -330,6 +310,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) var matched *QMIDevice var atProfile modem.ATProfile + explicitATIdentity := configuredATPort(devCfg) != "" && strings.TrimSpace(devCfg.ModemIMEI) != "" discoveryCache := &qmiBootstrapDiscoveryCache{} liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false) configuredIndex := BuildConfiguredDeviceIndex(config.ListDevices()) @@ -338,14 +319,18 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) if scan == compatibleATDiscoveryNone && configuredDevicesATDiscovery(config.ListDevices()) == compatibleATDiscoveryAll { scan = compatibleATDiscoveryAll } - atIMEIConfigured := resolvedBackendMode(devCfg) == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) != "" - hardware, atObservations := p.collectRescanHardware(nil, liveWorkerIndex, scan) + hardware, _ := p.collectRescanHardware(nil, liveWorkerIndex, scan) resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg}) if len(resolved.Matched) > 0 { hw := resolved.Matched[0].Hardware atProfile = hw.ATProfile() if atDeviceRulesFor(atProfile).verifyLiveIMEI { + if resolvedBackendMode(devCfg) == backend.BackendAT { + if port, _ := liveWorkerIndex.ownedATPort(hw.ATPorts); port != "" { + return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port) + } + } devCfg.USBPath = hw.USBPath devCfg.ATPort = hw.ATPort devCfg.ManagePort = hw.ATPort @@ -368,8 +353,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) devCfg.ModemIMEI = resolved.Matched[0].BackfillIMEI logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI) } - } else if (strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ManagePort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "") || - (atIMEIConfigured && configuredPortRequiresLiveATIdentity(devCfg, atObservations)) { + } else if configuredATPort(devCfg) == "" && strings.TrimSpace(devCfg.ControlDevice) == "" { return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") } } else if hasManagedQMINetwork(devCfg) { @@ -443,15 +427,24 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) } backendMode := resolvedBackendMode(devCfg) - if backendMode == backend.BackendAT && strings.TrimSpace(devCfg.ModemIMEI) == "" && atProfile == modem.ATProfileDefault { + if backendMode == backend.BackendAT && atProfile == modem.ATProfileDefault && + (strings.TrimSpace(devCfg.ModemIMEI) == "" || explicitATIdentity) { + ports := []string{configuredATPort(devCfg)} if hw, ok := configuredATDevice(devCfg); ok { atProfile = hw.ATProfile() + ports = hw.ATPorts if atDeviceRulesFor(atProfile).verifyLiveIMEI { - if port, _ := liveWorkerIndex.ownedATPort(hw.ATPorts); port != "" { - return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port) - } devCfg.USBPath, devCfg.ATPort, devCfg.ManagePort = hw.USBPath, hw.ATPort, hw.ATPort } + } else if usb := resolveUSBPathForScan(devCfg.USBPath); explicitATIdentity && usb != "" && + atDeviceRulesFor(readUSBDeviceIdentity(usb).atProfile()).verifyLiveIMEI { + // The selected path is not a recognized AT interface of the attached modem. + return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动") + } + if explicitATIdentity || atDeviceRulesFor(atProfile).verifyLiveIMEI { + if port, _ := liveWorkerIndex.ownedATPort(ports); port != "" { + return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port) + } } } m, err := newWorkerModem(devCfg, backendMode, atProfile) @@ -692,7 +685,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) } logger.Info(fmt.Sprintf("[%s] 短信模式已配置", w.ID), "sms_mode", w.smsMode.String(), "backend", backendMode) - if err := m.Start(); err != nil { + expectedOpenedIMEI := "" + if backendMode == backend.BackendAT && (explicitATIdentity || atDeviceRulesFor(atProfile).verifyLiveIMEI) { + expectedOpenedIMEI = strings.TrimSpace(devCfg.ModemIMEI) + } + if err := startWorkerModem(m, expectedOpenedIMEI); err != nil { if qmiTransportLifecycle != nil { _ = qmiTransportLifecycle.Stop() } diff --git a/internal/modem/imei_cache_test.go b/internal/modem/imei_cache_test.go index b97ea61c..e250eb43 100644 --- a/internal/modem/imei_cache_test.go +++ b/internal/modem/imei_cache_test.go @@ -15,8 +15,8 @@ func TestIMEICacheRejectsReusedSerialNode(t *testing.T) { if err != nil { t.Fatal(err) } - storeCachedIMEIForProfile(path, "111111111111111", node, ATProfileDefault) - if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "111111111111111" { + storeCachedIMEI(path, "111111111111111", node) + if got := loadCachedIMEI(path); got != "111111111111111" { t.Fatalf("cache = %q", got) } // Keep the old inode alive so this models replacement rather than inode reuse. @@ -26,11 +26,11 @@ func TestIMEICacheRejectsReusedSerialNode(t *testing.T) { if err := os.WriteFile(path, nil, 0600); err != nil { t.Fatal(err) } - if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "" { + if got := loadCachedIMEI(path); got != "" { t.Fatalf("reused port retained identity %q", got) } - storeCachedIMEIForProfile(path, "111111111111111", node, ATProfileDefault) - if got := loadCachedIMEIForProfile(path, ATProfileDefault); got != "" { + storeCachedIMEI(path, "111111111111111", node) + if got := loadCachedIMEI(path); got != "" { t.Fatalf("late probe poisoned new node: %q", got) } } diff --git a/internal/modem/imei_probe.go b/internal/modem/imei_probe.go index 51c7f8ff..b8145c76 100644 --- a/internal/modem/imei_probe.go +++ b/internal/modem/imei_probe.go @@ -3,20 +3,21 @@ package modem import ( "context" "errors" + "fmt" "os" "strings" "sync" "time" + "github.com/yibaiba/hideck/internal/config" "go.bug.st/serial" ) // imeiCacheItem 存储 IMEI 缓存条目及对应的获取时间戳 type imeiCacheItem struct { - IMEI string - TS time.Time - Node os.FileInfo - Profile ATProfile + IMEI string + TS time.Time + Node os.FileInfo } // imeiCache 提供线程安全的内存 IMEI 映射缓存,避免频繁通过串口发起硬件查询 @@ -32,10 +33,6 @@ func ProbeIMEICached(atPort string, timeout time.Duration) (string, error) { // ProbeIMEICachedContext 提供可取消的缓存 IMEI 探测。 func ProbeIMEICachedContext(ctx context.Context, atPort string, timeout time.Duration) (string, error) { - return ATProfileDefault.ProbeIMEICached(ctx, atPort, timeout) -} - -func (profile ATProfile) ProbeIMEICached(ctx context.Context, atPort string, timeout time.Duration) (string, error) { atPort = strings.TrimSpace(atPort) if atPort == "" { return "", errors.New("empty at port") @@ -44,30 +41,30 @@ func (profile ATProfile) ProbeIMEICached(ctx context.Context, atPort string, tim ctx = context.Background() } - if imei := loadCachedIMEIForProfile(atPort, profile); imei != "" { + if imei := loadCachedIMEI(atPort); imei != "" { return imei, nil } node, _ := os.Stat(atPort) - imei, err := profile.probeIMEI(ctx, atPort, timeout) + imei, err := ProbeIMEIContext(ctx, atPort, timeout) if err == nil && imei != "" { - storeCachedIMEIForProfile(atPort, imei, node, profile) + storeCachedIMEI(atPort, imei, node) } return imei, err } -func loadCachedIMEIForProfile(atPort string, profile ATProfile) string { +func loadCachedIMEI(atPort string) string { imeiCache.mu.RLock() defer imeiCache.mu.RUnlock() item, ok := imeiCache.m[atPort] node, err := os.Stat(atPort) - if !ok || item.Profile != profile || item.IMEI == "" || time.Since(item.TS) >= 10*time.Minute || err != nil || item.Node == nil || !os.SameFile(item.Node, node) || !item.Node.ModTime().Equal(node.ModTime()) { + if !ok || item.IMEI == "" || time.Since(item.TS) >= 10*time.Minute || err != nil || item.Node == nil || !os.SameFile(item.Node, node) || !item.Node.ModTime().Equal(node.ModTime()) { return "" } return item.IMEI } -func storeCachedIMEIForProfile(atPort, imei string, node os.FileInfo, profile ATProfile) { +func storeCachedIMEI(atPort, imei string, node os.FileInfo) { current, err := os.Stat(atPort) if err != nil || node == nil || !os.SameFile(node, current) || !node.ModTime().Equal(current.ModTime()) { return @@ -77,7 +74,7 @@ func storeCachedIMEIForProfile(atPort, imei string, node os.FileInfo, profile AT if imeiCache.m == nil { imeiCache.m = make(map[string]imeiCacheItem) } - imeiCache.m[atPort] = imeiCacheItem{IMEI: imei, TS: time.Now(), Node: node, Profile: profile} + imeiCache.m[atPort] = imeiCacheItem{IMEI: imei, TS: time.Now(), Node: node} } // ProbeIMEI 通过打开底层 TTY 串口设备并执行 `AT+CGSN` 指令来实时探测模组的 IMEI 串号 @@ -87,10 +84,11 @@ func ProbeIMEI(atPort string, timeout time.Duration) (string, error) { // ProbeIMEIContext 在取消时主动关闭串口,避免 USB 重枚举期间阻塞设备恢复。 func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) (string, error) { - return ATProfileDefault.probeIMEI(ctx, atPort, timeout) + return ATProfileDefault.ProbeIMEI(ctx, atPort, timeout) } -func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout time.Duration) (string, error) { +// ProbeIMEI reads the current IMEI with the selected AT dialect and bypasses the cache. +func (profile ATProfile) ProbeIMEI(ctx context.Context, atPort string, timeout time.Duration) (string, error) { atPort = strings.TrimSpace(atPort) if atPort == "" { return "", errors.New("empty at port") @@ -112,7 +110,7 @@ func (profile ATProfile) probeIMEI(ctx context.Context, atPort string, timeout t probeCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - p, err := openIMEISerialPort(probeCtx, atPort, mode) + p, err := openIMEISerialPortFn(probeCtx, atPort, mode) if err != nil { return "", err } @@ -170,6 +168,8 @@ type imeiSerialOpenResult struct { err error } +var openIMEISerialPortFn = openIMEISerialPort + func openIMEISerialPort(ctx context.Context, atPort string, mode *serial.Mode) (serial.Port, error) { result := make(chan imeiSerialOpenResult, 1) go func() { @@ -199,3 +199,65 @@ func closeIMEISerialPortOnCancel(ctx context.Context, port serial.Port, stop <-c case <-stop: } } + +// verifyOpenedIMEI consumes the entire identity reply before the manager starts +// reading URCs or issuing initialization commands on this handle. +func (m *Manager) verifyOpenedIMEI(expected string) error { + live, err := readOpenedIMEI(m.port, m.atProfile.dialect(), 1200*time.Millisecond) + if err != nil { + return fmt.Errorf("无法验证 AT 口 %s 的实时 IMEI: %w", m.atPort, err) + } + if !config.IMEIMatches(live, expected) { + return fmt.Errorf("AT 口 %s 的实时 IMEI 与配置不匹配", m.atPort) + } + return nil +} + +func readOpenedIMEI(port serial.Port, dialect *atDialect, timeout time.Duration) (string, error) { + if err := port.SetReadTimeout(80 * time.Millisecond); err != nil { + return "", err + } + if err := port.ResetInputBuffer(); err != nil { + return "", err + } + cmd := dialect.imei.command + "\r\n" + n, err := port.Write([]byte(cmd)) + if err != nil { + return "", err + } + if n != len(cmd) { + return "", errors.New("incomplete IMEI command write") + } + + deadline := time.Now().Add(timeout) + var response strings.Builder + var pending string + buf := make([]byte, 1024) + for time.Now().Before(deadline) { + n, err := port.Read(buf) + if err != nil { + return "", err + } + pending += string(buf[:n]) + for { + line, rest, complete := strings.Cut(pending, "\n") + if !complete { + break + } + pending = rest + line = strings.TrimSpace(line) + switch { + case line == "OK": + imei := dialect.imei.parse(response.String()) + if imei == "" { + return "", errors.New("empty IMEI response") + } + return imei, nil + case line == "ERROR" || strings.HasPrefix(line, "+CME ERROR:") || strings.HasPrefix(line, "+CMS ERROR:"): + return "", fmt.Errorf("IMEI query failed: %s", line) + } + response.WriteString(line + "\n") + } + } + return "", errors.New("imei probe timeout") +} diff --git a/internal/modem/imei_probe_test.go b/internal/modem/imei_probe_test.go new file mode 100644 index 00000000..57e89c3f --- /dev/null +++ b/internal/modem/imei_probe_test.go @@ -0,0 +1,157 @@ +package modem + +import ( + "context" + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yibaiba/hideck/internal/config" + "go.bug.st/serial" +) + +type imeiProbeSerialPort struct { + serial.Port + reply *strings.Reader + written []string +} + +func (p *imeiProbeSerialPort) SetReadTimeout(time.Duration) error { return nil } +func (p *imeiProbeSerialPort) Close() error { return nil } +func (p *imeiProbeSerialPort) Read(b []byte) (int, error) { return p.reply.Read(b) } +func (p *imeiProbeSerialPort) Write(b []byte) (int, error) { + p.written = append(p.written, string(b)) + return len(b), nil +} + +func TestLiveIMEIProbeBypassesCacheForUnchangedTTYNode(t *testing.T) { + path := filepath.Join(t.TempDir(), "ttyUSB8") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + node, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + const cachedIMEI, replacementIMEI = "490154203237518", "490154203237526" + t.Cleanup(func() { + imeiCache.mu.Lock() + delete(imeiCache.m, path) + imeiCache.mu.Unlock() + }) + storeCachedIMEI(path, cachedIMEI, node) + + serialPort := &imeiProbeSerialPort{reply: strings.NewReader("\r\n+CGSN: " + replacementIMEI + "\r\n\r\nOK\r\n")} + origOpen := openIMEISerialPortFn + t.Cleanup(func() { openIMEISerialPortFn = origOpen }) + openIMEISerialPortFn = func(_ context.Context, port string, _ *serial.Mode) (serial.Port, error) { + if port != path { + t.Fatalf("probe opened %q, want %q", port, path) + } + return serialPort, nil + } + live, err := ATProfileML307C.ProbeIMEI(context.Background(), path, time.Second) + if err != nil || live != replacementIMEI { + t.Fatalf("live probe = %q, %v", live, err) + } + if want := []string{"AT\r\n", "AT+CGSN=1\r\n"}; !reflect.DeepEqual(serialPort.written, want) { + t.Fatalf("AT commands = %q, want %q", serialPort.written, want) + } + + cached, err := ProbeIMEICached(path, time.Second) + if err != nil || cached != cachedIMEI || len(serialPort.written) != 2 { + t.Fatalf("default cached probe = %q, %v, commands %q", cached, err, serialPort.written) + } +} + +type openedIMEISerialPort struct { + failingSerialPort + response []string + commands atomic.Int32 + terminalRead atomic.Bool + inputFlushed bool + earlyInit atomic.Bool +} + +func (p *openedIMEISerialPort) ResetInputBuffer() error { + p.inputFlushed = true + return nil +} + +func (p *openedIMEISerialPort) Write(b []byte) (int, error) { + if p.commands.Add(1) == 1 { + if !p.inputFlushed || string(b) != "AT+CGSN=1\r\n" { + return 0, errors.New("expected IMEI command after flushing stale input") + } + return len(b), nil + } + if !p.terminalRead.Load() { + p.earlyInit.Store(true) + } + return 0, errors.New("fake device stops after IMEI") +} + +func (p *openedIMEISerialPort) Read(b []byte) (int, error) { + if len(p.response) == 0 { + time.Sleep(time.Millisecond) + return 0, nil + } + part := p.response[0] + p.response = p.response[1:] + if part == "\n" { + p.terminalRead.Store(true) + } + return copy(b, part), nil +} + +func TestManagerVerifiesTheOpenedPortBeforeATInitialization(t *testing.T) { + const expected = "490154203237518" + original := openManagerSerialPort + t.Cleanup(func() { openManagerSerialPort = original }) + for _, tc := range []struct { + name, live, wantError string + }{ + {name: "matched", live: expected}, + {name: "replacement", live: "490154203237526", wantError: "实时 IMEI 与配置不匹配"}, + {name: "unreadable", wantError: "无法验证"}, + } { + t.Run(tc.name, func(t *testing.T) { + m, err := NewWithATProfile(config.DeviceConfig{ + ID: "imei-gate", DeviceBackend: "at", ATPort: filepath.Join(t.TempDir(), "ttyUSB8"), + }, ATProfileML307C) + if err != nil { + t.Fatal(err) + } + port := &openedIMEISerialPort{response: []string{"+CGSN: " + tc.live + "\r\n", "OK\r", "\n"}} + opens := 0 + openManagerSerialPort = func(string, *serial.Mode) (serial.Port, error) { + opens++ + if opens == 1 { + return nil, errors.New("device or resource busy") + } + return port, nil + } + err = m.StartWithExpectedIMEI(expected) + if opens != 2 || !port.terminalRead.Load() || port.earlyInit.Load() { + m.Stop() + t.Fatalf("opens=%d terminalRead=%v earlyInit=%v", opens, port.terminalRead.Load(), port.earlyInit.Load()) + } + if tc.wantError != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantError) || !port.closed.Load() || + m.CanExecuteAT() || port.commands.Load() != 1 { + t.Fatalf("err=%v closed=%v running=%v commands=%d", err, port.closed.Load(), m.CanExecuteAT(), port.commands.Load()) + } + return + } + defer m.Stop() + if err != nil || !m.CanExecuteAT() || port.closed.Load() { + t.Fatalf("err=%v running=%v closed=%v", err, m.CanExecuteAT(), port.closed.Load()) + } + }) + } +} diff --git a/internal/modem/manager.go b/internal/modem/manager.go index 91a4031a..33bbcb5f 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -522,6 +522,11 @@ func (m *Manager) tripATTimeoutWatchdog(cmd string, failures int) { // Start 启动 AT 管理器的后台协程 func (m *Manager) Start() error { + return m.StartWithExpectedIMEI("") +} + +// StartWithExpectedIMEI verifies the opened AT port before modem initialization. +func (m *Manager) StartWithExpectedIMEI(expected string) error { m.startStopMu.Lock() defer m.startStopMu.Unlock() select { @@ -544,7 +549,7 @@ func (m *Manager) Start() error { var err error for attempt := 0; attempt < 8; attempt++ { - m.port, err = serial.Open(m.atPort, m.portMode) + m.port, err = openManagerSerialPort(m.atPort, m.portMode) if err == nil { break } @@ -557,6 +562,13 @@ func (m *Manager) Start() error { return fmt.Errorf("打开串口 %s 失败: %w", m.atPort, err) } + if expected != "" { + if err := m.verifyOpenedIMEI(expected); err != nil { + _ = m.port.Close() + m.port = nil + return err + } + } m.port.SetReadTimeout(100 * time.Millisecond) m.setRunning(true) @@ -593,6 +605,8 @@ func (m *Manager) Start() error { return nil } +var openManagerSerialPort = serial.Open + func isRetryableSerialOpenErr(err error) bool { if err == nil { return false From f2cf1c9f3be9d87ee739ee6686079ca63ce09528 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:41:00 +0800 Subject: [PATCH 28/39] fix(sms): isolate store failures and recheck deletion receipts --- internal/device/sms_at_inbox.go | 9 ++- internal/device/sms_at_inbox_test.go | 46 ++++++++++++++++ internal/modem/manager_sms_storage_test.go | 64 ++++++++++++++++++++++ internal/modem/sms_inbox.go | 7 ++- 4 files changed, 123 insertions(+), 3 deletions(-) diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index d8913a43..d2e6685a 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -250,7 +250,9 @@ func (w *Worker) readStoredSMSInbox(owner storedSMSOwner, notice *storedSMSNotic scanIncomplete := false for _, store := range storedSMSStores { if err := inbox.Select(store); err != nil { - return errors.Join(scanErr, err) + scanErr = errors.Join(scanErr, err) + scanIncomplete = true + continue } // Only notices already observed before this snapshot can identify // a listed PDU. A newer CMTI may refer to a reused slot. @@ -662,7 +664,10 @@ func (state *atSMSParts) commit(part atInboxPart, content string) (bool, *Inboun return false, nil, err } if !result.Created { - return true, nil, nil + // History dedup follows ICCID. Slot deletion also requires the + // receipt to attest the current IMSI. + found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, part.key) + return found, nil, err } return true, &InboundSMS{ DeviceID: state.scope.DeviceID, ICCID: state.scope.ICCID, IMSI: state.scope.IMSI, diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index 46f6317b..2fdc02b1 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -338,3 +338,49 @@ func TestATStoredSMSNoticeSurvivesReadFailure(t *testing.T) { t.Fatal("an old scan discarded a newer SIM generation's notice") } } + +func TestATStoredSMSDuplicateRequiresReceiptIMSIForDeletion(t *testing.T) { + initDevicePhoneNumberTestDB(t) + identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} + part, err := decodeATInboxPart(identity, "0004038177F7000862119121000000027532") + if err != nil || part.Concat.IsConcat || part.Content != "甲" { + t.Fatalf("single PDU fixture = %+v, %v", part, err) + } + scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} + original, err := loadATSMSParts(scope) + if err != nil { + t.Fatal(err) + } + if stored, inbound, err := original.persist(part, true); err != nil || !stored || inbound == nil { + t.Fatalf("initial persist = %t, %+v, %v", stored, inbound, err) + } + scope.IMSI = "001010123456788" + changed, err := loadATSMSParts(scope) + if err != nil { + t.Fatal(err) + } + assertRetry := func(state *atSMSParts, sourceKnown, wantDelete bool) { + t.Helper() + if stored, inbound, err := state.persist(part, sourceKnown); err != nil || stored != wantDelete || inbound != nil { + t.Fatalf("replay persist = %t, %+v, %v, want delete=%t", stored, inbound, err, wantDelete) + } + } + assertRetry(changed, true, false) + assertRetry(original, true, true) + + var row db.SMS + if err := db.DB.Where("iccid = ? AND fragment_session_key = ?", identity.ICCID, part.key).First(&row).Error; err != nil { + t.Fatal(err) + } + if _, _, _, err := db.DeleteSMSByID(row.ID); err != nil { + t.Fatal(err) + } + assertRetry(changed, true, false) + assertRetry(changed, false, false) + assertRetry(original, true, true) + assertRetry(original, false, true) + var count int64 + if err := db.DB.Model(&db.SMS{}).Where("iccid = ?", identity.ICCID).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("replay recreated removed history: count=%d, err=%v", count, err) + } +} diff --git a/internal/modem/manager_sms_storage_test.go b/internal/modem/manager_sms_storage_test.go index 06f5185e..dd3f8aa9 100644 --- a/internal/modem/manager_sms_storage_test.go +++ b/internal/modem/manager_sms_storage_test.go @@ -196,3 +196,67 @@ func TestReadSMSRetainsMessageWhenProcessorFails(t *testing.T) { t.Fatalf("commands=%v, want read without delete", commands) } } + +func TestML307CSMSInboxRecoversOtherStoreAfterSelectionFailure(t *testing.T) { + m := newRunningTestManager(t) + m.SetStoredSMSHandler(func(_, _ string) {}) + m.atProfile = ATProfileML307C + const ( + pdu = "0004038177F7000862119121000000027532" + initial = `+CPMS: "SM",1,10,"ME",1,180,"ME",1,180` + ) + selectErr := errors.New("ME selection failed") + done := make(chan []string, 1) + go func() { + selection := initial + done <- respondToCommands(t, m, 8, func(req commandRequest) { + switch req.cmd { + case "AT+CPMS?": + req.respChan <- selection + case `AT+CPMS="ME","ME","ME"`: + // The modem changed its read location despite returning an error. + selection = `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180` + req.errChan <- selectErr + case `AT+CPMS="SM","SM","SM"`: + selection = `+CPMS: "SM",1,10,"SM",1,10,"SM",1,10` + req.respChan <- "OK" + case "AT+CMGL=4": + if selection != `+CPMS: "SM",1,10,"SM",1,10,"SM",1,10` { + req.errChan <- errors.New("listed the wrong store") + return + } + req.respChan <- "+CMGL: 7,0,,17\n" + pdu + case `AT+CPMS="SM","ME","ME"`: + selection = initial + req.respChan <- "OK" + default: + req.errChan <- errors.New("unexpected command " + req.cmd) + } + }) + }() + + err := m.WithSMSInbox(func(inbox *SMSInbox) error { + err := inbox.Select("ME") + if !errors.Is(err, selectErr) { + t.Fatalf("ME selection error = %v", err) + } + if err := inbox.Select("SM"); err != nil { + t.Fatal(err) + } + records, err := inbox.List() + if err != nil || len(records) != 1 || records[0].PDU != pdu || !records[0].Received() { + t.Fatalf("SM records = %+v, %v", records, err) + } + return selectErr + }) + if !errors.Is(err, selectErr) { + t.Fatalf("WithSMSInbox() error = %v", err) + } + want := []string{ + "AT+CPMS?", `AT+CPMS="ME","ME","ME"`, "AT+CPMS?", `AT+CPMS="SM","SM","SM"`, + "AT+CPMS?", "AT+CMGL=4", `AT+CPMS="SM","ME","ME"`, "AT+CPMS?", + } + if got := <-done; !reflect.DeepEqual(got, want) { + t.Fatalf("commands = %v, want %v", got, want) + } +} diff --git a/internal/modem/sms_inbox.go b/internal/modem/sms_inbox.go index 03d7d065..b039e5f5 100644 --- a/internal/modem/sms_inbox.go +++ b/internal/modem/sms_inbox.go @@ -85,7 +85,12 @@ func (inbox *SMSInbox) Select(storage string) error { return fmt.Errorf("unsupported SMS read store %q", storage) } if inbox.current == nil { - return errors.New("CPMS selection failed in this transaction") + // A failed CPMS may still have changed one or more locations. + actual, err := inbox.modem.smsStorageSelection() + if err != nil { + return err + } + inbox.current = actual } if inbox.current[0] == storage { return nil From fea491cd65376842ea9767765fca61ac307765fb Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 20:53:01 +0800 Subject: [PATCH 29/39] fix(device): converge strict SIM identity before using the card --- internal/device/outbound_limits_test.go | 52 +++++++++ internal/device/phone_mode_test.go | 3 + internal/device/policy_owner.go | 4 + internal/device/pool.go | 38 ++++-- internal/device/pool_sms.go | 9 +- internal/device/sim_removal.go | 50 +++++++- internal/device/sim_removal_test.go | 149 +++++++++++++++++++++++- internal/device/sms_at_inbox.go | 33 ++++-- internal/device/sms_at_inbox_test.go | 79 +++++++++++++ internal/device/sms_identity.go | 72 ++++++++++++ internal/device/vowifi_sms_send.go | 2 +- 11 files changed, 463 insertions(+), 28 deletions(-) diff --git a/internal/device/outbound_limits_test.go b/internal/device/outbound_limits_test.go index 8b430658..c6d6e31f 100644 --- a/internal/device/outbound_limits_test.go +++ b/internal/device/outbound_limits_test.go @@ -11,6 +11,7 @@ import ( "github.com/iniwex5/vowifi-go/runtimehost/messaging" "github.com/iniwex5/vowifi-go/runtimehost/voicehost" "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/modem" "github.com/yibaiba/hideck/internal/outbound" "github.com/yibaiba/hideck/pkg/smscodec" ) @@ -143,3 +144,54 @@ func TestQueuedSMSSIMReplacementStopsBeforeNewRuntimeSend(t *testing.T) { t.Fatalf("queued send crossed SIM: err=%v sent=%d", err, newRuntime.sendCount()) } } + +func TestML307CCSSMSChecksLiveSIMBeforeSubmitting(t *testing.T) { + for _, tc := range []struct { + name string + iccid, imsi string + simErr, want error + simAbsent bool + }{ + {name: "matching", iccid: "card-old", imsi: "imsi-old"}, + {name: "different_card", iccid: "card-new", imsi: "imsi-new", want: ErrSMSIdentityConflict}, + {name: "same_iccid_different_imsi", iccid: "card-old", imsi: "imsi-new", want: ErrSMSIdentityConflict}, + {name: "incomplete", iccid: "card-old", want: ErrSMSIdentityUnknown}, + {name: "absent", simAbsent: true, want: ErrSMSIdentityUnknown}, + {name: "pin_required", iccid: "card-old", imsi: "imsi-old", simErr: modem.ErrSIMPINRequired, want: modem.ErrSIMPINRequired}, + } { + t.Run(tc.name, func(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + limiter := &recordingOutboundLimiter{} + p.SetOutboundLimiter(limiter) + be.liveICCID, be.liveIMSI, be.simErr, be.simAbsent = tc.iccid, tc.imsi, tc.simErr, tc.simAbsent + if err := w.SendSMS("10010", "test"); !errors.Is(err, tc.want) { + t.Fatalf("SendSMS() = %v, want %v", err, tc.want) + } + count := 0 + if tc.want == nil { + count = 1 + } + if be.sends != count || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" { + t.Fatalf("sends=%d want %d; charges=%+v want one on intended card", be.sends, count, limiter.requests) + } + if tc.want != nil && !w.SIMIdentityConvergenceMatches("", 0) { + t.Fatal("confirmed SIM state did not invalidate cached readiness") + } + }) + } +} + +func TestML307CCSSMSRejectsSilentSIMSwapDuringAuthorization(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + be.liveICCID, be.liveIMSI = "card-old", "imsi-old" + limiter := &recordingOutboundLimiter{after: func() { + be.liveICCID, be.liveIMSI = "card-new", "imsi-new" + }} + p.SetOutboundLimiter(limiter) + if err := w.SendSMS("10010", "test"); !errors.Is(err, ErrSMSIdentityConflict) { + t.Fatalf("SendSMS() = %v, want SIM conflict", err) + } + if be.sends != 0 || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" { + t.Fatalf("wrong send or quota owner: sends=%d charges=%+v", be.sends, limiter.requests) + } +} diff --git a/internal/device/phone_mode_test.go b/internal/device/phone_mode_test.go index 7befbae1..b813aa68 100644 --- a/internal/device/phone_mode_test.go +++ b/internal/device/phone_mode_test.go @@ -78,6 +78,7 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { t.Cleanup(p.cancel) w := p.GetWorker("ml307c") w.Modem = newML307CPhoneTestModem(t, w.ID) + w.state.Identity.Phase = simIdentityPhaseReady radio := &esimSwitchRestoreBackendStub{mode: backend.BackendAT, getMode: backend.ModeOnline} w.Backend = radio pol := cardpolicy.Policy{ @@ -124,6 +125,7 @@ func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) { t.Cleanup(p.cancel) w := p.GetWorker("ml307c") w.Modem = newML307CPhoneTestModem(t, w.ID) + w.state.Identity.Phase = simIdentityPhaseReady p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ ICCID: w.CurrentICCID(), PhoneMode: PhoneModeWiFi, VoWiFiEnabled: true, }}) @@ -156,6 +158,7 @@ func TestML307CLebaraSavedVoLTERecoversEffectiveWiFi(t *testing.T) { t.Cleanup(p.cancel) w := p.GetWorker("ml307c") w.Modem = newML307CPhoneTestModem(t, w.ID) + w.state.Identity.Phase = simIdentityPhaseReady pol := cardpolicy.Policy{ ICCID: w.CurrentICCID(), PhoneMode: PhoneModeVoLTE, VoWiFiEnabled: true, } diff --git a/internal/device/policy_owner.go b/internal/device/policy_owner.go index d3c01dbf..eedcc47c 100644 --- a/internal/device/policy_owner.go +++ b/internal/device/policy_owner.go @@ -60,6 +60,10 @@ func (p *Pool) validatePolicyOwner(owner policyOwner, transition *policyTransiti if strings.TrimSpace(identity.ICCID) != owner.iccid || identity.Generation != owner.identityGeneration { return errPolicyOwnerChanged } + if w.atDeviceRules().strictSIMIdentity && (!identity.Ready || identity.Phase != simIdentityPhaseReady || + strings.TrimSpace(identity.ICCID) == "" || strings.TrimSpace(identity.IMSI) == "") { + return errPolicyOwnerChanged + } p.switchMu.Lock() switching, snapshot := p.switchingDevices[w.ID], p.switchContexts[w.ID] p.switchMu.Unlock() diff --git a/internal/device/pool.go b/internal/device/pool.go index e5fcae30..11fe3330 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -685,19 +685,20 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str } strictSIMIdentity := w.atDeviceRules().strictSIMIdentity + var generation uint64 + if strictSIMIdentity { + generation = w.SIMIdentityGeneration() + } if strictSIMIdentity && !presenceConfirmed { - generation := w.SIMIdentityGeneration() inserted, err := w.Backend.IsSimInserted(ctx) if err != nil { - if errors.Is(err, modem.ErrSIMPINRequired) && (w.Pool == nil || !w.Pool.IsESIMSwitching(w.ID)) { - if w.markSIMPINRequired(generation) && w.Pool != nil { - owner := workerLifecycleOwner{worker: w, generation: w.generation} - w.Pool.handleSIMStatusEventForOwner(owner, reason, nil, "SIM PIN") - } + if errors.Is(err, modem.ErrSIMPINRequired) { + w.recordStrictSIMLock(generation, reason) } return liveSIMIdentityRefreshResult{}, err } if !inserted { + w.recordStrictSIMAbsence(generation, reason) return liveSIMIdentityRefreshResult{}, errATNoSIM } } @@ -708,6 +709,9 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str if snapshotReader, supported := w.Backend.(liveSIMIdentitySnapshotReader); supported { snapshot, err := snapshotReader.ReadSIMIdentityLive(ctx) if err != nil { + if strictSIMIdentity { + w.degradeStrictSIMIdentity(generation, reason, err) + } return liveSIMIdentityRefreshResult{}, err } iccid = strings.TrimSpace(snapshot.ICCID) @@ -749,7 +753,9 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str } } if strictSIMIdentity && (iccid == "" || imsi == "") { - return liveSIMIdentityRefreshResult{}, errors.New("live_identity_incomplete") + err := errors.New("live_identity_incomplete") + w.degradeStrictSIMIdentity(generation, reason, err) + return liveSIMIdentityRefreshResult{}, err } _, snapshotSupported := w.Backend.(liveSIMIdentitySnapshotReader) if !snapshotSupported && (simMetadata == nil || @@ -813,6 +819,10 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str now := time.Now() w.cacheMu.Lock() + if strictSIMIdentity && w.state.Identity.Generation != generation { + w.cacheMu.Unlock() + return liveSIMIdentityRefreshResult{}, ErrSMSIdentityTransitioning + } identityIncomplete := (iccid == "") != (imsi == "") hasCachedIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" || strings.TrimSpace(w.state.Identity.IMSI) != "" @@ -841,8 +851,10 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str (imsi != "" && imsi != strings.TrimSpace(w.state.Identity.IMSI)) // Physical swaps do not necessarily pass through the eSIM transition hook. // Retain a generation change even if the original ICCID later returns. - if iccid != "" && w.state.Identity.ICCID != "" && - normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID) { + iccidChanged := iccid != "" && w.state.Identity.ICCID != "" && + normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID) + if iccidChanged || (strictSIMIdentity && imsi != "" && w.state.Identity.IMSI != "" && + imsi != strings.TrimSpace(w.state.Identity.IMSI)) { w.state.Identity.Generation++ } if iccid != "" { @@ -1259,7 +1271,7 @@ func (p *Pool) confirmSIMStatusForOwner(owner workerLifecycleOwner, source strin p.finishConfirmedSIMInsertion(owner, source, result) return } - p.handleConfirmedSIMRemoval(owner, source, baseCtx) + p.handleConfirmedSIMRemoval(owner, source, baseCtx, generation) transition.Unlock() } @@ -1323,7 +1335,7 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st } // Caller holds the device policy transition lock. -func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context) { +func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context, generation uint64) { if !p.workerLifecycleOwnerCurrent(owner) { return } @@ -1332,7 +1344,9 @@ func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source stri refreshCtx, cancel := context.WithTimeout(baseCtx, 3*time.Second) _ = w.RefreshRuntime(refreshCtx, "sim_removed") cancel() - w.markSIMRemoved("sim_removed") + if !w.markSIMRemoved("sim_removed", generation) { + return + } p.detachPersistedSIMBinding(w) p.broadcastVoWiFiStateChange(deviceID) p.clearDesiredVoWiFiRecoverState(deviceID) diff --git a/internal/device/pool_sms.go b/internal/device/pool_sms.go index 106fd4f5..399269b5 100644 --- a/internal/device/pool_sms.go +++ b/internal/device/pool_sms.go @@ -410,10 +410,17 @@ func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitO } defer release() check := w.Pool.outboundOwnerCheck(w) + var intended SMSIdentity + if w.atDeviceRules().strictSIMIdentity { + intended, err = w.strictSMSSendIdentity() + if err != nil { + return err + } + } if err := w.Pool.authorizeSMS(context.Background(), outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts}); err != nil { return err } - if err := check(); err != nil { + if err := w.confirmCSSMSIdentity(context.Background(), intended, check); err != nil { return err } return w.sendSMSWithOptions(phone, message, opts) diff --git a/internal/device/sim_removal.go b/internal/device/sim_removal.go index ee764e4c..d0bdfdf3 100644 --- a/internal/device/sim_removal.go +++ b/internal/device/sim_removal.go @@ -11,15 +11,17 @@ import ( "github.com/yibaiba/hideck/pkg/logger" ) -func (w *Worker) markSIMRemoved(reason string) { - if w == nil { - return - } +func (w *Worker) markSIMRemoved(reason string, generation uint64) bool { now := time.Now() w.cacheMu.Lock() + defer w.cacheMu.Unlock() + strict := w.atDeviceRules().strictSIMIdentity + if strict && w.state.Identity.Generation != generation { + return false + } hadIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" || strings.TrimSpace(w.state.Identity.IMSI) != "" || w.state.Identity.Ready - if hadIdentity { + if hadIdentity || (strict && w.state.Identity.LastError != "sim_removed") { w.state.Identity.Generation++ } w.state.Identity.ICCID = "" @@ -35,7 +37,43 @@ func (w *Worker) markSIMRemoved(reason string) { w.state.Meta.IdentityUpdatedAt = now w.state.Meta.RuntimeUpdatedAt = now w.state.Meta.UpdatedAt = now - w.cacheMu.Unlock() + return true +} + +func (w *Worker) scheduleSIMStatusCheck(source string, inserted *bool, state string) { + if w.Pool == nil { + return + } + owner := workerLifecycleOwner{worker: w, generation: w.generation} + w.Pool.handleSIMStatusEventForOwner(owner, source, inserted, state) +} + +func (w *Worker) recordStrictSIMAbsence(generation uint64, source string) { + w.degradeStrictSIMIdentity(generation, source, errATNoSIM) + inserted := false + w.scheduleSIMStatusCheck(source, &inserted, "") +} + +func (w *Worker) recordStrictSIMLock(generation uint64, source string) { + if w.Pool != nil && w.Pool.IsESIMSwitching(w.ID) { + return + } + if w.markSIMPINRequired(generation) { + w.scheduleSIMStatusCheck(source, nil, "SIM PIN") + } +} + +func (w *Worker) degradeStrictSIMIdentity(generation uint64, reason string, err error) bool { + now := time.Now() + w.cacheMu.Lock() + defer w.cacheMu.Unlock() + if w.state.Identity.Generation != generation || !w.state.Identity.Ready || + w.state.Identity.Phase == simIdentityPhaseTransitioning { + return false + } + w.markSIMIdentityDegradedLocked(reason, err, now) + w.state.Identity.Generation++ + return true } func (w *Worker) markSIMPINRequired(generation uint64) bool { diff --git a/internal/device/sim_removal_test.go b/internal/device/sim_removal_test.go index 9d82c9b4..265ac8c6 100644 --- a/internal/device/sim_removal_test.go +++ b/internal/device/sim_removal_test.go @@ -2,6 +2,7 @@ package device import ( "context" + "errors" "testing" "time" @@ -178,14 +179,160 @@ func TestConfirmedSIMRemovalCancelsStartingVoWiFi(t *testing.T) { type ml307cSIMBackendStub struct { workerStartupIdentityBackendStub simErr error + simAbsent bool onSIMQuery func() + onICCID func() + sends int } func (s *ml307cSIMBackendStub) IsSimInserted(context.Context) (bool, error) { if s.onSIMQuery != nil { s.onSIMQuery() } - return s.simErr == nil, s.simErr + return !s.simAbsent && s.simErr == nil, s.simErr +} + +func (s *ml307cSIMBackendStub) GetICCIDLive(context.Context) (string, error) { + if s.onICCID != nil { + s.onICCID() + } + return s.liveICCID, nil +} + +func (s *ml307cSIMBackendStub) SendSMS(context.Context, string, string) error { + s.sends++ + return nil +} + +func newML307CIdentityWorker(t *testing.T) (*Pool, *Worker, *ml307cSIMBackendStub) { + t.Helper() + p := NewPool(&config.Config{}) + t.Cleanup(func() { _ = p.Shutdown() }) + cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"} + m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + be := &ml307cSIMBackendStub{} + w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be} + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"}) + p.AttachWorkerForTest(w) + t.Cleanup(func() { p.cancelWorkerLifecycleTimers(w.ID) }) + return p, w, be +} + +func TestML307CIncompleteReadyIdentityBlocksOldCardAndRetries(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + before := w.SIMIdentityGeneration() + be.liveICCID = "card-new" + p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test") + if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() <= before { + t.Fatal("incomplete live identity left the previous SIM ready") + } + p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ICCID: "card-old"}}) + if result := p.resolveAndApplyPolicy(w, "test"); result.Applied || !errors.Is(result.Err, errPolicyOwnerChanged) { + t.Fatalf("unready SIM applied cached policy: %+v", result) + } + p.SetPolicyResolver(nil) + be.liveIMSI = "imsi-new" + owner := p.captureWorkerLifecycleOwner(w.ID) + ready := true + p.handleSIMStatusEventForOwner(owner, "test", &ready, "") + p.simEventMu.Lock() + timer := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if timer == nil || !timer.Stop() { + t.Fatal("subsequent READY did not schedule an identity retry") + } + p.confirmSIMRemovedForOwner(owner, "test", timer) + if w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-new" || w.GetCachedIMSI() != "imsi-new" { + t.Fatal("subsequent READY did not settle on the new identity") + } + before = w.SIMIdentityGeneration() + be.liveIMSI = "imsi-rotated" + if err := w.RefreshIdentityLive(context.Background(), "test"); err != nil || w.SIMIdentityGeneration() <= before { + t.Fatalf("changed IMSI on a stable ICCID did not retire the old generation: %v", err) + } + + w.BeginSIMIdentityTransition("target", "test") + be.liveICCID, be.liveIMSI = "", "" + if err := w.RefreshIdentityLive(context.Background(), "test"); err == nil { + t.Fatal("incomplete identity unexpectedly succeeded during the switch") + } + w.cacheMu.RLock() + phase, target := w.state.Identity.Phase, w.state.Identity.TargetICCID + w.cacheMu.RUnlock() + if phase != simIdentityPhaseTransitioning || target != "target" { + t.Fatalf("incomplete read interrupted eSIM identity transition: phase=%s target=%s", phase, target) + } +} + +func TestML307CAbsentIdentityBlocksOldCardBeforeDebouncedCleanup(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + be.simAbsent = true + if err := w.RefreshIdentityLive(context.Background(), "test"); !errors.Is(err, errATNoSIM) { + t.Fatalf("absent SIM returned %v", err) + } + if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" { + t.Fatal("absent SIM should immediately become unready and keep its binding until confirmation") + } + p.simEventMu.Lock() + timer := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if timer == nil || !timer.Stop() { + t.Fatal("absent SIM did not schedule debounced cleanup") + } + p.confirmSIMRemovedForOwner(p.captureWorkerLifecycleOwner(w.ID), "test", timer) + if w.CurrentICCID() != "" { + t.Fatal("confirmed absence retained the previous identity") + } +} + +func TestML307CAbsentConfirmationDoesNotClearNewerSIM(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + be.simAbsent = true + be.onSIMQuery = func() { + w.cacheMu.Lock() + defer w.cacheMu.Unlock() + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}) + w.state.Identity.Generation++ + } + p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test") + if w.CurrentICCID() != "card-new" || w.SIMIdentityConvergenceMatches("", 0) { + t.Fatal("stale absence cleared the live SIM generation") + } +} + +func TestML307CSlowIdentityCannotReviveOlderSIMGeneration(t *testing.T) { + for _, before := range []bool{false, true} { + name := "probe_presence" + if before { + name = "confirmed_presence" + } + t.Run(name, func(t *testing.T) { + _, w, be := newML307CIdentityWorker(t) + be.liveICCID, be.liveIMSI = "card-old", "imsi-old" + started, finish := make(chan struct{}), make(chan struct{}) + be.onICCID = func() { + close(started) + <-finish + } + done := make(chan error, 1) + go func() { + _, err := w.refreshIdentityLiveWithPresence(context.Background(), "old-read", before) + done <- err + }() + <-started + generation := w.BeginSIMIdentityTransition("target", "test") + close(finish) + if err := <-done; !errors.Is(err, ErrSMSIdentityTransitioning) { + t.Fatalf("superseded identity read returned %v", err) + } + if !w.SIMIdentityConvergenceMatches("target", generation) || currentSIMOwnership(w).iccid != "" { + t.Fatal("superseded read reset the current identity transition") + } + }) + } } func confirmScheduledSIMPIN(t *testing.T, p *Pool, owner workerLifecycleOwner) { diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index d2e6685a..b1aaeb72 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -54,30 +54,49 @@ func (owner storedSMSOwner) check() error { return nil } +type storedSMSIdentityReader interface { + QuerySIMInserted() (bool, error) + QueryICCID() (string, error) + QueryIMSI() (string, error) +} + func (owner storedSMSOwner) verifyLive() error { + return owner.verifyLiveFrom(owner.worker.Modem) +} + +func (owner storedSMSOwner) verifyLiveFrom(reader storedSMSIdentityReader) error { if err := owner.check(); err != nil { return err } - w := owner.worker - inserted, err := w.Modem.QuerySIMInserted() + inserted, err := reader.QuerySIMInserted() if err != nil { return err } if !inserted { return ErrSMSIdentityUnknown } - iccid, err := w.Modem.QueryICCID() + iccid, err := reader.QueryICCID() if err != nil { return err } - imsi, err := w.Modem.QueryIMSI() + imsi, err := reader.QueryIMSI() if err != nil { return err } - if normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi}) != owner.SMSIdentity { - return ErrSMSIdentityConflict + if err := owner.check(); err != nil { + return err } - return owner.check() + live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi}) + switch { + case live.ICCID == "" || live.IMSI == "": + err = ErrSMSIdentityUnknown + case live != owner.SMSIdentity: + err = ErrSMSIdentityConflict + } + if err != nil && owner.worker.atDeviceRules().strictSIMIdentity { + return owner.worker.rejectLiveCSSMSIdentity(owner.simGeneration, "at_sms_inbox_identity", err) + } + return err } // A CMTI only proves provenance within the current worker and SIM generation. diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index 2fdc02b1..8697b781 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -3,6 +3,7 @@ package device import ( "context" "encoding/hex" + "errors" "path/filepath" "testing" "time" @@ -384,3 +385,81 @@ func TestATStoredSMSDuplicateRequiresReceiptIMSIForDeletion(t *testing.T) { t.Fatalf("replay recreated removed history: count=%d, err=%v", count, err) } } + +type storedSMSIdentityTestReader struct { + SMSIdentity + onIMSI func() +} + +func (r storedSMSIdentityTestReader) QuerySIMInserted() (bool, error) { return true, nil } +func (r storedSMSIdentityTestReader) QueryICCID() (string, error) { return r.ICCID, nil } +func (r storedSMSIdentityTestReader) QueryIMSI() (string, error) { + if r.onIMSI != nil { + r.onIMSI() + } + return r.IMSI, nil +} + +func TestATStoredSMSLiveSwapSchedulesSIMConvergence(t *testing.T) { + p, w, be := newML307CIdentityWorker(t) + configureWorkerATSMS(w) + owner, err := w.storedSMSOwner() + if err != nil { + t.Fatal(err) + } + live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"} + be.liveICCID, be.liveIMSI = live.ICCID, live.IMSI + if err := owner.verifyLiveFrom(storedSMSIdentityTestReader{SMSIdentity: live}); !errors.Is(err, ErrSMSIdentityConflict) { + t.Fatalf("live swap returned %v", err) + } + if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() != owner.simGeneration+1 { + t.Fatal("live swap left old cached identity ready") + } + var messages []InboundSMS + if err := w.readStoredSMSInbox(owner, nil, &messages); !errors.Is(err, ErrSMSIdentityTransitioning) || len(messages) != 0 { + t.Fatalf("old owner could enter the inbox: messages=%+v, err=%v", messages, err) + } + p.simEventMu.Lock() + timer := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if timer == nil || !timer.Stop() { + t.Fatal("inbox mismatch did not schedule SIM status convergence") + } + p.confirmSIMRemovedForOwner(owner.workerLifecycleOwner, "test", timer) + current, err := w.storedSMSOwner() + if err != nil || current.SMSIdentity != live || current.simGeneration <= owner.simGeneration { + t.Fatalf("inbox did not converge to the live identity: %+v, %v", current.SMSIdentity, err) + } +} + +func TestATStoredSMSStaleLiveReadLeavesNewerSIMReady(t *testing.T) { + p, w, _ := newML307CIdentityWorker(t) + configureWorkerATSMS(w) + owner, err := w.storedSMSOwner() + if err != nil { + t.Fatal(err) + } + live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"} + reader := storedSMSIdentityTestReader{ + SMSIdentity: SMSIdentity{ICCID: "card-intermediate", IMSI: "imsi-intermediate"}, + onIMSI: func() { + w.cacheMu.Lock() + defer w.cacheMu.Unlock() + setWorkerSMSIdentity(w, live) + w.state.Identity.Generation++ + }, + } + if err := owner.verifyLiveFrom(reader); !errors.Is(err, ErrSMSIdentityTransitioning) { + t.Fatalf("superseded read returned %v", err) + } + current, err := w.storedSMSOwner() + if err != nil || current.SMSIdentity != live || current.simGeneration != owner.simGeneration+1 { + t.Fatalf("superseded read altered the newer generation: %+v, %v", current.SMSIdentity, err) + } + p.simEventMu.Lock() + timer := p.simEventTimers[w.ID] + p.simEventMu.Unlock() + if timer != nil { + t.Fatal("superseded read scheduled a new SIM status check") + } +} diff --git a/internal/device/sms_identity.go b/internal/device/sms_identity.go index b75d9e45..041a0ba3 100644 --- a/internal/device/sms_identity.go +++ b/internal/device/sms_identity.go @@ -1,6 +1,7 @@ package device import ( + "context" "errors" "fmt" "strings" @@ -9,6 +10,7 @@ import ( "github.com/yibaiba/hideck/internal/backend" "github.com/yibaiba/hideck/internal/config" "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/modem" ) var ( @@ -130,6 +132,76 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error) }, nil } +func (w *Worker) strictSMSSendIdentity() (SMSIdentity, error) { + w.cacheMu.RLock() + state := w.state.Identity + w.cacheMu.RUnlock() + identity := normalizeSMSIdentity(SMSIdentity{ICCID: state.ICCID, IMSI: state.IMSI}) + if !state.Ready || state.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" { + return SMSIdentity{}, ErrSMSIdentityUnknown + } + return identity, nil +} + +// Caller holds the outbound operation through confirmation and submission. +func (w *Worker) confirmCSSMSIdentity(ctx context.Context, intended SMSIdentity, checkOwner func() error) error { + if err := checkOwner(); err != nil || !w.atDeviceRules().strictSIMIdentity { + return err + } + reader, ok := w.Backend.(liveSIMIdentityReader) + if !ok { + return ErrSMSIdentityUnknown + } + const source = "cs_sms_identity" + generation := w.SIMIdentityGeneration() + ctx, cancel := context.WithTimeout(contextOrBackground(ctx), 8*time.Second) + defer cancel() + inserted, err := w.Backend.IsSimInserted(ctx) + if err != nil { + if errors.Is(err, modem.ErrSIMPINRequired) { + w.recordStrictSIMLock(generation, source) + } + return err + } + if !inserted { + w.recordStrictSIMAbsence(generation, source) + return ErrSMSIdentityUnknown + } + iccid, err := reader.GetICCIDLive(ctx) + if err != nil { + return err + } + imsi, err := reader.GetIMSILive(ctx) + if err != nil { + return err + } + live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi}) + cached, err := w.strictSMSSendIdentity() + if err != nil { + return err + } + if err := checkOwner(); err != nil { + return err + } + switch { + case live.ICCID == "" || live.IMSI == "": + err = ErrSMSIdentityUnknown + case live != intended || cached != intended: + err = ErrSMSIdentityConflict + } + if err != nil { + return w.rejectLiveCSSMSIdentity(generation, source, err) + } + return ctx.Err() +} + +func (w *Worker) rejectLiveCSSMSIdentity(generation uint64, source string, err error) error { + if w.degradeStrictSIMIdentity(generation, source, err) { + w.scheduleSIMStatusCheck(source, nil, "READY") + } + return err +} + // smsIMSIAliasChecker is implemented by stores that remember every IMSI read on a // card, so a multi-IMSI SIM switching EF_IMSI is not treated as a different card. type smsIMSIAliasChecker interface { diff --git a/internal/device/vowifi_sms_send.go b/internal/device/vowifi_sms_send.go index b7eee30d..79977dae 100644 --- a/internal/device/vowifi_sms_send.go +++ b/internal/device/vowifi_sms_send.go @@ -146,7 +146,7 @@ func (p *Pool) SendRoutedSMS( return err } defer release() - if err := checkOwner(); err != nil { + if err := worker.confirmCSSMSIdentity(ctx, identity, checkOwner); err != nil { return err } if sendCSHook != nil { From da22cc7a2fd912b0f6acac6d9724002e9bff682f Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 21:09:57 +0800 Subject: [PATCH 30/39] fix(sms): match stored multipart pieces by PDU fingerprint --- internal/device/sms_at_inbox.go | 6 +++--- internal/device/sms_at_inbox_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index b1aaeb72..d9d45d9a 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -447,10 +447,10 @@ const ( func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (string, bool, error) { fingerprint := hex.EncodeToString(part.fingerprint[:]) matches := func(saved db.SMSInboundFragment) bool { - if sourceKnown { - return saved.Content == part.Content + if saved.PDUFingerprint != "" { + return saved.PDUFingerprint == fingerprint } - return saved.PDUFingerprint == fingerprint + return sourceKnown && saved.Content == part.Content } // Older fragments only have the legacy exact-SCTS key. It remains valid // for exact matches, but cannot prove the new metadata for a fuzzy join. diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index 8697b781..b93eaa2c 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -176,6 +176,27 @@ func TestATStoredSMSPersistence(t *testing.T) { t.Fatal("completed fragment groups were not collected") } + // A new message can reuse the exact grouping fields and first-part text + // of a completed one. Its different PDU must have its own receipt. + first := fragment(1, 0x03, 0, '同', observed) + firstTail := fragment(2, 0x03, 0, '甲', observed.Add(time.Second)) + second := fragment(1, 0x03, 0, '同', observed.Add(2*time.Second), 0x70, 1, 0x01) + secondTail := fragment(2, 0x03, 0, '乙', observed.Add(3*time.Second)) + if first.key != second.key || first.family != second.family || first.fingerprint == second.fingerprint { + t.Fatal("fixture must share grouping fields and have distinct first-part PDUs") + } + state = load(scope) + apply(state, first, true, false, "") + apply(state, firstTail, true, true, "同甲") + state = load(scope) + apply(state, second, true, false, "") + apply(state, secondTail, true, true, "同乙") + state = load(scope) + apply(state, second, false, true, "") + if err := load(scope).clearCompletedGroups(); err != nil { + t.Fatal(err) + } + // Legacy groups can still finish after upgrade with their original key. legacy1 := fragment(1, 0x05, 0, '旧', observed) legacy2 := fragment(2, 0x05, 0, '件', observed) @@ -190,6 +211,7 @@ func TestATStoredSMSPersistence(t *testing.T) { apply(load(scope), legacy1, false, false, "") apply(load(scope), legacy2, true, true, "旧件") apply(load(scope), legacy1, false, false, "") // No raw PDU hash on the pre-upgrade row. + apply(load(scope), legacy1, true, true, "") // Known sources can still match legacy rows by text. observed = observed.Add(5 * time.Minute) c1 := fragment(1, 0x30, 0x95, '跨', observed) From 0c56e920b2f5627e7263ac7825ba2f1d937bf389 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 21:12:45 +0800 Subject: [PATCH 31/39] fix(phone): reject cellular IMS without a modem data path --- internal/api/card_policy_test.go | 54 ++++++++++++++++++++++++++++-- internal/api/openapi.hideck.yaml | 3 ++ internal/api/phone.go | 3 ++ internal/device/at_device_rules.go | 2 ++ internal/device/phone_mode.go | 20 +++++++++-- internal/device/phone_mode_test.go | 12 ++++++- web/src/services/phone.ts | 1 + web/src/utils/phoneModeSwitch.ts | 6 +++- web/src/views/Phone.vue | 13 ++++--- web/tests/phoneModeSwitch.test.ts | 10 ++++-- 10 files changed, 109 insertions(+), 15 deletions(-) diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go index fa45ba6d..94770477 100644 --- a/internal/api/card_policy_test.go +++ b/internal/api/card_policy_test.go @@ -19,6 +19,7 @@ import ( "github.com/yibaiba/hideck/internal/db" "github.com/yibaiba/hideck/internal/device" "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/phone" "github.com/yibaiba/hideck/internal/vowifihost" ) @@ -605,10 +606,14 @@ func TestPutCardPolicyAirplaneField(t *testing.T) { func TestPhoneModePatchUsesEffectivePolicy(t *testing.T) { gin.SetMode(gin.TestMode) for _, tc := range []struct { - name, imsi, workerMode, storedMode, body string - wantEnabled, defaultProfile, missingPolicy bool + name, imsi, workerMode, storedMode, body, wantReason string + wantEnabled, defaultProfile, missingPolicy bool }{ {name: "native VoLTE", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"volte"}`}, + {name: "cellular IMS on demand", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"cellular","data_strategy":"on_demand"}`, + wantReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS"}, + {name: "saved cellular IMS mode", imsi: "530010000000001", workerMode: "wifi", storedMode: "cellular", body: `{"enabled":true}`, + wantReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS"}, {name: "direct dial", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"modem_voice"}`}, {name: "China software fallback", imsi: "460011234567890", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"wifi"}`}, {name: "stored VoLTE ahead of worker", imsi: "530010000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`}, @@ -657,7 +662,11 @@ func TestPhoneModePatchUsesEffectivePolicy(t *testing.T) { } return } - if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨") { + wantReason := tc.wantReason + if wantReason == "" { + wantReason = "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨" + } + if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), wantReason) { t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) } if store.policy != policy || w.Config != cfg { @@ -667,6 +676,45 @@ func TestPhoneModePatchUsesEffectivePolicy(t *testing.T) { } } +func TestPhoneDevicesReportsCellularIMSAvailability(t *testing.T) { + gin.SetMode(gin.TestMode) + pool := device.NewPool(&config.Config{}) + for id, profile := range map[string]modem.ATProfile{ + "ml307c": modem.ATProfileML307C, + "default": modem.ATProfileDefault, + } { + cfg := config.DeviceConfig{ID: id, DeviceBackend: "at", ATPort: "/dev/test-" + id} + manager, err := modem.NewWithATProfile(cfg, profile) + if err != nil { + t.Fatal(err) + } + injectWorker(pool, &device.Worker{ID: id, Config: cfg, Modem: manager}) + } + s := &Server{pool: pool, phone: &phone.Service{}} + r := gin.New() + r.GET("/api/phone/devices", s.handlePhoneDevices) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/phone/devices", nil)) + + var response struct { + Devices []struct { + ID string `json:"id"` + Reason *string `json:"cellular_ims_unavailable_reason"` + } `json:"devices"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &response); rec.Code != http.StatusOK || err != nil || len(response.Devices) != 2 { + t.Fatalf("code=%d error=%v body=%s", rec.Code, err, rec.Body.String()) + } + for _, item := range response.Devices { + if item.ID == "ml307c" && (item.Reason == nil || *item.Reason != "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS") { + t.Fatalf("missing ML307C reason: %s", rec.Body.String()) + } + if item.ID == "default" && item.Reason != nil { + t.Fatalf("unexpected default-profile restriction: %s", rec.Body.String()) + } + } +} + func TestLebaraUKRFLockRejectsNetworkAndCellular(t *testing.T) { gin.SetMode(gin.TestMode) openTestDB(t) diff --git a/internal/api/openapi.hideck.yaml b/internal/api/openapi.hideck.yaml index 7d42af66..b618e87c 100644 --- a/internal/api/openapi.hideck.yaml +++ b/internal/api/openapi.hideck.yaml @@ -4007,6 +4007,9 @@ components: phone_region: type: string description: SIM 归属国家或地区的 ISO 3166-1 alpha-2 代码 + cellular_ims_unavailable_reason: + type: string + description: 设备无法通过模组蜂窝数据使用软件 IMS 的原因 voice: type: object additionalProperties: true diff --git a/internal/api/phone.go b/internal/api/phone.go index e7f58f58..595102fe 100644 --- a/internal/api/phone.go +++ b/internal/api/phone.go @@ -112,6 +112,9 @@ func (s *Server) usePhoneDevices(c businessContext) { if err := worker.CheckPhoneModeSupported(device.PhoneModeVoLTE); err != nil { item["native_voice_unavailable_reason"] = err.Error() } + if reason := worker.CellularIMSUnavailableReason(); reason != "" { + item["cellular_ims_unavailable_reason"] = reason + } if region := s.phoneNumberRegion(worker.ID); region != "" { item["phone_region"] = region if code := phonenumbers.GetCountryCodeForRegion(region); code != 0 { diff --git a/internal/device/at_device_rules.go b/internal/device/at_device_rules.go index 94ec0467..a3c16f28 100644 --- a/internal/device/at_device_rules.go +++ b/internal/device/at_device_rules.go @@ -9,6 +9,7 @@ type atDeviceRules struct { model string storedSMSInbox bool nativeVoiceUnavailableReason string + cellularIMSUnavailableReason string } func atDeviceRulesFor(profile modem.ATProfile) atDeviceRules { @@ -21,6 +22,7 @@ func atDeviceRulesFor(profile modem.ATProfile) atDeviceRules { model: "ML307C", storedSMSInbox: true, nativeVoiceUnavailableReason: "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨", + cellularIMSUnavailableReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS", } default: return atDeviceRules{model: "EC20"} diff --git a/internal/device/phone_mode.go b/internal/device/phone_mode.go index d2273ca2..a896a6cf 100644 --- a/internal/device/phone_mode.go +++ b/internal/device/phone_mode.go @@ -65,24 +65,38 @@ func WorkerSoftwareIMSBlocked(w *Worker) bool { if w == nil { return false } + w.cacheMu.RLock() mcc := strings.TrimSpace(w.state.Identity.NativeMCC) + imsi := strings.TrimSpace(w.state.Identity.IMSI) + w.cacheMu.RUnlock() if carrier.IsVoWiFiBlockedMCC(mcc) { return true } - imsi := strings.TrimSpace(w.state.Identity.IMSI) if len(imsi) >= 3 && carrier.IsVoWiFiBlockedMCC(imsi[:3]) { return true } return false } -// CheckPhoneModeSupported checks native call control when selected or required -// by the SIM's software IMS policy. +// CellularIMSUnavailableReason reports the modem data-path limitation, independent of SIM policy. +func (w *Worker) CellularIMSUnavailableReason() string { + if w.NetworkController() != nil { + return "" + } + return w.atDeviceRules().cellularIMSUnavailableReason +} + +// CheckPhoneModeSupported checks the device and SIM capabilities for a phone mode. func (w *Worker) CheckPhoneModeSupported(mode string) error { if reason := w.atDeviceRules().nativeVoiceUnavailableReason; reason != "" && (UsesModemPhoneControl(mode) || WorkerSoftwareIMSBlocked(w)) { return &PhoneModeUnsupportedError{Reason: reason} } + if strings.TrimSpace(mode) == PhoneModeCellular { + if reason := w.CellularIMSUnavailableReason(); reason != "" { + return &PhoneModeUnsupportedError{Reason: reason} + } + } return nil } diff --git a/internal/device/phone_mode_test.go b/internal/device/phone_mode_test.go index b813aa68..6b9d1331 100644 --- a/internal/device/phone_mode_test.go +++ b/internal/device/phone_mode_test.go @@ -70,6 +70,8 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { }{ {name: "China WiFi", imsi: "460011234567890", mode: PhoneModeWiFi}, {name: "China cellular", imsi: "460011234567890", mode: PhoneModeCellular}, + {name: "overseas cellular", imsi: "530240000000001", mode: PhoneModeCellular}, + {name: "overseas cellular in airplane", imsi: "530240000000001", mode: PhoneModeCellular, airplane: true}, {name: "overseas VoLTE", imsi: "530240000000001", mode: PhoneModeVoLTE}, {name: "overseas direct dial", imsi: "530240000000001", mode: PhoneModeModemVoice, airplane: true}, } { @@ -107,7 +109,7 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { if resolver.pol != pol || p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test", LebaraUKClass{}) { t.Fatalf("card policy changed or still enables recovery: %+v", resolver.pol) } - if tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular { + if !tc.airplane && (tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular) { var unsupported *PhoneModeUnsupportedError if err := p.EnableVoWiFi(w.ID); !errors.As(err, &unsupported) { t.Fatalf("direct software IMS start error = %v", err) @@ -120,6 +122,14 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) { } } +func TestML307CCellularIMSCapabilityWithNetworkController(t *testing.T) { + w := &Worker{ID: "ml307c", netOverride: &fakeController{}} + w.Modem = newML307CPhoneTestModem(t, w.ID) + if err := w.CheckPhoneModeSupported(PhoneModeCellular); err != nil { + t.Fatalf("cellular IMS with a controller: %v", err) + } +} + func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) { p := newDesiredVoWiFiTestPool(t, "ml307c", false, "530010000000001") t.Cleanup(p.cancel) diff --git a/web/src/services/phone.ts b/web/src/services/phone.ts index 4dcc854f..b16f3684 100644 --- a/web/src/services/phone.ts +++ b/web/src/services/phone.ts @@ -30,6 +30,7 @@ export type PhoneDevice = { vowifi_active?: boolean software_ims_blocked?: boolean native_voice_unavailable_reason?: string + cellular_ims_unavailable_reason?: string phone_region?: string phone_country_code?: number rf_lock?: string diff --git a/web/src/utils/phoneModeSwitch.ts b/web/src/utils/phoneModeSwitch.ts index 51816b53..9b21f43a 100644 --- a/web/src/utils/phoneModeSwitch.ts +++ b/web/src/utils/phoneModeSwitch.ts @@ -13,6 +13,9 @@ export function phoneModeDisabledReason(device: PhoneDevice | undefined, mode: s if ((mode === 'volte' || mode === 'modem_voice') && device.native_voice_unavailable_reason) { return device.native_voice_unavailable_reason } + if (mode === 'cellular' && device.cellular_ims_unavailable_reason) { + return device.cellular_ims_unavailable_reason + } if (phoneModeCampsOnCell(mode) && device.rf_lock) { return '此 SIM 卡禁止蜂窝驻网,不能切换到该模式' } @@ -60,7 +63,8 @@ export async function confirmPhoneModeChange(options: ChangeOptions): Promise { if (mode === 'cellular' || mode === 'volte' || mode === 'modem_voice') return mode return 'wifi' }) -const selectedModeBlocked = computed(() => selected.value?.native_voice_unavailable_reason +const selectedDeviceModeReasons = computed(() => [ + selected.value?.native_voice_unavailable_reason, + selected.value?.cellular_ims_unavailable_reason +].filter(Boolean).join('。')) +const selectedModeBlocked = computed(() => selectedDeviceModeReasons.value ? phoneModeDisabledReason(selected.value, selectedMode.value) : undefined) const selectedStrategy = computed(() => selected.value?.data_strategy === 'always' ? 'always' : 'on_demand') @@ -490,8 +495,8 @@ async function sendDTMF(digit: string) { -

- {{ selectedModeBlocked || selected.native_voice_unavailable_reason }} +

+ {{ selectedModeBlocked || selectedDeviceModeReasons }}

{{ selected?.network_enabled diff --git a/web/tests/phoneModeSwitch.test.ts b/web/tests/phoneModeSwitch.test.ts index 13991adb..0361eb8e 100644 --- a/web/tests/phoneModeSwitch.test.ts +++ b/web/tests/phoneModeSwitch.test.ts @@ -33,13 +33,17 @@ test('mode availability follows SIM capability and RF lock, not country alone', assert.ok(phoneModeDisabledReason(undefined, 'wifi')) }) -test('ML307C blocks both native voice modes and preserves One NZ WiFi calling', () => { +test('ML307C blocks native voice and cellular IMS modes and preserves One NZ WiFi calling', () => { const reason = 'ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨' - const oneNZ = { ...device(), phone_region: 'NZ', native_voice_unavailable_reason: reason } + const cellularReason = 'ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS' + const oneNZ = { + ...device(), phone_region: 'NZ', native_voice_unavailable_reason: reason, + cellular_ims_unavailable_reason: cellularReason + } assert.equal(phoneModeDisabledReason(oneNZ, 'volte'), reason) assert.equal(phoneModeDisabledReason(oneNZ, 'modem_voice'), reason) assert.equal(phoneModeDisabledReason(oneNZ, 'wifi'), undefined) - assert.equal(phoneModeDisabledReason(oneNZ, 'cellular'), undefined) + assert.equal(phoneModeDisabledReason(oneNZ, 'cellular'), cellularReason) const china = { ...oneNZ, phone_region: 'CN', software_ims_blocked: true } assert.equal(phoneModeDisabledReason(china, 'wifi'), `此 SIM 卡不支持软件 IMS。${reason}`) }) From 984c4d199df4f3580cf86027944597cff695dc3d Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 21:27:13 +0800 Subject: [PATCH 32/39] fix(sms): verify each fragment before cross-SCTS recovery --- internal/device/sms_at_inbox.go | 30 +++++++++++++++--------- internal/device/sms_at_inbox_test.go | 34 ++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/internal/device/sms_at_inbox.go b/internal/device/sms_at_inbox.go index d9d45d9a..d28afcee 100644 --- a/internal/device/sms_at_inbox.go +++ b/internal/device/sms_at_inbox.go @@ -389,10 +389,16 @@ type atSMSParts struct { scope db.SMSInboundFragmentScope groups map[string][]db.SMSInboundFragment seen map[string]bool - senders map[string]string + observed map[atSMSFragmentObservation]string blockedFamilies map[string]bool } +type atSMSFragmentObservation struct { + sessionKey string + sequence int + fingerprint string +} + func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { rows, err := db.LoadSMSInboundFragments(scope) if err != nil { @@ -400,7 +406,7 @@ func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) { } state := &atSMSParts{ scope: scope, groups: make(map[string][]db.SMSInboundFragment), - seen: make(map[string]bool), senders: make(map[string]string), blockedFamilies: make(map[string]bool), + seen: make(map[string]bool), observed: make(map[atSMSFragmentObservation]string), blockedFamilies: make(map[string]bool), } for _, row := range rows { if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) { @@ -444,8 +450,7 @@ const ( atSMSReassemblyWindow = 2 * time.Minute ) -func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (string, bool, error) { - fingerprint := hex.EncodeToString(part.fingerprint[:]) +func (state *atSMSParts) fragmentGroup(part atInboxPart, fingerprint string, sourceKnown bool) (string, bool, error) { matches := func(saved db.SMSInboundFragment) bool { if saved.PDUFingerprint != "" { return saved.PDUFingerprint == fingerprint @@ -508,12 +513,12 @@ func (state *atSMSParts) fragmentGroup(part atInboxPart, sourceKnown bool) (stri } func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) { - key, matched, err := state.fragmentGroup(part, sourceKnown) + fingerprint := hex.EncodeToString(part.fingerprint[:]) + key, matched, err := state.fragmentGroup(part, fingerprint, sourceKnown) if err != nil || key == "" { return false, nil, err } state.seen[key] = true - state.senders[key] = part.Sender fragments := state.groups[key] if !matched { scope := state.scope @@ -522,7 +527,7 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo result, err := db.SaveSMSInboundFragment(scope, db.SMSInboundFragment{ Sequence: concat.Seq, Reference: concat.Ref, ReferenceBits: concat.RefBits, Total: concat.Total, Content: part.Content, ArrivedAt: part.Timestamp, - PDUFingerprint: hex.EncodeToString(part.fingerprint[:]), + PDUFingerprint: fingerprint, }) if err != nil { return false, nil, err @@ -530,6 +535,7 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo fragments = result.Fragments state.groups[key] = fragments } + state.observed[atSMSFragmentObservation{key, part.Concat.Seq, fingerprint}] = part.Sender if len(fragments) < part.Concat.Total { // Keep the source while other exact groups can still arrive. return false, nil, nil @@ -543,16 +549,18 @@ func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bo } func (state *atSMSParts) archiveSettledATFragments(now time.Time) ([]InboundSMS, error) { + observedSender := func(fragment db.SMSInboundFragment) string { + return state.observed[atSMSFragmentObservation{fragment.SessionKey, fragment.Sequence, fragment.PDUFingerprint}] + } var notifications []InboundSMS for _, fragments := range state.settledATFragments(now) { - // Each group must have an exact PDU in the current scan. A DB-only - // group can outlive its source slots and must not complete a new SMS. + // Each fragment must match a PDU observed in the current scan. if slices.ContainsFunc(fragments, func(fragment db.SMSInboundFragment) bool { - return state.senders[fragment.SessionKey] == "" + return observedSender(fragment) == "" }) { continue } - sender := state.senders[fragments[0].SessionKey] + sender := observedSender(fragments[0]) key, content, err := completeATMultipart(fragments[0].SessionKey, fragments) if err != nil { return notifications, err diff --git a/internal/device/sms_at_inbox_test.go b/internal/device/sms_at_inbox_test.go index b93eaa2c..f19f47ef 100644 --- a/internal/device/sms_at_inbox_test.go +++ b/internal/device/sms_at_inbox_test.go @@ -36,14 +36,14 @@ func TestATStoredSMSPersistence(t *testing.T) { }) identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"} scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI} - fragment := func(seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart { + multipart := func(total, seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart { t.Helper() pdu := []byte{ 0, // default SMSC 0x40, 3, 0x81, 0x77, 0xF7, // SMS-DELIVER, UDHI, sender 777 0, 8, // PID, UCS2 0x62, 0x11, 0x91, 0x21, minute, second, 0, // SCTS - byte(8 + len(extraUDH)), byte(5 + len(extraUDH)), 0, 3, 17, 2, seq, + byte(8 + len(extraUDH)), byte(5 + len(extraUDH)), 0, 3, 17, total, seq, } pdu = append(pdu, extraUDH...) pdu = append(pdu, byte(ch>>8), byte(ch)) @@ -57,6 +57,10 @@ func TestATStoredSMSPersistence(t *testing.T) { part.observedAt = observed return part } + fragment := func(seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart { + t.Helper() + return multipart(2, seq, minute, second, ch, observed, extraUDH...) + } load := func(scope db.SMSInboundFragmentScope) *atSMSParts { t.Helper() state, err := loadATSMSParts(scope) @@ -311,6 +315,32 @@ func TestATStoredSMSPersistence(t *testing.T) { t.Fatalf("archive ignored a same-family write failure: %+v, %v", messages, err) } + // One exact group contains two of the three parts. Observing its first + // part alone cannot prove the other part is still in modem storage. + observed = observed.Add(10 * time.Minute) + p1 := multipart(3, 1, 0x15, 0, '全', observed) + p2 := multipart(3, 2, 0x15, 0, '部', observed.Add(time.Second)) + p3 := multipart(3, 3, 0x15, 0x10, '在', observed.Add(2*time.Second)) + state = load(scope) + for _, part := range []atInboxPart{p1, p2, p3} { + apply(state, part, true, false, "") + } + settledAt := observed.Add(3 * time.Minute) + state = load(scope) + apply(state, p1, false, false, "") + apply(state, p3, false, false, "") + if messages, err := state.archiveSettledATFragments(settledAt); err != nil || len(messages) != 0 { + t.Fatalf("archived a cross-SCTS SMS with an unobserved part: %+v, %v", messages, err) + } + state = load(scope) + for _, part := range []atInboxPart{p1, p2, p3} { + apply(state, part, false, false, "") + } + messages, err = state.archiveSettledATFragments(settledAt) + if err != nil || len(messages) != 1 || messages[0].Content != "全部在" { + t.Fatalf("archive with all parts observed: %+v, %v", messages, err) + } + swapped := scope swapped.ICCID, swapped.IMSI = "8988110000000000002", "001010123456788" apply(load(swapped), a1, false, false, "") // unknown old ME after a card change From ffb5cbceeef06365793b60d25347b14b099572d6 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 21:36:16 +0800 Subject: [PATCH 33/39] fix(phone): enforce capability for automatic cellular dialing --- internal/api/automatic_tasks_call_test.go | 36 +++++++++++++++++++++++ internal/api/automatic_tasks_executor.go | 5 ++++ internal/device/outbound_limits.go | 3 ++ 3 files changed, 44 insertions(+) create mode 100644 internal/api/automatic_tasks_call_test.go diff --git a/internal/api/automatic_tasks_call_test.go b/internal/api/automatic_tasks_call_test.go new file mode 100644 index 00000000..515ebb91 --- /dev/null +++ b/internal/api/automatic_tasks_call_test.go @@ -0,0 +1,36 @@ +package api + +import ( + "context" + "errors" + "testing" + + "github.com/yibaiba/hideck/internal/automation" + "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/device" + "github.com/yibaiba/hideck/internal/modem" +) + +func TestAutomaticCellularCallRejectsUnsupportedModemBeforePreparation(t *testing.T) { + cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: "at", ATPort: "/dev/test-ml307c"} + manager, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C) + if err != nil { + t.Fatal(err) + } + pool := device.NewPool(&config.Config{}) + pool.AttachWorkerForTest(&device.Worker{ID: cfg.ID, Config: cfg, Modem: manager}) + executor := &automaticTaskExecutor{server: &Server{pool: pool}} + + _, err = executor.Execute(context.Background(), automation.Task{ + DeviceID: cfg.ID, TaskType: automation.TaskTypeCall, Environment: automation.EnvironmentCellular, + ProfileICCID: "8944000000000000501", ProfileAID: "A0000005591010FFFFFFFF8900000100", + Payload: automation.Payload{Phone: "888"}, + }, func(step string) error { + t.Fatalf("unsupported cellular call reached preparation: %s", step) + return nil + }) + var unsupported *device.PhoneModeUnsupportedError + if !errors.As(err, &unsupported) || automation.IsRetryable(err) { + t.Fatalf("Execute() error = %v, want a permanent unsupported phone mode error", err) + } +} diff --git a/internal/api/automatic_tasks_executor.go b/internal/api/automatic_tasks_executor.go index 8dfad615..fe025439 100644 --- a/internal/api/automatic_tasks_executor.go +++ b/internal/api/automatic_tasks_executor.go @@ -38,6 +38,11 @@ func (e *automaticTaskExecutor) Execute( if worker == nil { return "", fmt.Errorf("device %s is offline", task.DeviceID) } + if task.TaskType == automation.TaskTypeCall && task.Environment == automation.EnvironmentCellular { + if err := worker.CheckPhoneModeSupported(device.PhoneModeVoLTE); err != nil { + return "", automation.Permanent(err) + } + } owner := captureAutomaticTaskDeviceOwner(e.server.pool, worker) profileAction, err := resolveAutomaticTaskProfile(task, worker.CurrentICCID()) if err != nil { diff --git a/internal/device/outbound_limits.go b/internal/device/outbound_limits.go index c8c361c6..0acc18c5 100644 --- a/internal/device/outbound_limits.go +++ b/internal/device/outbound_limits.go @@ -36,6 +36,9 @@ func (p *Pool) DialAuthorizedCellularCall(ctx context.Context, worker *Worker, n if p == nil || worker == nil || worker.Modem == nil { return errors.New("cellular calling requires an AT modem channel") } + if err := worker.CheckPhoneModeSupported(PhoneModeVoLTE); err != nil { + return err + } release, err := p.acquireOutboundOperation(worker) if err != nil { return err From 04bcac76e78ff596f85d2a89bf38f25272519303 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 21:39:58 +0800 Subject: [PATCH 34/39] fix(sms): preserve the selected SIM through submission --- internal/api/automatic_tasks_executor.go | 5 +- internal/api/automatic_tasks_sms_test.go | 24 +++++++ internal/api/command_center_test.go | 4 +- internal/api/sms_send_usecase.go | 7 +- internal/api/sms_send_usecase_test.go | 81 ++++++++++++++++++++++++ internal/balance/device_gateway.go | 12 ++-- internal/balance/device_gateway_test.go | 17 ++++- internal/balance/service.go | 4 +- internal/balance/service_test.go | 4 +- internal/balance/types.go | 4 +- internal/device/outbound_limits.go | 24 ++++--- internal/device/outbound_limits_test.go | 35 ++++++++++ internal/device/pool_sms.go | 28 +++++++- internal/device/sms_identity.go | 29 +++++++++ internal/device/vowifi_sms_send.go | 39 ++++++++++-- 15 files changed, 282 insertions(+), 35 deletions(-) diff --git a/internal/api/automatic_tasks_executor.go b/internal/api/automatic_tasks_executor.go index fe025439..ff726f83 100644 --- a/internal/api/automatic_tasks_executor.go +++ b/internal/api/automatic_tasks_executor.go @@ -241,8 +241,9 @@ func (e *automaticTaskExecutor) executeSMS( if err := reportAutomationProgress(progress, "正在提交短信"); err != nil { return "", err } + selector := device.SMSIdentity{ICCID: task.ProfileICCID} if task.Environment == automation.EnvironmentVoWiFi { - routed, err := e.server.pool.SendRoutedSMS(ctx, worker, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{}) + routed, err := e.server.pool.SendRoutedSMSForIdentity(ctx, worker, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{}, selector) if err != nil { return "", automation.Permanent(fmt.Errorf("send VoWiFi SMS: %w", err)) } @@ -261,7 +262,7 @@ func (e *automaticTaskExecutor) executeSMS( routed.Outcome.MessageID, routed.Outcome.DeliveryState, routed.Outcome.PartsTotal, ), nil } - if err := worker.SendSMS(task.Payload.Phone, task.Payload.Message); err != nil { + if err := worker.SendSMSForIdentity(ctx, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{}, selector); err != nil { return "", automation.Permanent(fmt.Errorf("send cellular SMS: %w", err)) } return "蜂窝短信已由模组提交", nil diff --git a/internal/api/automatic_tasks_sms_test.go b/internal/api/automatic_tasks_sms_test.go index 7982c8fd..743b6272 100644 --- a/internal/api/automatic_tasks_sms_test.go +++ b/internal/api/automatic_tasks_sms_test.go @@ -74,6 +74,30 @@ func TestExecuteSMSDoesNotFallbackAfterIMSAccept(t *testing.T) { } } +func TestExecuteSMSRejectsChangedTaskProfile(t *testing.T) { + for _, environment := range []string{automation.EnvironmentVoWiFi, automation.EnvironmentCellular} { + t.Run(environment, func(t *testing.T) { + pool := device.NewPool(&config.Config{}) + worker := &device.Worker{ID: "wwan0", Pool: pool} + original := device.SMSIdentity{ICCID: "8944000000000000501", IMSI: "234150000000501"} + pool.AttachWorkerWithSMSIdentityForTest(worker, original) + executor := &automaticTaskExecutor{server: &Server{pool: pool}} + _, err := executor.executeSMS(context.Background(), worker, automation.Task{ + DeviceID: worker.ID, ProfileICCID: original.ICCID, Environment: environment, + Payload: automation.Payload{Phone: "888", Message: "BAL"}, + }, func(string) error { + pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{ + ICCID: "8944000000000000502", IMSI: "234150000000502", + }) + return nil + }) + if !errors.Is(err, device.ErrSMSSelectorMismatch) { + t.Fatalf("submit SMS after changing profile: %v", err) + } + }) + } +} + func TestVoWiFiReadyForSMSTaskUsesMOReadiness(t *testing.T) { state := runtimehost.State{ IMSReady: true, SMSMOReady: true, diff --git a/internal/api/command_center_test.go b/internal/api/command_center_test.go index 4fb4fc1b..fd483c0c 100644 --- a/internal/api/command_center_test.go +++ b/internal/api/command_center_test.go @@ -33,11 +33,11 @@ func (g *apiBalanceGateway) Snapshot(deviceID string) (balance.DeviceSnapshot, e return balance.DeviceSnapshot{DeviceID: deviceID, ICCID: "iccid-1", MCC: "234", MNC: "10"}, nil } -func (g *apiBalanceGateway) SendVoWiFiSMS(context.Context, string, string, string) error { +func (g *apiBalanceGateway) SendVoWiFiSMS(context.Context, balance.DeviceSnapshot, string, string) error { return errors.New("unexpected VoWiFi route") } -func (g *apiBalanceGateway) SendBackendSMS(context.Context, string, string, string) error { +func (g *apiBalanceGateway) SendBackendSMS(context.Context, balance.DeviceSnapshot, string, string) error { g.smsCalls++ return nil } diff --git a/internal/api/sms_send_usecase.go b/internal/api/sms_send_usecase.go index 748837b9..d3f5d1f3 100644 --- a/internal/api/sms_send_usecase.go +++ b/internal/api/sms_send_usecase.go @@ -66,12 +66,17 @@ func (s *Server) useSendSMS(c businessContext) { logger.Warn("取消短信发送等待写入超时失败", "err", err) } } - routed, err := s.pool.SendRoutedSMS(businessRequestContext(c), worker, req.Phone, req.Message, sendOpts) + selector := device.SMSIdentity{ICCID: db.CanonicalICCID(req.ICCID), IMSI: strings.TrimSpace(req.IMSI)} + routed, err := s.pool.SendRoutedSMSForIdentity(businessRequestContext(c), worker, req.Phone, req.Message, sendOpts, selector) if responseController != nil { if err := responseController.SetWriteDeadline(time.Now().Add(managedHTTPWriteTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) { logger.Warn("恢复短信响应写入超时失败", "err", err) } } + if errors.Is(err, device.ErrSMSSelectorMismatch) { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": err.Error()}) + return + } if respondOutboundLimit(c, err) { return } diff --git a/internal/api/sms_send_usecase_test.go b/internal/api/sms_send_usecase_test.go index 256c3b53..43f5245d 100644 --- a/internal/api/sms_send_usecase_test.go +++ b/internal/api/sms_send_usecase_test.go @@ -17,6 +17,7 @@ import ( "github.com/yibaiba/hideck/internal/db" "github.com/yibaiba/hideck/internal/device" "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/outbound" "github.com/yibaiba/hideck/pkg/smscodec" ) @@ -135,3 +136,83 @@ func TestRESTSMSUncertainResultSurvivesWriteTimeout(t *testing.T) { t.Fatalf("HTTP %d result=%+v CS sends=%d", resp.StatusCode, result, sends.Load()) } } + +type smsWriteDeadlineRecorder struct { + *httptest.ResponseRecorder + onClear func() +} + +func (r *smsWriteDeadlineRecorder) SetWriteDeadline(deadline time.Time) error { + if deadline.IsZero() { + r.onClear() + } + return nil +} + +type smsSelectorTestBackend struct { + ussdDeviceBackendStub + imsi string +} + +func (b *smsSelectorTestBackend) GetIMSI(context.Context) (string, error) { + return b.imsi, nil +} + +type smsSelectorTestLimiter struct { + attempts int +} + +func (l *smsSelectorTestLimiter) Consume(context.Context, outbound.Request) error { + l.attempts++ + return nil +} + +func TestSendSMSKeepsExplicitSIMSelectorThroughSubmission(t *testing.T) { + gin.SetMode(gin.TestMode) + original := device.SMSIdentity{ICCID: "8944000000000000601", IMSI: "234150000000601"} + for _, test := range []struct { + name, request string + active device.SMSIdentity + wantStatus int + wantSends int + }{ + {"matching ICCID", `"iccid":" 8944000000000000601f "`, original, http.StatusOK, 1}, + {"matching IMSI", `"imsi":" 234150000000601 "`, original, http.StatusOK, 1}, + {"stale ICCID", `"iccid":"8944000000000000601"`, device.SMSIdentity{ICCID: "8944000000000000602", IMSI: original.IMSI}, http.StatusConflict, 0}, + {"stale IMSI", `"imsi":"234150000000601"`, device.SMSIdentity{ICCID: original.ICCID, IMSI: "234150000000602"}, http.StatusConflict, 0}, + {"device selection follows active SIM", `"device_id":"sms-at"`, device.SMSIdentity{ICCID: "8944000000000000602", IMSI: "234150000000602"}, http.StatusOK, 1}, + } { + t.Run(test.name, func(t *testing.T) { + openTestDB(t) + pool := device.NewPool(&config.Config{}) + backend := &smsSelectorTestBackend{imsi: original.IMSI} + worker := &device.Worker{ID: "sms-at", Backend: backend} + pool.AttachWorkerWithSMSIdentityForTest(worker, original) + limiter := &smsSelectorTestLimiter{} + pool.SetOutboundLimiter(limiter) + sends := 0 + pool.SetRoutedSMSTestSenders(nil, func(string, string, string) error { + sends++ + return nil + }) + writer := &smsWriteDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), onClear: func() { + // The handler clears its write deadline after selecting a worker. + backend.imsi = test.active.IMSI + pool.AttachWorkerWithSMSIdentityForTest(worker, test.active) + }} + c, _ := gin.CreateTestContext(writer) + c.Request = httptest.NewRequest(http.MethodPost, "/api/sms/send", strings.NewReader( + `{`+test.request+`,"phone":"777","message":"test"}`)) + c.Request.Header.Set("Content-Type", "application/json") + server := &Server{pool: pool} + server.handleSendSMS(c) + if writer.Code != test.wantStatus || limiter.attempts != test.wantSends || sends != test.wantSends { + t.Fatalf("HTTP %d: %s, quota attempts=%d, sends=%d", writer.Code, writer.Body, limiter.attempts, sends) + } + messages, err := db.GetSMSByICCID(test.active.ICCID, 10) + if err != nil || len(messages) != test.wantSends { + t.Fatalf("active SIM history = %+v, error = %v", messages, err) + } + }) + } +} diff --git a/internal/balance/device_gateway.go b/internal/balance/device_gateway.go index adb490e1..6d6909c2 100644 --- a/internal/balance/device_gateway.go +++ b/internal/balance/device_gateway.go @@ -40,24 +40,24 @@ func (g *PoolGateway) Snapshot(deviceID string) (DeviceSnapshot, error) { RouteSMSViaVoWiFi: g.pool.ShouldRouteSMSViaVoWiFi(worker.ID)}, nil } -func (g *PoolGateway) SendVoWiFiSMS(ctx context.Context, deviceID, destination, payload string) error { +func (g *PoolGateway) SendVoWiFiSMS(ctx context.Context, snapshot DeviceSnapshot, destination, payload string) error { if g == nil || g.pool == nil { return ErrDeviceNotFound } - worker := g.pool.GetWorker(deviceID) + worker := g.pool.GetWorker(snapshot.DeviceID) if worker == nil { return ErrDeviceNotFound } - _, err := g.pool.SendRoutedSMS(ctx, worker, destination, payload, smscodec.SubmitOptions{}) + _, err := g.pool.SendRoutedSMSForIdentity(ctx, worker, destination, payload, smscodec.SubmitOptions{}, device.SMSIdentity{ICCID: snapshot.ICCID}) return err } -func (g *PoolGateway) SendBackendSMS(_ context.Context, deviceID, destination, payload string) error { - worker := g.pool.GetWorker(deviceID) +func (g *PoolGateway) SendBackendSMS(ctx context.Context, snapshot DeviceSnapshot, destination, payload string) error { + worker := g.pool.GetWorker(snapshot.DeviceID) if worker == nil { return ErrDeviceNotFound } - return worker.SendSMSWithOptions(destination, payload, smscodec.SubmitOptions{}) + return worker.SendSMSForIdentity(ctx, destination, payload, smscodec.SubmitOptions{}, device.SMSIdentity{ICCID: snapshot.ICCID}) } func (g *PoolGateway) SendVoWiFiUSSD(ctx context.Context, deviceID, code string) (USSDResponse, error) { diff --git a/internal/balance/device_gateway_test.go b/internal/balance/device_gateway_test.go index 041b44d0..4cb151f1 100644 --- a/internal/balance/device_gateway_test.go +++ b/internal/balance/device_gateway_test.go @@ -25,7 +25,7 @@ func TestPoolGatewaySendVoWiFiSMSFallsBackToCSWithoutDoubleSend(t *testing.T) { }, func(string, string, string) error { csCalls++; return nil }, ) - if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), "wwan0", "85075", "INFO"); err != nil { + if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"}, "85075", "INFO"); err != nil { t.Fatalf("SendVoWiFiSMS() = %v", err) } if vowifiCalls != 1 || csCalls != 1 { @@ -46,7 +46,7 @@ func TestPoolGatewaySendVoWiFiSMSDoesNotFallbackAfterIMSAccept(t *testing.T) { }, func(string, string, string) error { csCalls++; return nil }, ) - if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), "wwan0", "85075", "INFO"); err == nil || + if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"}, "85075", "INFO"); err == nil || !strings.Contains(err.Error(), "403") { t.Fatalf("expected IMS 403 to stay on VoWiFi, got %v", err) } @@ -54,3 +54,16 @@ func TestPoolGatewaySendVoWiFiSMSDoesNotFallbackAfterIMSAccept(t *testing.T) { t.Fatalf("calls vowifi=%d cs=%d", vowifiCalls, csCalls) } } + +func TestPoolGatewayRejectsSMSAfterCardChanges(t *testing.T) { + pool := device.NewPool(&config.Config{}) + worker := &device.Worker{ID: "wwan0", Pool: pool} + pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{ICCID: "8944100000000000002", IMSI: "234150000000002"}) + gateway := NewPoolGateway(pool) + stale := DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"} + for _, send := range []func(context.Context, DeviceSnapshot, string, string) error{gateway.SendVoWiFiSMS, gateway.SendBackendSMS} { + if err := send(context.Background(), stale, "85075", "INFO"); !errors.Is(err, device.ErrSMSSelectorMismatch) { + t.Fatalf("send with stale ICCID = %v", err) + } + } +} diff --git a/internal/balance/service.go b/internal/balance/service.go index d1459f8d..922d5198 100644 --- a/internal/balance/service.go +++ b/internal/balance/service.go @@ -71,9 +71,9 @@ func (s *Service) send(ctx context.Context, snapshot DeviceSnapshot, rule carrie func (s *Service) sendSMS(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule) error { if snapshot.VoWiFiActive || snapshot.RouteSMSViaVoWiFi { - return s.gateway.SendVoWiFiSMS(ctx, snapshot.DeviceID, rule.Destination, rule.Payload) + return s.gateway.SendVoWiFiSMS(ctx, snapshot, rule.Destination, rule.Payload) } - return s.gateway.SendBackendSMS(ctx, snapshot.DeviceID, rule.Destination, rule.Payload) + return s.gateway.SendBackendSMS(ctx, snapshot, rule.Destination, rule.Payload) } func (s *Service) sendUSSD(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule, queryID string) error { diff --git a/internal/balance/service_test.go b/internal/balance/service_test.go index ad614151..8bbe3bc6 100644 --- a/internal/balance/service_test.go +++ b/internal/balance/service_test.go @@ -23,11 +23,11 @@ type fakeGateway struct { } func (g *fakeGateway) Snapshot(string) (DeviceSnapshot, error) { return g.snapshot, nil } -func (g *fakeGateway) SendVoWiFiSMS(context.Context, string, string, string) error { +func (g *fakeGateway) SendVoWiFiSMS(context.Context, DeviceSnapshot, string, string) error { g.wifiSMS++ return g.sendErr } -func (g *fakeGateway) SendBackendSMS(context.Context, string, string, string) error { +func (g *fakeGateway) SendBackendSMS(context.Context, DeviceSnapshot, string, string) error { g.backendSMS++ if g.onBackendSMS != nil { g.onBackendSMS() diff --git a/internal/balance/types.go b/internal/balance/types.go index 5f8fdb5b..44f41ba2 100644 --- a/internal/balance/types.go +++ b/internal/balance/types.go @@ -91,8 +91,8 @@ type Completion struct { type Gateway interface { Snapshot(deviceID string) (DeviceSnapshot, error) - SendVoWiFiSMS(context.Context, string, string, string) error - SendBackendSMS(context.Context, string, string, string) error + SendVoWiFiSMS(context.Context, DeviceSnapshot, string, string) error + SendBackendSMS(context.Context, DeviceSnapshot, string, string) error SendVoWiFiUSSD(context.Context, string, string) (USSDResponse, error) SendBackendUSSD(context.Context, string, string) (USSDResponse, error) } diff --git a/internal/device/outbound_limits.go b/internal/device/outbound_limits.go index 0acc18c5..3eb743cc 100644 --- a/internal/device/outbound_limits.go +++ b/internal/device/outbound_limits.go @@ -27,7 +27,7 @@ func (p *Pool) AuthorizeOutboundCall(ctx context.Context, id, number string) err if !outboundNumber.MatchString(strings.TrimSpace(number)) { return errors.New("无效的外呼号码") } - return p.consumeOutbound(ctx, p.GetWorker(id), outbound.Request{Kind: outbound.Call, Units: 1}) + return p.consumeOutbound(ctx, p.GetWorker(id), outbound.Request{Kind: outbound.Call, Units: 1}, nil) } // DialAuthorizedCellularCall keeps the SIM owner stable from quota charging @@ -71,9 +71,10 @@ func (p *Pool) acquireOutboundOperation(worker *Worker) (func(), error) { } type outboundSMSRequest struct { - Worker *Worker - To, Text string - Options smscodec.SubmitOptions + Worker *Worker + To, Text string + Options smscodec.SubmitOptions + CheckOwner func() error } func (p *Pool) authorizeSMS(ctx context.Context, request outboundSMSRequest) error { @@ -84,7 +85,7 @@ func (p *Pool) authorizeSMS(ctx context.Context, request outboundSMSRequest) err if err != nil { return err } - return p.consumeOutbound(ctx, request.Worker, outbound.Request{Kind: outbound.SMS, Units: len(parts)}) + return p.consumeOutbound(ctx, request.Worker, outbound.Request{Kind: outbound.SMS, Units: len(parts)}, request.CheckOwner) } // A queued operation must not spend one SIM's budget on another. @@ -98,7 +99,7 @@ func (p *Pool) outboundOwnerCheck(w *Worker) func() error { } } -func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound.Request) error { +func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound.Request, checkOwner func() error) error { if p == nil { return nil } @@ -114,14 +115,21 @@ func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound. if limiter == nil { return nil } - if w == nil || p.GetWorker(w.ID) != w || p.IsESIMSwitching(w.ID) { + sim := currentSIMOwnership(w) + if checkOwner != nil { + if err := checkOwner(); err != nil { + return err + } + } else if w == nil || p.GetWorker(w.ID) != w || p.IsESIMSwitching(w.ID) { return errors.New("设备或 SIM 正在变更,不能发起外发请求") } - sim := currentSIMOwnership(w) attempt := outbound.Request{ICCID: sim.iccid, Kind: request.Kind, Units: request.Units} if err := limiter.Consume(contextOrBackground(ctx), attempt); err != nil { return err } + if checkOwner != nil { + return checkOwner() + } if p.GetWorker(w.ID) != w || currentSIMOwnership(w) != sim || p.IsESIMSwitching(w.ID) { return errors.New("记录额度期间设备或 SIM 已变更,请重新操作") } diff --git a/internal/device/outbound_limits_test.go b/internal/device/outbound_limits_test.go index c6d6e31f..76a6f677 100644 --- a/internal/device/outbound_limits_test.go +++ b/internal/device/outbound_limits_test.go @@ -195,3 +195,38 @@ func TestML307CCSSMSRejectsSilentSIMSwapDuringAuthorization(t *testing.T) { t.Fatalf("wrong send or quota owner: sends=%d charges=%+v", be.sends, limiter.requests) } } + +type directSMSSelectorBackend struct { + workerStatusBackendStub + sends int +} + +func (b *directSMSSelectorBackend) SendSMS(context.Context, string, string) error { + b.sends++ + return nil +} + +func TestDirectSMSMatchesICCIDWithoutIMSI(t *testing.T) { + _, w, limiter := outboundTestWorker(t) + backend := &directSMSSelectorBackend{workerStatusBackendStub: workerStatusBackendStub{mode: "qmi"}} + w.Backend = backend + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "123"}) + err := w.SendSMSForIdentity(context.Background(), "10010", "test", smscodec.SubmitOptions{}, SMSIdentity{ICCID: "123f"}) + if err != nil || backend.sends != 1 || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "123" { + t.Fatalf("send error=%v, sends=%d, quota=%+v", err, backend.sends, limiter.requests) + } +} + +func TestRoutedSMSReportsStaleSelectorBeforeFallback(t *testing.T) { + p, w, limiter := outboundTestWorker(t) + w.Config.VoWiFiEnabled, w.Config.PhoneMode = true, "wifi" + cs := false + p.SetRoutedSMSTestSenders(func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) { + setWorkerSMSIdentity(w, SMSIdentity{ICCID: "456", IMSI: "234150123456789"}) + return messaging.SendOutcome{}, messaging.ErrSMSNotReady + }, func(string, string, string) error { cs = true; return nil }) + _, err := p.SendRoutedSMSForIdentity(context.Background(), w, "10010", "test", smscodec.SubmitOptions{}, SMSIdentity{ICCID: "123"}) + if !errors.Is(err, ErrSMSSelectorMismatch) || cs || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "123" { + t.Fatalf("fallback: error=%v CS sent=%v quota=%+v", err, cs, limiter.requests) + } +} diff --git a/internal/device/pool_sms.go b/internal/device/pool_sms.go index 399269b5..ecc566e1 100644 --- a/internal/device/pool_sms.go +++ b/internal/device/pool_sms.go @@ -401,6 +401,11 @@ func (w *Worker) SendSMS(phone, message string) error { } func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitOptions) error { + return w.SendSMSForIdentity(context.Background(), phone, message, opts, SMSIdentity{}) +} + +// SendSMSForIdentity binds a SIM selector to a direct backend send. +func (w *Worker) SendSMSForIdentity(ctx context.Context, phone, message string, opts smscodec.SubmitOptions, selector SMSIdentity) error { if w == nil || w.Pool == nil { return errors.New("短信发送需要有效的设备池") } @@ -409,18 +414,35 @@ func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitO return err } defer release() - check := w.Pool.outboundOwnerCheck(w) + explicitSelector := selector != (SMSIdentity{}) + selector = normalizeSMSIdentity(selector) + check := w.Pool.smsSendOwnerCheck(w, selector) + request := outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts} var intended SMSIdentity if w.atDeviceRules().strictSIMIdentity { intended, err = w.strictSMSSendIdentity() if err != nil { return err } + } else if explicitSelector { + intended = w.cachedSMSIdentity() } - if err := w.Pool.authorizeSMS(context.Background(), outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts}); err != nil { + if explicitSelector { + if !selector.matches(intended) { + return ErrSMSSelectorMismatch + } + if err := check(); err != nil { + return err + } + request.CheckOwner = check + } + if err := w.Pool.authorizeSMS(ctx, request); err != nil { return err } - if err := w.confirmCSSMSIdentity(context.Background(), intended, check); err != nil { + if err := w.confirmCSSMSIdentity(ctx, intended, check); err != nil { + if explicitSelector && errors.Is(err, ErrSMSIdentityConflict) { + return ErrSMSSelectorMismatch + } return err } return w.sendSMSWithOptions(phone, message, opts) diff --git a/internal/device/sms_identity.go b/internal/device/sms_identity.go index 041a0ba3..8d3d4020 100644 --- a/internal/device/sms_identity.go +++ b/internal/device/sms_identity.go @@ -14,6 +14,7 @@ import ( ) var ( + ErrSMSSelectorMismatch = errors.New("所选 SIM 身份已变更,请重新选择") ErrSMSIdentityUnknown = errors.New("短信身份未知") ErrSMSIdentityConflict = errors.New("短信身份冲突") ErrSMSIdentityTransitioning = errors.New("SIM 身份正在切换") @@ -56,6 +57,34 @@ func (databaseSMSIdentityStore) SaveReceived(identity SMSIdentity, message inbou }) } +func (p *Pool) smsSendOwnerCheck(worker *Worker, selector SMSIdentity) func() error { + checkOwner := p.outboundOwnerCheck(worker) + if selector == (SMSIdentity{}) { + return checkOwner + } + return func() error { + if selector.IMSI != "" && worker.cachedSMSIdentity().IMSI != selector.IMSI { + return ErrSMSSelectorMismatch + } + if err := checkOwner(); err != nil { + return ErrSMSSelectorMismatch + } + return nil + } +} + +func (w *Worker) cachedSMSIdentity() SMSIdentity { + w.cacheMu.RLock() + defer w.cacheMu.RUnlock() + return normalizeSMSIdentity(SMSIdentity{ICCID: w.state.Identity.ICCID, IMSI: w.state.Identity.IMSI}) +} + +func (selector SMSIdentity) matches(identity SMSIdentity) bool { + return selector != (SMSIdentity{}) && + (selector.ICCID == "" || selector.ICCID == identity.ICCID) && + (selector.IMSI == "" || selector.IMSI == identity.IMSI) +} + func (p *Pool) ResolveSMSIdentity(deviceID string) (SMSIdentity, error) { return p.resolveSMSIdentity(deviceID, true) } diff --git a/internal/device/vowifi_sms_send.go b/internal/device/vowifi_sms_send.go index 79977dae..5f05aae3 100644 --- a/internal/device/vowifi_sms_send.go +++ b/internal/device/vowifi_sms_send.go @@ -58,6 +58,9 @@ func sendRoutedSMS( return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome}, err } if csErr := sendCS(); csErr != nil { + if errors.Is(csErr, ErrSMSSelectorMismatch) { + return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome, FellBackToCS: true}, csErr + } if result := csSMSResult(csErr); result.Outcome.DeliveryState != "" { result.FellBackToCS = true return result, csErr @@ -96,6 +99,17 @@ func (p *Pool) SendRoutedSMS( worker *Worker, phone, message string, opts smscodec.SubmitOptions, +) (routedSMSSendResult, error) { + return p.SendRoutedSMSForIdentity(ctx, worker, phone, message, opts, SMSIdentity{}) +} + +// SendRoutedSMSForIdentity binds an explicit SIM selector to the selected worker through submission. +func (p *Pool) SendRoutedSMSForIdentity( + ctx context.Context, + worker *Worker, + phone, message string, + opts smscodec.SubmitOptions, + selector SMSIdentity, ) (routedSMSSendResult, error) { if p == nil { return routedSMSSendResult{}, errors.New("sms route: pool is nil") @@ -105,15 +119,27 @@ func (p *Pool) SendRoutedSMS( } deviceID := worker.ID destination := strings.TrimSpace(phone) - checkOwner := p.outboundOwnerCheck(worker) - identity, identityErr := p.ResolveSMSIdentity(deviceID) - if identityErr != nil { - return routedSMSSendResult{}, fmt.Errorf("sms route: resolve SIM identity: %w", identityErr) + explicitSelector := selector != (SMSIdentity{}) + selector = normalizeSMSIdentity(selector) + checkOwner := p.smsSendOwnerCheck(worker, selector) + identity, err := p.ResolveSMSIdentity(deviceID) + if err != nil { + if explicitSelector && (errors.Is(err, ErrSMSIdentityUnknown) || errors.Is(err, ErrSMSIdentityConflict) || errors.Is(err, ErrSMSIdentityTransitioning)) { + return routedSMSSendResult{}, ErrSMSSelectorMismatch + } + return routedSMSSendResult{}, fmt.Errorf("sms route: resolve SIM identity: %w", err) + } + if explicitSelector && !selector.matches(identity) { + return routedSMSSendResult{}, ErrSMSSelectorMismatch } if err := checkOwner(); err != nil { return routedSMSSendResult{Identity: identity, IdentityRead: true}, err } - if err := p.authorizeSMS(ctx, outboundSMSRequest{Worker: worker, To: destination, Text: message, Options: opts}); err != nil { + request := outboundSMSRequest{Worker: worker, To: destination, Text: message, Options: opts} + if explicitSelector { + request.CheckOwner = checkOwner + } + if err := p.authorizeSMS(ctx, request); err != nil { return routedSMSSendResult{Identity: identity, IdentityRead: true}, err } p.mu.RLock() @@ -147,6 +173,9 @@ func (p *Pool) SendRoutedSMS( } defer release() if err := worker.confirmCSSMSIdentity(ctx, identity, checkOwner); err != nil { + if explicitSelector && errors.Is(err, ErrSMSIdentityConflict) { + return ErrSMSSelectorMismatch + } return err } if sendCSHook != nil { From dccf97b14101be5b40f7fe8965335b9d7b02e1f5 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 22:04:32 +0800 Subject: [PATCH 35/39] chore: simplify SMS dispatch and phone test assertion --- internal/modem/manager.go | 5 ++--- web/tests/phonePresentation.test.ts | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/internal/modem/manager.go b/internal/modem/manager.go index 33bbcb5f..5db54100 100644 --- a/internal/modem/manager.go +++ b/internal/modem/manager.go @@ -733,12 +733,11 @@ func (m *Manager) handleCommand(req commandRequest) { m.handleFileUpload(req) return } - dialect := m.atProfile.dialect() - if dialect.ownedSMSSubmit != nil && req.smsFinalTimeout > 0 { + if req.smsFinalTimeout > 0 { m.handleML307CSMS(req) return } - cpinPresence := dialect.cpinPresence + cpinPresence := m.atProfile.dialect().cpinPresence queryingPresence := cpinPresence != nil && req.cmd == cpinQuery startTime := time.Now() diff --git a/web/tests/phonePresentation.test.ts b/web/tests/phonePresentation.test.ts index 1fde683e..aeadc1c4 100644 --- a/web/tests/phonePresentation.test.ts +++ b/web/tests/phonePresentation.test.ts @@ -253,7 +253,7 @@ test('wifi calling keeps a dedicated start switch under the mode control', () => assert.match(phoneView, /disableVoWiFi\(selectedDevice\.value\)/) assert.match(phoneView, /打开后开始注册。关掉只停服务,仍是 WiFi calling/) assert.match(phoneView, /if \(mode === selectedMode\.value\) \{[\s\S]*if \(mode === 'wifi'\) return/) - assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\) \|\| \(!!selectedModeBlocked && !selected\?\.vowifi_enabled\)"/) + assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\)/) assert.doesNotMatch(phoneView, /modePending \|\| !!selected\?\.rf_lock/) assert.match(phoneView, /status === 'recovering' \|\| status === 'waiting_identity'/) assert.match(phoneView, /正在恢复英国身份/) From 8eb1bf4c94114c83278aa27123ede1bf25825a27 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Fri, 20 Nov 2026 11:57:24 +0800 Subject: [PATCH 36/39] fix(modem): retry a missing startup IMEI reply --- internal/modem/imei_probe.go | 16 ++++++++--- internal/modem/imei_probe_test.go | 44 ++++++++++++++++++++++--------- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/internal/modem/imei_probe.go b/internal/modem/imei_probe.go index b8145c76..338b3d32 100644 --- a/internal/modem/imei_probe.go +++ b/internal/modem/imei_probe.go @@ -200,10 +200,18 @@ func closeIMEISerialPortOnCancel(ctx context.Context, port serial.Port, stop <-c } } +var errIMEIReplyUnavailable = errors.New("IMEI reply unavailable") + // verifyOpenedIMEI consumes the entire identity reply before the manager starts // reading URCs or issuing initialization commands on this handle. func (m *Manager) verifyOpenedIMEI(expected string) error { - live, err := readOpenedIMEI(m.port, m.atProfile.dialect(), 1200*time.Millisecond) + const timeout = 1200 * time.Millisecond + dialect := m.atProfile.dialect() + live, err := readOpenedIMEI(m.port, dialect, timeout) + if errors.Is(err, errIMEIReplyUnavailable) { + time.Sleep(250 * time.Millisecond) + live, err = readOpenedIMEI(m.port, dialect, timeout) + } if err != nil { return fmt.Errorf("无法验证 AT 口 %s 的实时 IMEI: %w", m.atPort, err) } @@ -250,14 +258,14 @@ func readOpenedIMEI(port serial.Port, dialect *atDialect, timeout time.Duration) case line == "OK": imei := dialect.imei.parse(response.String()) if imei == "" { - return "", errors.New("empty IMEI response") + return "", fmt.Errorf("%w: empty IMEI response", errIMEIReplyUnavailable) } return imei, nil case line == "ERROR" || strings.HasPrefix(line, "+CME ERROR:") || strings.HasPrefix(line, "+CMS ERROR:"): - return "", fmt.Errorf("IMEI query failed: %s", line) + return "", fmt.Errorf("%w: %s", errIMEIReplyUnavailable, line) } response.WriteString(line + "\n") } } - return "", errors.New("imei probe timeout") + return "", fmt.Errorf("%w: timeout", errIMEIReplyUnavailable) } diff --git a/internal/modem/imei_probe_test.go b/internal/modem/imei_probe_test.go index 57e89c3f..4c320159 100644 --- a/internal/modem/imei_probe_test.go +++ b/internal/modem/imei_probe_test.go @@ -71,8 +71,11 @@ func TestLiveIMEIProbeBypassesCacheForUnchangedTTYNode(t *testing.T) { type openedIMEISerialPort struct { failingSerialPort + probeCommand string + replies [][]string response []string commands atomic.Int32 + probes atomic.Int32 terminalRead atomic.Bool inputFlushed bool earlyInit atomic.Bool @@ -84,10 +87,16 @@ func (p *openedIMEISerialPort) ResetInputBuffer() error { } func (p *openedIMEISerialPort) Write(b []byte) (int, error) { - if p.commands.Add(1) == 1 { - if !p.inputFlushed || string(b) != "AT+CGSN=1\r\n" { - return 0, errors.New("expected IMEI command after flushing stale input") + p.commands.Add(1) + if p.inputFlushed { + p.inputFlushed = false + if string(b) != p.probeCommand || len(p.replies) == 0 { + return 0, errors.New("unexpected IMEI probe") } + p.probes.Add(1) + p.terminalRead.Store(false) + p.response = p.replies[0] + p.replies = p.replies[1:] return len(b), nil } if !p.terminalRead.Load() { @@ -113,21 +122,30 @@ func TestManagerVerifiesTheOpenedPortBeforeATInitialization(t *testing.T) { const expected = "490154203237518" original := openManagerSerialPort t.Cleanup(func() { openManagerSerialPort = original }) + match := []string{"+CGSN: " + expected + "\r\n", "OK\r", "\n"} + empty := []string{"OK\r", "\n"} for _, tc := range []struct { - name, live, wantError string + name, wantError string + profile ATProfile + replies [][]string }{ - {name: "matched", live: expected}, - {name: "replacement", live: "490154203237526", wantError: "实时 IMEI 与配置不匹配"}, - {name: "unreadable", wantError: "无法验证"}, + {name: "matched", profile: ATProfileML307C, replies: [][]string{match}}, + {name: "replacement", profile: ATProfileML307C, replies: [][]string{{"+CGSN: 490154203237526\r\n", "OK\r", "\n"}}, wantError: "实时 IMEI 与配置不匹配"}, + {name: "unreadable after retry", profile: ATProfileML307C, replies: [][]string{empty, empty}, wantError: "无法验证"}, + {name: "default AT retries ERROR", profile: ATProfileDefault, replies: [][]string{{"ERROR\r", "\n"}, {expected + "\r\n", "OK\r", "\n"}}}, + {name: "timeout then matched", profile: ATProfileML307C, replies: [][]string{nil, match}}, } { t.Run(tc.name, func(t *testing.T) { m, err := NewWithATProfile(config.DeviceConfig{ ID: "imei-gate", DeviceBackend: "at", ATPort: filepath.Join(t.TempDir(), "ttyUSB8"), - }, ATProfileML307C) + }, tc.profile) if err != nil { t.Fatal(err) } - port := &openedIMEISerialPort{response: []string{"+CGSN: " + tc.live + "\r\n", "OK\r", "\n"}} + port := &openedIMEISerialPort{ + probeCommand: tc.profile.dialect().imei.command + "\r\n", + replies: tc.replies, + } opens := 0 openManagerSerialPort = func(string, *serial.Mode) (serial.Port, error) { opens++ @@ -137,13 +155,15 @@ func TestManagerVerifiesTheOpenedPortBeforeATInitialization(t *testing.T) { return port, nil } err = m.StartWithExpectedIMEI(expected) - if opens != 2 || !port.terminalRead.Load() || port.earlyInit.Load() { + wantProbes := int32(len(tc.replies)) + if opens != 2 || port.probes.Load() != wantProbes || !port.terminalRead.Load() || port.earlyInit.Load() { m.Stop() - t.Fatalf("opens=%d terminalRead=%v earlyInit=%v", opens, port.terminalRead.Load(), port.earlyInit.Load()) + t.Fatalf("opens=%d probes=%d want=%d terminalRead=%v earlyInit=%v", + opens, port.probes.Load(), wantProbes, port.terminalRead.Load(), port.earlyInit.Load()) } if tc.wantError != "" { if err == nil || !strings.Contains(err.Error(), tc.wantError) || !port.closed.Load() || - m.CanExecuteAT() || port.commands.Load() != 1 { + m.CanExecuteAT() || port.commands.Load() != wantProbes { t.Fatalf("err=%v closed=%v running=%v commands=%d", err, port.closed.Load(), m.CanExecuteAT(), port.commands.Load()) } return From 6b726fdb83550856e09ba7c0415beb00b3155ce0 Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Fri, 20 Nov 2026 12:30:12 +0800 Subject: [PATCH 37/39] docs(api): document native voice availability reason --- internal/api/openapi.hideck.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/api/openapi.hideck.yaml b/internal/api/openapi.hideck.yaml index b618e87c..c8e44655 100644 --- a/internal/api/openapi.hideck.yaml +++ b/internal/api/openapi.hideck.yaml @@ -4007,6 +4007,9 @@ components: phone_region: type: string description: SIM 归属国家或地区的 ISO 3166-1 alpha-2 代码 + native_voice_unavailable_reason: + type: string + description: 设备不支持模组原生语音模式时返回的原因 cellular_ims_unavailable_reason: type: string description: 设备无法通过模组蜂窝数据使用软件 IMS 的原因 From 7b1c7413a77834c4bedc03d63dedd05920037b2e Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Thu, 19 Nov 2026 13:52:25 +0800 Subject: [PATCH 38/39] fix(smscodec): classify WAP payloads before port fallback --- pkg/smscodec/binary_classifier.go | 54 ++++++++++++++------------ pkg/smscodec/binary_classifier_test.go | 14 ++++++- 2 files changed, 43 insertions(+), 25 deletions(-) diff --git a/pkg/smscodec/binary_classifier.go b/pkg/smscodec/binary_classifier.go index 301b8e17..ec10ca39 100644 --- a/pkg/smscodec/binary_classifier.go +++ b/pkg/smscodec/binary_classifier.go @@ -104,8 +104,36 @@ func classifyBinarySMS(t *tpdu.TPDU, msg []byte) binarySMSClassification { c.SummaryLines = append(c.SummaryLines, fmt.Sprintf("wsp_tid=0x%02x pdu=0x%02x", wsp.TransactionID, wsp.PDUType)) } - // OMA CP:优先由端口识别,其次由 content-type 识别。 - if (hasDestPort && destPort == wapPushPort16) || isLikelyOMAContentType(c.ContentType) { + oma := isLikelyOMAContentType(c.ContentType) + si := isLikelySIContentType(c.ContentType) + sl := isLikelySLContentType(c.ContentType) + mms := isLikelyMMSContentType(c.ContentType) + unknownType := !oma && !si && !sl && !mms + + // WAP SI / SL + if si || (unknownType && isLikelySIWBXML(c.Payload)) { + c.Kind = binaryKindWAPSI + c.Label = "WAP SI Push" + addSISLHints(&c, c.Payload) + return c + } + if sl || (unknownType && isLikelySLWBXML(c.Payload)) { + c.Kind = binaryKindWAPSL + c.Label = "WAP SL Push" + addSISLHints(&c, c.Payload) + return c + } + + // MMS Notification + if mms || (unknownType && isLikelyMMSNotification(c.Payload)) { + c.Kind = binaryKindMMSNotification + c.Label = "MMS Notification" + addMMSHints(&c, c.Payload) + return c + } + + // Recognized WAP payloads take precedence over the shared port fallback. + if oma || (hasDestPort && destPort == wapPushPort16) { c.Kind = binaryKindOmaCP c.Label = "OMA CP 运营商配置短信" if cfg, err := DecodeOmaCPFromTPDU(c.Payload); err == nil { @@ -118,28 +146,6 @@ func classifyBinarySMS(t *tpdu.TPDU, msg []byte) binarySMSClassification { return c } - // WAP SI / SL - if isLikelySIContentType(c.ContentType) || isLikelySIWBXML(c.Payload) { - c.Kind = binaryKindWAPSI - c.Label = "WAP SI Push" - addSISLHints(&c, c.Payload) - return c - } - if isLikelySLContentType(c.ContentType) || isLikelySLWBXML(c.Payload) { - c.Kind = binaryKindWAPSL - c.Label = "WAP SL Push" - addSISLHints(&c, c.Payload) - return c - } - - // MMS Notification - if isLikelyMMSContentType(c.ContentType) || isLikelyMMSNotification(c.Payload) { - c.Kind = binaryKindMMSNotification - c.Label = "MMS Notification" - addMMSHints(&c, c.Payload) - return c - } - // SIM OTA (23.048) 分类识别(不解密) if isLikelySIMOTA(t, c.Payload, c.ContentType, hasDestPort, destPort) { c.Kind = binaryKindSIMOTA diff --git a/pkg/smscodec/binary_classifier_test.go b/pkg/smscodec/binary_classifier_test.go index 6d91fee7..deda2b76 100644 --- a/pkg/smscodec/binary_classifier_test.go +++ b/pkg/smscodec/binary_classifier_test.go @@ -60,6 +60,15 @@ func TestClassifyBinarySMS_OmaCPByPort(t *testing.T) { } } +func TestClassifyBinarySMS_ExplicitOMATypeBeatsMMSHint(t *testing.T) { + ct := "application/vnd.wap.connectivity-wbxml\x00" + msg := append([]byte{0x21, 0x06, byte(len(ct))}, []byte(ct)...) + msg = append(msg, 0x8C, 0x82) + if kind := classifyBinarySMS(&tpdu.TPDU{}, msg).Kind; kind != binaryKindOmaCP { + t.Fatalf("explicit OMA content type classified as %s", kind) + } +} + func TestClassifyBinarySMS_WAPSI(t *testing.T) { // WSP header 使用文本 content-type,避免依赖 token 映射。 ct := "application/vnd.wap.sic\x00" @@ -88,7 +97,10 @@ func TestClassifyBinarySMS_MMSNotification(t *testing.T) { msg := append([]byte{0x31, 0x06, byte(len(ct))}, []byte(ct)...) msg = append(msg, body...) - c := classifyBinarySMS(&tpdu.TPDU{}, msg) + tp := &tpdu.TPDU{UDH: tpdu.UserDataHeader{ + {ID: 0x05, Data: []byte{0x0B, 0x84, 0x23, 0xF0}}, + }} + c := classifyBinarySMS(tp, msg) if c.Kind != binaryKindMMSNotification { t.Fatalf("应识别为 MMS Notification,实际: %s", c.Kind) } From efe03c30c8b3471ceafa85877abdee55fcb289dc Mon Sep 17 00:00:00 2001 From: Jiahui Zhu Date: Fri, 20 Nov 2026 13:38:09 +0800 Subject: [PATCH 39/39] fix(esim): reload switched ML307C profiles with RF off --- internal/backend/at_backend.go | 26 +++++++++ internal/device/pool_esim_switch.go | 2 +- internal/device/post_switch_convergence.go | 54 +++++++++++++++++++ .../device/post_switch_convergence_test.go | 51 ++++++++++++++++++ internal/modem/at_profile.go | 7 +++ 5 files changed, 139 insertions(+), 1 deletion(-) diff --git a/internal/backend/at_backend.go b/internal/backend/at_backend.go index c7ba908b..4aca9bf5 100644 --- a/internal/backend/at_backend.go +++ b/internal/backend/at_backend.go @@ -261,6 +261,32 @@ func (a *ATBackend) GetOperatingMode(ctx context.Context) (OperatingMode, error) return OperatingMode(mode), nil } +func (a *ATBackend) SupportsOfflineSIMReload() bool { + return a.modem.ATProfile().SupportsOfflineSIMReload() +} + +// ReloadSIMOffline refreshes the SIM while keeping the radio off. +func (a *ATBackend) ReloadSIMOffline(ctx context.Context) error { + mode, err := a.GetOperatingMode(ctx) + if err != nil { + return err + } + if mode != ModeRFOff { + return fmt.Errorf("offline SIM reload requires CFUN=4, got %d", mode) + } + if err := ctx.Err(); err != nil { + return err + } + + reloadErr := a.SetOperatingMode(ctx, ModeLowPower) + if reloadErr == nil { + time.Sleep(time.Second) + } + // A command that timed out might still have taken effect. + restoreErr := a.SetOperatingMode(ctx, ModeRFOff) + return errors.Join(reloadErr, restoreErr) +} + func (a *ATBackend) Reboot(ctx context.Context) error { _, err := a.modem.ExecuteAT("AT+CFUN=1,1", 5*time.Second) return err diff --git a/internal/device/pool_esim_switch.go b/internal/device/pool_esim_switch.go index e625919f..b2040480 100644 --- a/internal/device/pool_esim_switch.go +++ b/internal/device/pool_esim_switch.go @@ -1276,7 +1276,7 @@ func (p *Pool) handleESIMSwitchAfter(deviceID string, token uint64) { "network_enabled_before", snapshot.NetworkEnabledBefore) convergence := p.runPostSwitchConvergence(deviceID, token, worker, snapshot) - if !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) { + if !p.switchTokenStillCurrent(deviceID, token, "sim_convergence") || !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) { return } if convergence.Degraded { diff --git a/internal/device/post_switch_convergence.go b/internal/device/post_switch_convergence.go index d234e84a..eadf9f36 100644 --- a/internal/device/post_switch_convergence.go +++ b/internal/device/post_switch_convergence.go @@ -3,6 +3,7 @@ package device import ( "context" "errors" + "fmt" "strings" "time" @@ -56,6 +57,13 @@ type postSwitchSIMReloader interface { UIMPostSwitchReload(ctx context.Context, readiness qmimanager.UIMReadiness, opts qmimanager.UIMPostSwitchReloadOptions) (uint8, error) } +// This capability is used only for eSIM recovery, apart from regular radio readiness. +type postSwitchOfflineSIMReloader interface { + SupportsOfflineSIMReload() bool + GetICCIDLive(context.Context) (string, error) + ReloadSIMOffline(context.Context) error +} + type postSwitchSIMPowerController interface { UIMPowerOffSIM(ctx context.Context, slot uint8) error UIMPowerOnSIM(ctx context.Context, slot uint8) error @@ -311,6 +319,48 @@ func effectivePostSwitchReinitWindow(cfg config.ESIMSwitchConfig) time.Duration return 5 * time.Second } +func (p *Pool) convergePostSwitchOfflineSIM(deviceID string, token uint64, worker *Worker, + snapshot esimSwitchContext, reloader postSwitchOfflineSIMReloader, +) postSwitchConvergenceResult { + releaseOperation, err := p.AcquireDeviceOperation(deviceID) + if err != nil { + return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()} + } + defer releaseOperation() + + transition := p.policyTransitionFor(deviceID) + transition.Lock() + defer transition.Unlock() + if !p.switchTokenStillCurrent(deviceID, token, "offline_sim_reload") || !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) { + return postSwitchConvergenceResult{Degraded: true, Reason: "switch_superseded"} + } + + ctx, cancel := context.WithTimeout(p.Context(), 5*time.Second) + defer cancel() + releaseAT, err := p.acquireDeviceAT(ctx, deviceID) + if err != nil { + return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()} + } + defer releaseAT() + + iccid, err := reloader.GetICCIDLive(ctx) + if err != nil { + return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()} + } + current := normalizeSIMIdentityForCompare(iccid) + if current == normalizeSIMIdentityForCompare(snapshot.TargetICCID) { + return postSwitchConvergenceResult{Ready: true, Reason: "target_iccid_already_active"} + } + if current == "" || current != normalizeSIMIdentityForCompare(snapshot.ICCIDBefore) { + return postSwitchConvergenceResult{Degraded: true, Reason: "unexpected_iccid_before_reload"} + } + if err := reloader.ReloadSIMOffline(ctx); err != nil { + return postSwitchConvergenceResult{Degraded: true, Reason: fmt.Sprintf("offline SIM reload: %v", err)} + } + // The common identity refresh still waits for the target ICCID and IMSI. + return postSwitchConvergenceResult{Ready: true, Reason: "offline_sim_reloaded"} +} + func (p *Pool) runPostSwitchConvergence(deviceID string, token uint64, worker *Worker, snapshot esimSwitchContext) postSwitchConvergenceResult { if worker == nil || worker.Backend == nil { return postSwitchConvergenceResult{Degraded: true, Reason: "worker_or_backend_missing"} @@ -318,6 +368,10 @@ func (p *Pool) runPostSwitchConvergence(deviceID string, token uint64, worker *W if resolvedBackendMode(worker.Config) == backend.BackendPCSC { return postSwitchConvergenceResult{Ready: true, Reason: "pcsc_card_reset_complete"} } + if reloader, ok := worker.Backend.(postSwitchOfflineSIMReloader); ok && reloader.SupportsOfflineSIMReload() && + snapshot.FlightModeBefore && !worker.Config.ESIMSwitch.RadioCycle && normalizeSIMIdentityForCompare(snapshot.TargetICCID) != "" { + return p.convergePostSwitchOfflineSIM(deviceID, token, worker, snapshot, reloader) + } readiness, ok := worker.Backend.(postSwitchReadinessProvider) if !ok { return postSwitchConvergenceResult{Degraded: true, Reason: "uim_readiness_not_supported"} diff --git a/internal/device/post_switch_convergence_test.go b/internal/device/post_switch_convergence_test.go index 98776bba..4b2ed295 100644 --- a/internal/device/post_switch_convergence_test.go +++ b/internal/device/post_switch_convergence_test.go @@ -206,6 +206,57 @@ func (s *postSwitchRunBackendStub) UIMPowerOnSIM(ctx context.Context, slot uint8 return nil } +type offlineSIMReloadBackendStub struct { + workerStatusBackendStub + iccid string + reloadCalls int +} + +func (s *offlineSIMReloadBackendStub) SupportsOfflineSIMReload() bool { return true } + +func (s *offlineSIMReloadBackendStub) GetICCIDLive(context.Context) (string, error) { + return s.iccid, nil +} + +func (s *offlineSIMReloadBackendStub) ReloadSIMOffline(context.Context) error { + s.reloadCalls++ + return nil +} + +func TestPostSwitchOfflineSIMReloadUsesLiveICCID(t *testing.T) { + const deviceID = "dev-1" + const previousICCID = "8985203103011907194" + const targetICCID = "8985203103011907195" + for _, tc := range []struct { + name, liveICCID string + token uint64 + radioCycle bool + wantReady bool + wantReloads int + }{ + {name: "target already active", liveICCID: targetICCID + "F", token: 2, wantReady: true}, + {name: "old ICCID needs reload", liveICCID: previousICCID, token: 2, wantReady: true, wantReloads: 1}, + {name: "different live card", liveICCID: "8985203103011907196", token: 2}, + {name: "newer switch owns device", liveICCID: previousICCID, token: 1}, + {name: "radio cycle may enable RF", liveICCID: previousICCID, token: 2, radioCycle: true}, + } { + t.Run(tc.name, func(t *testing.T) { + deviceBackend := &offlineSIMReloadBackendStub{iccid: tc.liveICCID} + worker := &Worker{ + ID: deviceID, Backend: deviceBackend, + Config: config.DeviceConfig{ESIMSwitch: config.ESIMSwitchConfig{RadioCycle: tc.radioCycle}}, + } + pool := &Pool{workers: map[string]*Worker{deviceID: worker}, switchTokens: map[string]uint64{deviceID: 2}} + snapshot := esimSwitchContext{ICCIDBefore: previousICCID, TargetICCID: targetICCID, FlightModeBefore: true} + result := pool.runPostSwitchConvergence(deviceID, tc.token, worker, snapshot) + if result.Ready != tc.wantReady || result.Degraded == tc.wantReady || deviceBackend.reloadCalls != tc.wantReloads { + t.Fatalf("result=%+v, reloads=%d; want ready=%t and reloads=%d", + result, deviceBackend.reloadCalls, tc.wantReady, tc.wantReloads) + } + }) + } +} + func TestRunPostSwitchConvergenceFlagOffUsesLegacyPollingOnly(t *testing.T) { worker := &Worker{Config: config.DeviceConfig{}} backend := &postSwitchRunBackendStub{ diff --git a/internal/modem/at_profile.go b/internal/modem/at_profile.go index dc523b81..0c731c1c 100644 --- a/internal/modem/at_profile.go +++ b/internal/modem/at_profile.go @@ -50,6 +50,7 @@ type atDialect struct { simStatus string cpinPresence *atCPINPresenceQuery parseCCHO func(string) (int, bool) + offlineSIMReload bool voiceInit []string ownedSMSSubmit *atOwnedSMSSubmit } @@ -83,6 +84,7 @@ var ml307cATDialect = atDialect{ radio: atRadioQuery{"AT+COPS?", parseCOPSRadio}, cpinPresence: &atCPINPresenceQuery{parse: parseML307CCPIN, isAbsentError: isML307CNoSIMError}, parseCCHO: parseML307CCCHO, + offlineSIMReload: true, ownedSMSSubmit: &atOwnedSMSSubmit{promptTimeout: ml307cSMSPromptTimeout, finalTimeout: ml307cSMSResultTimeout}, } @@ -93,6 +95,11 @@ func (profile ATProfile) dialect() *atDialect { return &defaultATDialect } +// SupportsOfflineSIMReload reports whether the SIM can reload without enabling RF. +func (profile ATProfile) SupportsOfflineSIMReload() bool { + return profile.dialect().offlineSIMReload +} + func parseML307CIMEI(resp string) string { if line, ok := findLineWithPrefix(resp, "+CGSN:"); ok { return parseIMEI(strings.TrimPrefix(line, "+CGSN:"))