diff --git a/cmd/hideck/main.go b/cmd/hideck/main.go index cea9c8a8..045c93d2 100644 --- a/cmd/hideck/main.go +++ b/cmd/hideck/main.go @@ -304,7 +304,7 @@ func main() { } } - if err := pool.Shutdown(); err != nil { + if err := pool.ShutdownContext(shutdownCtx); err != nil { logger.Error("关闭工作器池时出错", "err", err) } qmi.StopStartedProxy() diff --git a/internal/backend/at_backend.go b/internal/backend/at_backend.go index f9b3021a..ca8a945a 100644 --- a/internal/backend/at_backend.go +++ b/internal/backend/at_backend.go @@ -80,7 +80,7 @@ func (a *ATBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) { info.SINR = cell.SINR } - return info, nil + return normalizeSignalInfo(info), nil } func (a *ATBackend) GetServingSystem(ctx context.Context) (*ServingSystem, error) { diff --git a/internal/backend/mbim_backend.go b/internal/backend/mbim_backend.go index e5c4a38d..cd6aa79d 100644 --- a/internal/backend/mbim_backend.go +++ b/internal/backend/mbim_backend.go @@ -98,7 +98,7 @@ func (b *MBIMBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) { if s.HasSNR { info.SINR = s.SNR } - return info, nil + return normalizeSignalInfo(info), nil } func (b *MBIMBackend) GetServingSystem(ctx context.Context) (*ServingSystem, error) { diff --git a/internal/backend/mbim_backend_test.go b/internal/backend/mbim_backend_test.go index a4109133..6ceb8438 100644 --- a/internal/backend/mbim_backend_test.go +++ b/internal/backend/mbim_backend_test.go @@ -386,6 +386,9 @@ func TestMBIMBackendSignalInfoFillsRsrpSinrFromV2(t *testing.T) { if si.RSRP != -85 { t.Fatalf("RSRP = %d, want -85", si.RSRP) } + if si.RSSI != -85 { + t.Fatalf("RSSI = %d, want RSRP fallback -85", si.RSSI) + } if si.SINR != 10 { t.Fatalf("SINR = %d, want 10", si.SINR) } diff --git a/internal/backend/qmi_backend.go b/internal/backend/qmi_backend.go index f0cd92d5..caef0f81 100644 --- a/internal/backend/qmi_backend.go +++ b/internal/backend/qmi_backend.go @@ -313,7 +313,7 @@ func (q *QMIBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) { } if hasSnapshotData { - return info, nil + return normalizeSignalInfo(info), nil } // 首先使用 NAS GetSignalInfo(字段最全,1 次 IPC) @@ -352,7 +352,7 @@ func (q *QMIBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) { } } - return info, nil + return normalizeSignalInfo(info), nil } func (q *QMIBackend) GetServingSystem(ctx context.Context) (*ServingSystem, error) { diff --git a/internal/backend/signal_display.go b/internal/backend/signal_display.go new file mode 100644 index 00000000..4bc1cbfb --- /dev/null +++ b/internal/backend/signal_display.go @@ -0,0 +1,37 @@ +package backend + +// QMI / 高通 NAS 在 LTE 上经常把 GSM RSSI 填成这些占位值,不是真实覆盖。 +const ( + qmiUnavailableRSSI = -125 + qmiMinInt8RSSI = -128 + legacyInvalidRSSI = -999 +) + +// IsPlaceholderRSSI 判断 RSSI 是否为“未测量/不可用”,不能当信号格用。 +func IsPlaceholderRSSI(rssi int) bool { + switch rssi { + case 0, qmiUnavailableRSSI, qmiMinInt8RSSI, legacyInvalidRSSI: + return true + default: + return false + } +} + +// DisplaySignalDBM 给页面/API 的主信号:有效 RSSI 优先,否则用 LTE RSRP。 +func DisplaySignalDBM(rssi, rsrp int) int { + if !IsPlaceholderRSSI(rssi) { + return rssi + } + if !IsPlaceholderRSSI(rsrp) { + return rsrp + } + return 0 +} + +func normalizeSignalInfo(info *SignalInfo) *SignalInfo { + if info == nil { + return nil + } + info.RSSI = DisplaySignalDBM(info.RSSI, info.RSRP) + return info +} diff --git a/internal/backend/signal_display_test.go b/internal/backend/signal_display_test.go new file mode 100644 index 00000000..b48b8023 --- /dev/null +++ b/internal/backend/signal_display_test.go @@ -0,0 +1,39 @@ +package backend + +import "testing" + +func TestDisplaySignalDBMFallsBackToRSRPWhenRSSIIsQMIPlaceholder(t *testing.T) { + t.Parallel() + + if got := DisplaySignalDBM(-125, -86); got != -86 { + t.Fatalf("DisplaySignalDBM(-125, -86)=%d, want -86", got) + } + if got := DisplaySignalDBM(-128, -90); got != -90 { + t.Fatalf("DisplaySignalDBM(-128, -90)=%d, want -90", got) + } + if got := DisplaySignalDBM(0, -80); got != -80 { + t.Fatalf("DisplaySignalDBM(0, -80)=%d, want -80", got) + } + if got := DisplaySignalDBM(-72, -86); got != -72 { + t.Fatalf("valid RSSI should win, got %d", got) + } + if got := DisplaySignalDBM(-125, 0); got != 0 { + t.Fatalf("both placeholders should yield 0, got %d", got) + } + if got := DisplaySignalDBM(-125, -125); got != 0 { + t.Fatalf("placeholder RSRP should not be reused, got %d", got) + } +} + +func TestIsPlaceholderRSSI(t *testing.T) { + t.Parallel() + + for _, rssi := range []int{0, -125, -128, -999} { + if !IsPlaceholderRSSI(rssi) { + t.Fatalf("rssi=%d should be placeholder", rssi) + } + } + if IsPlaceholderRSSI(-86) || IsPlaceholderRSSI(-105) { + t.Fatal("real LTE values must not be placeholders") + } +} diff --git a/internal/device/pool.go b/internal/device/pool.go index 6ee562f1..38da37ae 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -199,6 +199,8 @@ type Pool struct { voiceGateway *voicehost.Gateway volteCtl *volte.Controller + atPortMu sync.Mutex + atPortLocks map[string]*sync.Mutex // VoWiFi host 侧整合(多实例) vowifiHost *vowifihost.Manager @@ -275,6 +277,7 @@ func NewPoolWithDynamicInterfaceMapper(cfg *config.Config, mapper DynamicInterfa runtimeQMIAttachments: make(map[string]config.DeviceConfig), vowifiMWI: make(map[string]VoWiFiMWIState), smscCache: make(map[string]string), + atPortLocks: make(map[string]*sync.Mutex), } p.transportRecovery = NewTransportRecoveryController(p) p.voWiFiHost().ConfigureAdapter(p) @@ -474,7 +477,7 @@ func (w *Worker) collectRuntimeStatus(ctx context.Context, reason string) modem. call(func() { if sig, err := w.Backend.GetSignalInfo(ctx); err == nil && sig != nil { mu.Lock() - status.SignalDBM = sig.RSSI + status.SignalDBM = backend.DisplaySignalDBM(sig.RSSI, sig.RSRP) status.SignalRSRP = sig.RSRP status.SignalRSRQ = sig.RSRQ status.SignalSINR = sig.SINR @@ -2153,7 +2156,7 @@ func (w *Worker) GetStats() map[string]interface{} { var rssi int if w.Backend != nil { if sig, err := w.Backend.GetSignalInfo(context.Background()); err == nil && sig != nil { - rssi = sig.RSSI + rssi = backend.DisplaySignalDBM(sig.RSSI, sig.RSRP) } } else if w.Modem != nil { rssi, _ = w.Modem.CheckSignal() @@ -2391,14 +2394,21 @@ func (p *Pool) NotifyIPChanged(id, oldIP, newIP string, duration time.Duration) } func (p *Pool) Shutdown() error { + return p.ShutdownContext(context.Background()) +} + +func (p *Pool) ShutdownContext(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } // 先关闭所有 VoWiFi 应用实例(确保 XFRMI 接口和 SA/SP 被清理) devIDs := p.voWiFiHost().InstanceIDs() for _, devID := range devIDs { logger.Info("正在关闭 VoWiFi", "device", devID) - _ = p.stopVoWiFiAppForTeardown(context.Background(), devID, "shutdown") + _ = p.stopVoWiFiAppForTeardown(ctx, devID, "shutdown") } - mappingErr := p.removeAllDynamicInterfaceMappings(context.Background()) + mappingErr := p.removeAllDynamicInterfaceMappings(ctx) p.mu.RLock() for _, w := range p.workers { w.stopOnce.Do(func() { @@ -2461,6 +2471,9 @@ func (p *Pool) Shutdown() error { logger.Info("所有工作器已正常关闭") qmi.StopStartedProxy() return mappingErr + case <-ctx.Done(): + qmi.StopStartedProxy() + return errors.Join(mappingErr, ctx.Err()) case <-time.After(5 * time.Second): qmi.StopStartedProxy() return errors.Join(mappingErr, fmt.Errorf("关闭超时")) diff --git a/internal/device/pool_qmi_mode_test.go b/internal/device/pool_qmi_mode_test.go index 5fb75317..81de7e0c 100644 --- a/internal/device/pool_qmi_mode_test.go +++ b/internal/device/pool_qmi_mode_test.go @@ -612,6 +612,24 @@ func TestMergeRuntimeStatePreservesRadioFieldsOnPartialRefresh(t *testing.T) { } } +func TestMergeRuntimeStateClearsPlaceholderSignalDBM(t *testing.T) { + worker := &Worker{ID: "dev-qmi"} + worker.state.Runtime.SignalDBM = -125 + worker.state.Runtime.SignalRSRP = -86 + + worker.mergeRuntimeStateLocked(modem.DeviceStatus{ + SignalRSRP: -86, + }, true) + + status := worker.ProjectDeviceStatus() + if status.SignalDBM != 0 { + t.Fatalf("placeholder RSSI should be cleared, SignalDBM=%d", status.SignalDBM) + } + if status.SignalRSRP != -86 { + t.Fatalf("RSRP=%d, want -86", status.SignalRSRP) + } +} + func TestWorkerGetDeviceStatusIncludesOperatingModeForATBackend(t *testing.T) { worker := &Worker{ Backend: &workerStatusBackendStub{ diff --git a/internal/device/pool_state.go b/internal/device/pool_state.go index a932e6ba..cc136bd9 100644 --- a/internal/device/pool_state.go +++ b/internal/device/pool_state.go @@ -373,6 +373,8 @@ func (w *Worker) mergeRuntimeStateLocked(status modem.DeviceStatus, healthy bool w.state.Runtime.SimInserted = status.SimInserted if status.SignalDBM != 0 { w.state.Runtime.SignalDBM = status.SignalDBM + } else if backend.IsPlaceholderRSSI(w.state.Runtime.SignalDBM) { + w.state.Runtime.SignalDBM = 0 } if status.SignalRSRP != 0 { w.state.Runtime.SignalRSRP = status.SignalRSRP diff --git a/internal/device/volte.go b/internal/device/volte.go index d098b9ef..8fad72ef 100644 --- a/internal/device/volte.go +++ b/internal/device/volte.go @@ -2,8 +2,10 @@ package device import ( "context" + "errors" "fmt" "strings" + "sync" "time" "github.com/iniwex5/quectel-qmi-go/pkg/qmi" @@ -70,13 +72,56 @@ func (p *Pool) ScheduleNativeVoLTE(deviceID, reason string) { p.scheduleNativeVoLTE(deviceID, reason) } +const nativeVoLTEStartAttempts = 3 + +func nativeVoLTERetryDelay(attempt int) time.Duration { + if attempt < 1 { + attempt = 1 + } + return time.Duration(attempt) * 3 * time.Second +} + +func isTransientVoLTEStartError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, volte.ErrNoUniqueProfile) || + errors.Is(err, volte.ErrVIDPIDMismatch) || + errors.Is(err, ErrLebaraUKRFLocked) { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "timeout") || + strings.Contains(msg, "timed out") || + strings.Contains(msg, "busy") +} + func (p *Pool) scheduleNativeVoLTE(deviceID, reason string) { if p == nil || strings.TrimSpace(deviceID) == "" { return } go func() { - if err := p.EnableNativeVoLTE(deviceID); err != nil { - logger.Warn("启动原生 VoLTE 失败", "device", deviceID, "reason", reason, "err", err) + var err error + for attempt := 1; attempt <= nativeVoLTEStartAttempts; attempt++ { + if !p.IsNativeVoLTE(deviceID) { + return + } + err = p.EnableNativeVoLTE(deviceID) + if err == nil { + return + } + if !isTransientVoLTEStartError(err) || attempt == nativeVoLTEStartAttempts { + logger.Warn("启动原生 VoLTE 失败", "device", deviceID, "reason", reason, "attempt", attempt, "err", err) + return + } + logger.Warn("启动原生 VoLTE 将重试", "device", deviceID, "reason", reason, "attempt", attempt, "err", err) + timer := time.NewTimer(nativeVoLTERetryDelay(attempt)) + select { + case <-p.Context().Done(): + timer.Stop() + return + case <-timer.C: + } } }() } @@ -98,6 +143,8 @@ func (p *Pool) ExecuteAT(deviceID, cmd string, timeout time.Duration) (string, e if port == "" { return "", fmt.Errorf("设备 %s 没有 AT 口", deviceID) } + unlock := p.lockDeviceAT(deviceID) + defer unlock() session, err := modem.NewSerialAT(port, 115200, 8, 1, "N") if err != nil { return "", fmt.Errorf("打开 AT 口 %s: %w", port, err) @@ -106,6 +153,21 @@ func (p *Pool) ExecuteAT(deviceID, cmd string, timeout time.Duration) (string, e return session.Execute(cmd, timeout) } +func (p *Pool) lockDeviceAT(deviceID string) func() { + p.atPortMu.Lock() + if p.atPortLocks == nil { + p.atPortLocks = map[string]*sync.Mutex{} + } + mu := p.atPortLocks[deviceID] + if mu == nil { + mu = &sync.Mutex{} + p.atPortLocks[deviceID] = mu + } + p.atPortMu.Unlock() + mu.Lock() + return mu.Unlock +} + func (p *Pool) StopSoftwareIMS(deviceID string) error { if p == nil { return nil diff --git a/internal/device/volte_retry_test.go b/internal/device/volte_retry_test.go new file mode 100644 index 00000000..7f6313cc --- /dev/null +++ b/internal/device/volte_retry_test.go @@ -0,0 +1,24 @@ +package device + +import ( + "errors" + "testing" + "time" + + "github.com/yibaiba/hideck/internal/volte" +) + +func TestIsTransientVoLTEStartError(t *testing.T) { + if isTransientVoLTEStartError(nil) { + t.Fatal("nil") + } + if isTransientVoLTEStartError(volte.ErrNoUniqueProfile) || isTransientVoLTEStartError(ErrLebaraUKRFLocked) { + t.Fatal("permanent errors must not retry") + } + if !isTransientVoLTEStartError(errors.New("volte provision apply_ims: read before apply: query mbn list: timeout")) { + t.Fatal("AT timeout must retry") + } + if nativeVoLTERetryDelay(1) != 3*time.Second || nativeVoLTERetryDelay(2) != 6*time.Second { + t.Fatalf("retry delay %s %s", nativeVoLTERetryDelay(1), nativeVoLTERetryDelay(2)) + } +} diff --git a/internal/volte/at_exec.go b/internal/volte/at_exec.go new file mode 100644 index 00000000..c9a6faad --- /dev/null +++ b/internal/volte/at_exec.go @@ -0,0 +1,57 @@ +package volte + +import ( + "errors" + "strings" + "time" +) + +const ( + mbnListTimeout = 30 * time.Second + atRetryPause = 200 * time.Millisecond + atTimeoutRetries = 1 +) + +func atTimeout(cmd string) time.Duration { + switch strings.TrimSpace(cmd) { + case MBNListQueryCommand(), MBNActivateCommand(): + return mbnListTimeout + default: + return defaultATTimeout + } +} + +func isATTimeout(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "timeout") || strings.Contains(msg, "timed out") +} + +func execAT(at ATTransport, deviceID, cmd string) (string, error) { + if at == nil { + return "", errors.New("volte provision: AT transport is not configured") + } + timeout := atTimeout(cmd) + var ( + lastResp string + last error + ) + attempts := 1 + atTimeoutRetries + for i := 0; i < attempts; i++ { + if i > 0 { + time.Sleep(atRetryPause) + } + resp, err := at.ExecuteAT(deviceID, cmd, timeout) + err = atResult(resp, err) + if err == nil { + return resp, nil + } + lastResp, last = resp, err + if !isATTimeout(err) { + return resp, err + } + } + return lastResp, last +} diff --git a/internal/volte/at_exec_test.go b/internal/volte/at_exec_test.go new file mode 100644 index 00000000..5eddc708 --- /dev/null +++ b/internal/volte/at_exec_test.go @@ -0,0 +1,27 @@ +package volte + +import ( + "errors" + "testing" +) + +func TestATTimeoutForMBNList(t *testing.T) { + if got := atTimeout(MBNListQueryCommand()); got != mbnListTimeout { + t.Fatalf("list timeout %s", got) + } + if got := atTimeout(MBNActivateCommand()); got != mbnListTimeout { + t.Fatalf("activate timeout %s", got) + } + if got := atTimeout(IMSQueryCommand()); got != defaultATTimeout { + t.Fatalf("ims timeout %s", got) + } +} + +func TestIsATTimeout(t *testing.T) { + if !isATTimeout(errors.New("timeout")) || !isATTimeout(errors.New("query mbn list: timeout")) { + t.Fatal("want timeout detection") + } + if isATTimeout(errors.New("AT ERROR")) || isATTimeout(nil) { + t.Fatal("non-timeout must not retry") + } +} diff --git a/internal/volte/controller.go b/internal/volte/controller.go index c8542995..5e8412f6 100644 --- a/internal/volte/controller.go +++ b/internal/volte/controller.go @@ -111,7 +111,7 @@ func (c *Controller) Enable(ctx context.Context, deviceID string) error { if err := c.host.StopSoftwareIMS(deviceID); err != nil { return c.fail(deviceID, fmt.Errorf("stop software IMS: %w", err)) } - if _, err := c.host.ExecuteAT(deviceID, COPSNumericFormatCommand(), defaultATTimeout); err != nil { + if _, err := execAT(c.host, deviceID, COPSNumericFormatCommand()); err != nil { logger.Debug("AT+COPS=3,2 失败,继续用当前 COPS 格式", "device", deviceID, "err", err) } if err := c.waitLTE(ctx, deviceID); err != nil { @@ -225,17 +225,12 @@ func (c *Controller) provisionConfig(ctx context.Context, deviceID string) error return c.fail(deviceID, fmt.Errorf("read serving PLMN: %w", plmnErr)) } c.patch(deviceID, func(st *Status) { st.PLMN = NormalizePLMN(mcc, mnc) }) - name, mbnErr := c.resolveMBN(deviceID, mcc, mnc) - if mbnErr != nil { - return c.fail(deviceID, mbnErr) - } - c.patch(deviceID, func(st *Status) { st.MBNName = name }) desired := Desired{ IMSEnabled: boolPtr(true), VoLTEEnabled: boolPtr(true), UACEnabled: boolPtr(true), - MBNSelect: &name, - MBNAutoSel: boolPtr(false), + MCC: mcc, + MNC: mnc, } res, err := c.provision.Ensure(ctx, deviceID, desired) c.applyProvision(deviceID, res) @@ -269,6 +264,11 @@ func (c *Controller) applyProvision(deviceID string, res Result) { st.RebootRequired = res.RebootRequired || res.Current.UACEnabled st.ProvisionStage = res.Stage st.IMEITail = res.IMEITail + if name := strings.TrimSpace(res.Current.MBNName); name != "" { + st.MBNName = name + } else if name := strings.TrimSpace(res.Target.MBNName); name != "" { + st.MBNName = name + } }) } @@ -436,28 +436,16 @@ func (c *Controller) patch(deviceID string, fn func(*Status)) { } func (c *Controller) readPLMN(deviceID string) (string, string, error) { - resp, err := c.host.ExecuteAT(deviceID, COPSQueryCommand(), defaultATTimeout) + resp, err := execAT(c.host, deviceID, COPSQueryCommand()) if err != nil { return "", "", err } return ParseCOPS(resp) } -func (c *Controller) resolveMBN(deviceID, mcc, mnc string) (string, error) { - resp, err := c.host.ExecuteAT(deviceID, MBNListQueryCommand(), defaultATTimeout) - if err != nil { - return "", err - } - entries, err := ParseMBNList(resp) - if err != nil { - return "", err - } - return UniqueMBN(mcc, mnc, entries) -} - func (c *Controller) waitLTE(ctx context.Context, deviceID string) error { check := func() error { - resp, err := c.host.ExecuteAT(deviceID, CEREGQueryCommand(), defaultATTimeout) + resp, err := execAT(c.host, deviceID, CEREGQueryCommand()) if err != nil { return fmt.Errorf("query CEREG: %w", err) } @@ -488,7 +476,7 @@ func (c *Controller) waitLTE(ctx context.Context, deviceID string) error { } func (c *Controller) activateIMSPDN(deviceID string) error { - resp, err := c.host.ExecuteAT(deviceID, CGDCONTQueryCommand(), defaultATTimeout) + resp, err := execAT(c.host, deviceID, CGDCONTQueryCommand()) if err != nil { return fmt.Errorf("query CGDCONT: %w", err) } @@ -500,7 +488,7 @@ func (c *Controller) activateIMSPDN(deviceID string) error { if !ok { return fmt.Errorf("volte: no IMS APN in CGDCONT") } - actResp, err := c.host.ExecuteAT(deviceID, CGACTQueryCommand(), defaultATTimeout) + actResp, err := execAT(c.host, deviceID, CGACTQueryCommand()) if err != nil { return fmt.Errorf("query CGACT: %w", err) } @@ -509,10 +497,10 @@ func (c *Controller) activateIMSPDN(deviceID string) error { return err } if !active[ims.CID] { - if _, err := c.host.ExecuteAT(deviceID, CGACTSetCommand(ims.CID, true), defaultATTimeout); err != nil { + if _, err := execAT(c.host, deviceID, CGACTSetCommand(ims.CID, true)); err != nil { return fmt.Errorf("activate IMS PDN cid %d: %w", ims.CID, err) } - actResp, err = c.host.ExecuteAT(deviceID, CGACTQueryCommand(), defaultATTimeout) + actResp, err = execAT(c.host, deviceID, CGACTQueryCommand()) if err != nil { return fmt.Errorf("re-query CGACT: %w", err) } diff --git a/internal/volte/controller_test.go b/internal/volte/controller_test.go index 513058f5..b4354447 100644 --- a/internal/volte/controller_test.go +++ b/internal/volte/controller_test.go @@ -3,6 +3,7 @@ package volte import ( "context" "errors" + "strings" "testing" "github.com/iniwex5/quectel-qmi-go/pkg/qmi" @@ -131,8 +132,8 @@ func TestControllerRejectsUnknownPLMNWithoutGuessingMBN(t *testing.T) { host := newFakeModem() host.COPS = "23433" ctl := NewControllerWithBackup(host, t.TempDir()) - if err := ctl.Enable(context.Background(), "wwan1"); err == nil { - t.Fatal("UK PLMN must not guess an MBN") + if err := ctl.Enable(context.Background(), "wwan1"); err == nil || !errors.Is(err, ErrNoUniqueProfile) { + t.Fatalf("UK PLMN must not guess an MBN: %v", err) } if ctl.Status("wwan1").Phase != PhaseFailed { t.Fatalf("status %+v", ctl.Status("wwan1")) @@ -155,3 +156,35 @@ func TestControllerKeepsGoingWhenVoLTEBitStuck(t *testing.T) { t.Fatalf("want apply_ims drift recorded, got %+v", st) } } + +func TestControllerQueriesMBNListOnceBeforeIMSWrite(t *testing.T) { + host := newFakeModem() + ctl := NewControllerWithBackup(host, t.TempDir()) + if err := ctl.Enable(context.Background(), "wwan1"); err != nil { + t.Fatal(err) + } + n := 0 + for _, cmd := range host.Commands { + if strings.HasPrefix(cmd, `AT+QCFG="ims",`) { + break + } + if cmd == MBNListQueryCommand() { + n++ + } + } + if n != 1 { + t.Fatalf("want 1 MBN list before IMS write, got %d in %v", n, host.Commands) + } +} + +func TestControllerRetriesMBNListTimeout(t *testing.T) { + host := newFakeModem() + host.ListTimeouts = 1 + ctl := NewControllerWithBackup(host, t.TempDir()) + if err := ctl.Enable(context.Background(), "wwan1"); err != nil { + t.Fatal(err) + } + if st := ctl.Status("wwan1"); st.MBNName != "Volte_OpenMkt-Commercial-CMCC" { + t.Fatalf("status %+v", st) + } +} diff --git a/internal/volte/fakes_test.go b/internal/volte/fakes_test.go index 3cb16ec3..05f5ad85 100644 --- a/internal/volte/fakes_test.go +++ b/internal/volte/fakes_test.go @@ -2,6 +2,7 @@ package volte import ( "context" + "errors" "fmt" "strconv" "strings" @@ -23,6 +24,7 @@ type FakeModem struct { MBN []MBNEntry FailIMS11 bool Fail map[string]error + ListTimeouts int Commands []string PendingUAC *int NextID string @@ -101,6 +103,10 @@ func (f *FakeModem) ExecuteAT(deviceID, cmd string, _ time.Duration) (string, er case cmd == MBNAutoSelQueryCommand(): return fmt.Sprintf("+QMBNCFG: \"AutoSel\",%d\r\nOK\r\n", f.AutoSel), nil case cmd == MBNListQueryCommand(): + if f.ListTimeouts > 0 { + f.ListTimeouts-- + return "", errors.New("timeout") + } return f.listMBN(), nil case strings.HasPrefix(cmd, `AT+QMBNCFG="autosel",`): bit := 0 diff --git a/internal/volte/provision.go b/internal/volte/provision.go index f9453dca..45b150e2 100644 --- a/internal/volte/provision.go +++ b/internal/volte/provision.go @@ -48,6 +48,8 @@ type Desired struct { UACEnabled *bool MBNAutoSel *bool MBNSelect *string + MCC string + MNC string } type VoiceSettings struct { @@ -158,12 +160,12 @@ func (p *Provisioner) Ensure(ctx context.Context, deviceID string, desired Desir if err != nil { return res, err } - return p.apply(ctx, deviceID, snap, false) + return p.apply(ctx, deviceID, snap, res.Current, true, false) } func (p *Provisioner) Restore(ctx context.Context, deviceID string) (Result, error) { res := Result{DeviceID: deviceID, Stage: StageRestoreIdentity, Restored: false} - current, imei, err := p.readSettings(deviceID) + current, imei, _, err := p.readSettings(deviceID) if err != nil { return res, p.fail(res, StageRestoreIdentity, "read live identity", err) } @@ -182,7 +184,7 @@ func (p *Provisioner) Restore(ctx context.Context, deviceID string) (Result, err if canonHexID(snap.VID) != canonHexID(current.VID) || canonHexID(snap.PID) != canonHexID(current.PID) { return res, p.fail(res, StageRestoreIdentity, "snapshot VID/PID does not match live module", ErrVIDPIDMismatch) } - applied, err := p.apply(ctx, deviceID, snap.withTarget(snap.Original), true) + applied, err := p.apply(ctx, deviceID, snap.withTarget(snap.Original), current, true, true) if err != nil { applied.Restored = false stage := applied.Stage @@ -215,13 +217,23 @@ func (s Snapshot) withTarget(target VoiceSettings) Snapshot { func (p *Provisioner) capture(ctx context.Context, deviceID string, desired Desired) (Result, Snapshot, error) { _ = ctx res := Result{DeviceID: deviceID, Stage: StageIdentity, Restored: false} - current, imei, err := p.readSettings(deviceID) + current, imei, entries, err := p.readSettings(deviceID) if err != nil { return res, Snapshot{}, p.fail(res, StageIdentity, "read module identity", err) } res.IMEITail = IMEITail(imei) res.Current = current res.Original = current + if strings.TrimSpace(desired.MCC) != "" && desired.MBNSelect == nil { + name, mbnErr := UniqueMBN(desired.MCC, desired.MNC, entries) + if mbnErr != nil { + return res, Snapshot{}, p.fail(res, StageIdentity, "select MBN", mbnErr) + } + desired.MBNSelect = &name + if desired.MBNAutoSel == nil { + desired.MBNAutoSel = boolPtr(false) + } + } target := overlayDesired(current, desired) if canonHexID(target.VID) != canonHexID(current.VID) || canonHexID(target.PID) != canonHexID(current.PID) { return res, Snapshot{}, p.fail(res, StageIdentity, "refusing VID/PID change", ErrVIDPIDMismatch) @@ -261,7 +273,7 @@ func (p *Provisioner) capture(ctx context.Context, deviceID string, desired Desi return res, snap, nil } -func (p *Provisioner) apply(ctx context.Context, deviceID string, snap Snapshot, restoring bool) (Result, error) { +func (p *Provisioner) apply(ctx context.Context, deviceID string, snap Snapshot, live VoiceSettings, haveLive, restoring bool) (Result, error) { res := Result{ DeviceID: deviceID, IMEITail: IMEITail(snap.IMEI), @@ -273,13 +285,23 @@ func (p *Provisioner) apply(ctx context.Context, deviceID string, snap Snapshot, if path, err := p.store.PathFor(snap.IMEI); err == nil { res.SnapshotPath = path } - current, imei, err := p.readSettings(deviceID) - if err != nil { - stage := StageApplyIMS - if restoring { - stage = StageRestoreWrite + var ( + current VoiceSettings + imei string + err error + ) + if haveLive { + current = live + imei = snap.IMEI + } else { + current, imei, _, err = p.readSettings(deviceID) + if err != nil { + stage := StageApplyIMS + if restoring { + stage = StageRestoreWrite + } + return res, p.fail(res, stage, "read before apply", err) } - return res, p.fail(res, stage, "read before apply", err) } if imei != snap.IMEI { stage := StageIdentity @@ -323,7 +345,7 @@ func (p *Provisioner) apply(ctx context.Context, deviceID string, snap Snapshot, res.DeviceID = newID } - current, imei, err = p.readSettings(deviceID) + current, imei, _, err = p.readSettings(deviceID) if err != nil { return res, p.fail(res, StageVerify, "re-read after apply", err) } @@ -368,7 +390,7 @@ func (p *Provisioner) applyIMS(deviceID string, res *Result) error { return p.fail(*res, StageApplyIMS, "write IMS/VoLTE", last) } res.Written = appendUnique(res.Written, "ims") - current, _, err := p.readSettings(deviceID) + current, _, _, err := p.readSettings(deviceID) if err != nil { return p.fail(*res, StageApplyIMS, "re-query IMS", err) } @@ -412,7 +434,7 @@ func (p *Provisioner) applyMBN(deviceID string, res *Result) error { } res.Written = appendUnique(res.Written, "mbn_autosel") } - current, _, err := p.readSettings(deviceID) + current, _, _, err := p.readSettings(deviceID) if err != nil { return p.fail(*res, StageApplyMBN, "re-query MBN", err) } @@ -440,7 +462,7 @@ func (p *Provisioner) applyUSBCFG(deviceID string, res *Result) error { } res.Written = appendUnique(res.Written, "usbcfg") res.RebootRequired = true - current, _, err := p.readSettings(deviceID) + current, _, _, err := p.readSettings(deviceID) if err != nil { return p.fail(*res, StageApplyUSBCFG, "re-query USBCFG", err) } @@ -448,43 +470,43 @@ func (p *Provisioner) applyUSBCFG(deviceID string, res *Result) error { return nil } -func (p *Provisioner) readSettings(deviceID string) (VoiceSettings, string, error) { +func (p *Provisioner) readSettings(deviceID string) (VoiceSettings, string, []MBNEntry, error) { imei, err := p.readIMEI(deviceID) if err != nil { - return VoiceSettings{}, "", err + return VoiceSettings{}, "", nil, err } imsResp, err := p.exec(deviceID, IMSQueryCommand()) if err != nil { - return VoiceSettings{}, imei, fmt.Errorf("query IMS: %w", err) + return VoiceSettings{}, imei, nil, fmt.Errorf("query IMS: %w", err) } ims, err := ParseIMSConfig(imsResp) if err != nil { - return VoiceSettings{}, imei, err + return VoiceSettings{}, imei, nil, err } var usb USBConfig usbResp, usbErr := p.exec(deviceID, USBConfigQueryCommand()) if usbErr == nil { parsed, parseErr := ParseUSBConfig(usbResp) if parseErr != nil { - return VoiceSettings{}, imei, parseErr + return VoiceSettings{}, imei, nil, parseErr } usb = parsed } autoResp, err := p.exec(deviceID, MBNAutoSelQueryCommand()) if err != nil { - return VoiceSettings{}, imei, fmt.Errorf("query mbn autosel: %w", err) + return VoiceSettings{}, imei, nil, fmt.Errorf("query mbn autosel: %w", err) } autoSel, _, err := ParseMBNAutoSel(autoResp) if err != nil { - return VoiceSettings{}, imei, err + return VoiceSettings{}, imei, nil, err } listResp, err := p.exec(deviceID, MBNListQueryCommand()) if err != nil { - return VoiceSettings{}, imei, fmt.Errorf("query mbn list: %w", err) + return VoiceSettings{}, imei, nil, fmt.Errorf("query mbn list: %w", err) } entries, err := ParseMBNList(listResp) if err != nil { - return VoiceSettings{}, imei, err + return VoiceSettings{}, imei, nil, err } selected, _ := SelectedMBN(entries) return VoiceSettings{ @@ -497,7 +519,7 @@ func (p *Provisioner) readSettings(deviceID string) (VoiceSettings, string, erro MBNAutoSel: autoSel, MBNName: selected.Name, MBNIndex: selected.Index, - }, imei, nil + }, imei, entries, nil } func (p *Provisioner) readIMEI(deviceID string) (string, error) { @@ -522,11 +544,10 @@ func (p *Provisioner) readIMEI(deviceID string) (string, error) { } func (p *Provisioner) exec(deviceID, cmd string) (string, error) { - if p == nil || p.at == nil { + if p == nil { return "", errors.New("volte provision: AT transport is not configured") } - resp, err := p.at.ExecuteAT(deviceID, cmd, defaultATTimeout) - return resp, atResult(resp, err) + return execAT(p.at, deviceID, cmd) } func (p *Provisioner) fail(res Result, stage, message string, err error) error { diff --git a/internal/volte/provision_test.go b/internal/volte/provision_test.go index 476c6fe1..7eaaba0a 100644 --- a/internal/volte/provision_test.go +++ b/internal/volte/provision_test.go @@ -280,3 +280,58 @@ func TestMidApplyUSBCFGFailureKeepsIMSWriteAndReportsStage(t *testing.T) { t.Fatal("IMS write should have happened before USBCFG failure") } } + +func TestEnsureDoesNotRereadMBNListBeforeApply(t *testing.T) { + modem := newFakeModem() + p := NewProvisioner(modem, &MemoryStore{}) + if _, err := p.Ensure(context.Background(), "wwan1", Desired{IMSEnabled: boolPtr(true), VoLTEEnabled: boolPtr(true)}); err != nil { + t.Fatal(err) + } + lists := 0 + for _, cmd := range modem.Commands { + if strings.HasPrefix(cmd, `AT+QCFG="ims",`) { + break + } + if cmd == MBNListQueryCommand() { + lists++ + } + } + if lists != 1 { + t.Fatalf("want one MBN list before IMS write, got %d in %v", lists, modem.Commands) + } +} + +func TestEnsureRetriesMBNListTimeout(t *testing.T) { + modem := newFakeModem() + modem.ListTimeouts = 1 + p := NewProvisioner(modem, &MemoryStore{}) + if _, err := p.Ensure(context.Background(), "wwan1", Desired{IMSEnabled: boolPtr(true), VoLTEEnabled: boolPtr(true)}); err != nil { + t.Fatal(err) + } +} + +func TestEnsureSelectsMBNFromCapturedList(t *testing.T) { + modem := newFakeModem() + p := NewProvisioner(modem, &MemoryStore{}) + res, err := p.Ensure(context.Background(), "wwan1", Desired{ + IMSEnabled: boolPtr(true), + VoLTEEnabled: boolPtr(true), + MCC: "460", + MNC: "00", + }) + if err != nil && !errors.Is(err, ErrRebootRequired) { + t.Fatal(err) + } + if res.Target.MBNName != "Volte_OpenMkt-Commercial-CMCC" { + t.Fatalf("target MBN %q", res.Target.MBNName) + } + var sawSelect bool + for _, cmd := range modem.Commands { + if cmd == MBNSelectCommand("Volte_OpenMkt-Commercial-CMCC") { + sawSelect = true + } + } + if !sawSelect { + t.Fatalf("did not select CMCC profile: %v", modem.Commands) + } +} diff --git a/web/src/components/DeviceOverviewTab.vue b/web/src/components/DeviceOverviewTab.vue index bd0d79bc..d91a8c1d 100644 --- a/web/src/components/DeviceOverviewTab.vue +++ b/web/src/components/DeviceOverviewTab.vue @@ -3,6 +3,7 @@ import { ref, computed } from 'vue' import type { DeviceOverviewItem } from '../types/api' import { isControlOnline, isRadioRegistered, isRecoveryPhase, lifecycleStatusLabel } from '../utils/deviceLifecycle' import { phoneModeCampsOnCell } from '../utils/phoneMode' +import { displaySignalDbm, hasValidSignalDbm } from '../utils/signalPresentation' import StatusLight from './StatusLight.vue' import OperatorSelectionDialog from './OperatorSelectionDialog.vue' import { Settings24Regular } from '@vicons/fluent' @@ -27,7 +28,6 @@ const emit = defineEmits<{ }>() const showOperatorSelection = ref(false) -const QMI_INVALID_SIGNAL_DBM = -128 const trafficStateLabel = computed(() => { const status = props.device?.traffic_meta?.status @@ -47,24 +47,25 @@ const trafficUploadRateDisplay = computed(() => props.trafficSpeedTx || trafficS // ---- 蜂窝模式计算属性 ---- -function hasValidSignalDbm(dbm: number | null | undefined): dbm is number { - return typeof dbm === 'number' && Number.isFinite(dbm) && dbm > QMI_INVALID_SIGNAL_DBM && dbm !== 0 -} - function signalMetricDisplay(value: number | null | undefined): number | '--' { return typeof value === 'number' && Number.isFinite(value) && value !== 0 && value !== -999 ? value : '--' } +const signalDbmValue = computed(() => displaySignalDbm( + props.device?.modem?.signal_dbm, + props.device?.modem?.signal_rsrp +)) + const signalDbmDisplay = computed(() => { - const dbm = props.device?.modem?.signal_dbm - return hasValidSignalDbm(dbm) ? dbm : '--' + const dbm = signalDbmValue.value + return dbm === undefined ? '--' : dbm }) // 0-5 格 const signalLevel = computed(() => { - const dbm = props.device?.modem?.signal_dbm + const dbm = signalDbmValue.value if (!hasValidSignalDbm(dbm)) return 0 if (dbm >= -75) return 5 if (dbm >= -85) return 4 @@ -74,7 +75,7 @@ const signalLevel = computed(() => { }) const signalColor = computed<'green' | 'amber' | 'red' | 'gray'>(() => { - const dbm = props.device?.modem?.signal_dbm + const dbm = signalDbmValue.value if (!hasValidSignalDbm(dbm)) return 'gray' if (dbm >= -85) return 'green' if (dbm >= -100) return 'amber' diff --git a/web/src/utils/dashboardPresentation.ts b/web/src/utils/dashboardPresentation.ts index e14bb087..97874340 100644 --- a/web/src/utils/dashboardPresentation.ts +++ b/web/src/utils/dashboardPresentation.ts @@ -1,4 +1,5 @@ import type { DashboardDevice, VoWiFiRuntimeState } from '../types/api' +import { displaySignalDbm, hasValidSignalDbm } from './signalPresentation' export const DASHBOARD_UNAVAILABLE = '不可用' export const DASHBOARD_UNASSIGNED = '未分配' @@ -37,14 +38,8 @@ export type DashboardOperatorSource = Readonly<{ }> }> -const QMI_INVALID_SIGNAL_DBM = -128 -const LEGACY_INVALID_SIGNAL_DBM = -999 -const SIGNAL_SENTINELS = new Set([0, QMI_INVALID_SIGNAL_DBM, LEGACY_INVALID_SIGNAL_DBM]) - export function hasDashboardSignal(value: unknown): value is number { - return typeof value === 'number' - && Number.isFinite(value) - && !SIGNAL_SENTINELS.has(value) + return hasValidSignalDbm(value) } export function formatDashboardNetworkType(device: DashboardDevice): string { @@ -55,8 +50,12 @@ export function formatDashboardNetworkType(device: DashboardDevice): string { return parts.join(' ') || DASHBOARD_UNAVAILABLE } -export function formatDashboardSignal(value: unknown): string { - return hasDashboardSignal(value) ? `${value} dBm` : DASHBOARD_UNAVAILABLE +export function formatDashboardSignal(value: unknown, rsrp?: unknown): string { + const dbm = displaySignalDbm( + typeof value === 'number' ? value : undefined, + typeof rsrp === 'number' ? rsrp : undefined + ) + return dbm === undefined ? DASHBOARD_UNAVAILABLE : `${dbm} dBm` } export function createDashboardStages( diff --git a/web/src/utils/overviewConnectionPresentation.ts b/web/src/utils/overviewConnectionPresentation.ts index d082642b..8bb360a2 100644 --- a/web/src/utils/overviewConnectionPresentation.ts +++ b/web/src/utils/overviewConnectionPresentation.ts @@ -4,6 +4,7 @@ import { formatDashboardSignal, hasDashboardSignal } from './dashboardPresentation' +import { displaySignalDbm } from './signalPresentation' import { isNativeVoLTEMode, phoneModeCampsOnCell } from './phoneMode' export type OverviewConnectionKind = 'wifi' | 'volte' | 'cellular' @@ -92,7 +93,7 @@ function createVoWiFiOrCellularPresentation( ]) }) } - const signal = device?.modem?.signal_dbm + const signal = displaySignalDbm(device?.modem?.signal_dbm, device?.modem?.signal_rsrp) return Object.freeze({ kind: 'cellular', eyebrow: 'CELLULAR', @@ -104,7 +105,7 @@ function createVoWiFiOrCellularPresentation( metrics: Object.freeze([ { label: '蜂窝信号', - value: formatDashboardSignal(signal), + value: formatDashboardSignal(device?.modem?.signal_dbm, device?.modem?.signal_rsrp), hint: hasDashboardSignal(signal) ? signalQuality(signal) : '' }, metric('公网 IPv4', device?.public_ip, '未分配'), diff --git a/web/src/utils/signalPresentation.ts b/web/src/utils/signalPresentation.ts new file mode 100644 index 00000000..cbbaf06c --- /dev/null +++ b/web/src/utils/signalPresentation.ts @@ -0,0 +1,25 @@ +export const QMI_UNAVAILABLE_RSSI_DBM = -125 +export const QMI_INVALID_SIGNAL_DBM = -128 +export const LEGACY_INVALID_SIGNAL_DBM = -999 + +const SIGNAL_SENTINELS = new Set([ + 0, + QMI_UNAVAILABLE_RSSI_DBM, + QMI_INVALID_SIGNAL_DBM, + LEGACY_INVALID_SIGNAL_DBM +]) + +export function hasValidSignalDbm(value: unknown): value is number { + return typeof value === 'number' + && Number.isFinite(value) + && !SIGNAL_SENTINELS.has(value) +} + +export function displaySignalDbm( + rssi?: number | null, + rsrp?: number | null +): number | undefined { + if (hasValidSignalDbm(rssi)) return rssi + if (hasValidSignalDbm(rsrp)) return rsrp + return undefined +} diff --git a/web/tests/dashboardPresentation.test.ts b/web/tests/dashboardPresentation.test.ts index 9e038cbb..7c060460 100644 --- a/web/tests/dashboardPresentation.test.ts +++ b/web/tests/dashboardPresentation.test.ts @@ -109,9 +109,12 @@ test('formats cellular connection and validates signal sentinels', () => { assert.equal(presentation.showsCellularFacts, true) assert.equal(formatDashboardSignal(-105), '-105 dBm') assert.equal(formatDashboardSignal(0), '不可用') + assert.equal(formatDashboardSignal(-125), '不可用') + assert.equal(formatDashboardSignal(-125, -86), '-86 dBm') assert.equal(formatDashboardSignal(-128), '不可用') assert.equal(formatDashboardSignal(-999), '不可用') assert.equal(hasDashboardSignal(-78), true) + assert.equal(hasDashboardSignal(-125), false) assert.equal(hasDashboardSignal(Number.POSITIVE_INFINITY), false) }) diff --git a/web/tests/deviceOverviewLayoutSource.test.ts b/web/tests/deviceOverviewLayoutSource.test.ts index c84bd0eb..76be2bc8 100644 --- a/web/tests/deviceOverviewLayoutSource.test.ts +++ b/web/tests/deviceOverviewLayoutSource.test.ts @@ -70,7 +70,7 @@ test('identity panel keeps production facts and existing operations', () => { }) test('cellular signal panel hides invalid modem sentinel values', () => { - assert.match(overviewTab, /dbm > QMI_INVALID_SIGNAL_DBM/) + assert.match(overviewTab, /displaySignalDbm/) assert.match(overviewTab, /signalDbmDisplay/) assert.match(overviewTab, /signalMetricDisplay/) assert.doesNotMatch(overviewTab, /device\?\.modem\?\.signal_dbm \?\? '--'/) diff --git a/web/tests/signalPresentation.test.ts b/web/tests/signalPresentation.test.ts new file mode 100644 index 00000000..ab6fe0b1 --- /dev/null +++ b/web/tests/signalPresentation.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { displaySignalDbm, hasValidSignalDbm } from '../src/utils/signalPresentation.ts' + +test('treats QMI LTE placeholder RSSI as missing and falls back to RSRP', () => { + assert.equal(hasValidSignalDbm(-125), false) + assert.equal(hasValidSignalDbm(-128), false) + assert.equal(hasValidSignalDbm(0), false) + assert.equal(hasValidSignalDbm(-86), true) + assert.equal(displaySignalDbm(-125, -86), -86) + assert.equal(displaySignalDbm(-72, -86), -72) + assert.equal(displaySignalDbm(-125, 0), undefined) +})