diff --git a/cmd/hideck/main.go b/cmd/hideck/main.go index b069fe93..573f2e2e 100644 --- a/cmd/hideck/main.go +++ b/cmd/hideck/main.go @@ -26,6 +26,7 @@ import ( proxyserver "github.com/yibaiba/hideck/internal/proxy/server" "github.com/yibaiba/hideck/internal/proxy/traffic" "github.com/yibaiba/hideck/internal/upstreamproxy" + "github.com/yibaiba/hideck/internal/volte" "github.com/yibaiba/hideck/internal/web" "github.com/yibaiba/hideck/pkg/logger" @@ -207,8 +208,13 @@ func main() { if notifyMgr != nil { callResultNotifier = notifyMgr } + phoneGateway := &volte.Mux{ + IMS: voiceGW, + Native: pool.NativeVoLTEController(), + IsNative: pool.IsNativeVoLTE, + } phoneService, err := phone.NewService(phone.ServiceOptions{ - Gateway: voiceGW, Store: db.NewVoiceCallStore(db.DB), Transcoder: audioTranscoder, + Gateway: phoneGateway, Store: db.NewVoiceCallStore(db.DB), Transcoder: audioTranscoder, Notifier: callResultNotifier, RecordingDir: voiceRecordingDirectory, WebRTCUDPAddress: cfg.Server.WebRTCUDPAddress, WebRTCPublicHost: cfg.Server.WebRTCPublicHost, ICEServers: cfg.Server.ICEServers, diff --git a/internal/api/card_policy.go b/internal/api/card_policy.go index 03642829..7c1cae82 100644 --- a/internal/api/card_policy.go +++ b/internal/api/card_policy.go @@ -125,7 +125,7 @@ func (s *Server) handlePutCardPolicy(c *gin.Context) { if req.AirplaneEnabled != nil && !*req.AirplaneEnabled { unlocksRadio = true } - if normalizePhoneMode(req.PhoneMode) == "cellular" { + if device.PhoneModeCampsOnCell(normalizePhoneMode(req.PhoneMode)) { unlocksRadio = true } if unlocksRadio { diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go index 63a82cbf..e561c1c0 100644 --- a/internal/api/card_policy_test.go +++ b/internal/api/card_policy_test.go @@ -377,6 +377,17 @@ func TestApplyNetworkAndVoWiFiInterlock(t *testing.T) { if !cellPhone.VoWiFiEnabled || cellPhone.AirplaneEnabled || cellPhone.NetworkEnabled { t.Fatalf("开蜂窝软件电话应驻网且默认不开流量: %+v", cellPhone) } + + voltePhone := db.CardPolicy{PhoneMode: "volte", AirplaneEnabled: true, NetworkEnabled: false} + applyVoWiFiEnableToCardPolicy(&voltePhone) + if !voltePhone.VoWiFiEnabled || voltePhone.AirplaneEnabled || voltePhone.NetworkEnabled { + t.Fatalf("开 VoLTE 应驻网且不强制开上网流量: %+v", voltePhone) + } + + applyAirplaneToCardPolicy(&voltePhone, true) + if !voltePhone.AirplaneEnabled || voltePhone.NetworkEnabled || !voltePhone.VoWiFiEnabled { + t.Fatalf("VoLTE 开飞行应保留电话并关流量: %+v", voltePhone) + } } func TestPatchCardPolicyAirplaneMutualExclusion(t *testing.T) { diff --git a/internal/api/device_mgmt.go b/internal/api/device_mgmt.go index 3c770211..578938a7 100644 --- a/internal/api/device_mgmt.go +++ b/internal/api/device_mgmt.go @@ -224,10 +224,14 @@ func registrationStateLabel(regStatus int) string { // 误判为“未探测到数据控制端”、流量按空接口名也统计不到。 // cardPolicyVoWiFiEnabled 从卡策略读取用户意图,ICCID 为空或查不到时降级用 fallback。 func overviewPhoneMode(mode string) string { - if strings.TrimSpace(mode) == "cellular" { + switch strings.TrimSpace(mode) { + case "cellular": return "cellular" + case "volte": + return "volte" + default: + return "wifi" } - return "wifi" } func cardPolicyVoWiFiEnabled(iccid string, fallback bool) bool { @@ -396,6 +400,7 @@ type deviceMgmtOverviewLiteItem struct { VoWiFiEnabled bool `json:"vowifi_enabled"` VoWiFiActive bool `json:"vowifi_active"` VoWiFiRuntime *voWiFiRuntimeDTO `json:"vowifi_runtime,omitempty"` + NativeVoLTE any `json:"native_volte,omitempty"` RadioLiveOK *bool `json:"radio_live_ok,omitempty"` Modem modem.DeviceStatus `json:"modem"` Traffic map[string]string `json:"traffic,omitempty"` @@ -631,6 +636,7 @@ func (s *Server) buildOverviewLiteItemFromWorkerWithModem(w *device.Worker, cfg VoWiFiEnabled: cardPolicyVoWiFiEnabled(strings.TrimSpace(status.ICCID), cfg.VoWiFiEnabled), VoWiFiActive: s.pool.IsVoWiFiActive(w.ID), VoWiFiRuntime: s.getVoWiFiRuntimeDTO(w.ID), + NativeVoLTE: s.pool.NativeVoLTEStatus(w.ID), RadioLiveOK: radioLiveOK, Modem: modemStatus, NetworkConnected: w.NetworkConnected(), diff --git a/internal/api/phone.go b/internal/api/phone.go index 767a2af1..9db28077 100644 --- a/internal/api/phone.go +++ b/internal/api/phone.go @@ -63,7 +63,13 @@ func (s *Server) handlePhoneDevices(c *gin.Context) { logger.Warn("电话设备列表识别 Lebara UK 射频策略失败", "device", worker.ID, "err", err) } voice := map[string]interface{}{} - if s.voiceGW != nil { + if s.pool.IsNativeVoLTE(worker.ID) { + if ctl := s.pool.NativeVoLTEController(); ctl != nil { + for key, value := range ctl.DeviceStatus(worker.ID) { + voice[key] = value + } + } + } else if s.voiceGW != nil { voice = s.voiceGW.DeviceStatus(worker.ID) for key, value := range s.voiceGW.DeviceStatusCurrent(worker.ID) { voice[key] = value @@ -81,6 +87,7 @@ func (s *Server) handlePhoneDevices(c *gin.Context) { "network_enabled": worker.Config.NetworkEnabled, "vowifi_enabled": worker.Config.VoWiFiEnabled, "vowifi_active": s.pool.IsVoWiFiActive(worker.ID), + "native_volte": s.pool.NativeVoLTEStatus(worker.ID), "rf_lock": class.RFLock(), }) } diff --git a/internal/api/route_adapters.go b/internal/api/route_adapters.go index 91b05a05..88730878 100644 --- a/internal/api/route_adapters.go +++ b/internal/api/route_adapters.go @@ -6,12 +6,13 @@ import ( "github.com/gin-gonic/gin" "github.com/yibaiba/hideck/internal/db" + "github.com/yibaiba/hideck/internal/device" "github.com/yibaiba/hideck/pkg/logger" ) type enabledPatchRequest struct { Enabled *bool `json:"enabled"` - Mode *string `json:"mode"` // "wifi" | "cellular" + Mode *string `json:"mode"` // "wifi" | "cellular" | "volte" DataStrategy *string `json:"data_strategy"` // "always" | "on_demand" } @@ -89,7 +90,7 @@ func (s *Server) handleDeviceVoWiFiPatch(c *gin.Context) { // 落库:置 vowifi_enabled=true。若带 mode/data_strategy 则一并落库。 mode := normalizePhoneMode(req.Mode) strategy := normalizeDataStrategy(req.DataStrategy) - if mode == "cellular" { + if device.PhoneModeCampsOnCell(mode) { class, classifyErr := s.classifyLebaraUKForDevice(c.Request.Context(), deviceID) if rejectLebaraUKRFUnlock(c, class, classifyErr) { return @@ -127,6 +128,22 @@ func (s *Server) handleDeviceVoWiFiPatch(c *gin.Context) { } } s.pool.SetWorkerVoWiFiPolicy(deviceID, true) + if w := s.pool.GetWorker(deviceID); w != nil && device.IsNativeVoLTEMode(w.Config.PhoneMode) { + if err := s.pool.EnableNativeVoLTE(deviceID); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "status": "error", + "message": "切换 VoLTE 失败: " + err.Error(), + "device": deviceID, + }) + return + } + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "message": "VoLTE 已设置,会驻网并由模组原生 IMS 打电话。打开「网络」才会走上网流量", + "device": deviceID, + }) + return + } if w := s.pool.GetWorker(deviceID); w != nil && w.Config.PhoneMode == "cellular" && w.Config.DataStrategy != "always" { if err := s.pool.StopVoWiFiRuntimeForCellularIdle(deviceID); err != nil { c.JSON(http.StatusInternalServerError, gin.H{ @@ -200,7 +217,7 @@ func applyAirplaneToCardPolicy(p *db.CardPolicy, enabled bool) { return } p.NetworkEnabled = false - if p.PhoneMode != "cellular" { + if !device.PhoneModeCampsOnCell(p.PhoneMode) { p.VoWiFiEnabled = false } } @@ -212,7 +229,7 @@ func applyNetworkEnableToCardPolicy(p *db.CardPolicy) { } p.NetworkEnabled = true p.AirplaneEnabled = false - if p.PhoneMode != "cellular" { + if !device.PhoneModeCampsOnCell(p.PhoneMode) { p.VoWiFiEnabled = false } } @@ -230,6 +247,10 @@ func applyVoWiFiEnableToCardPolicy(p *db.CardPolicy) { } return } + if p.PhoneMode == "volte" { + p.AirplaneEnabled = false + return + } p.AirplaneEnabled = true p.NetworkEnabled = false } @@ -241,6 +262,8 @@ func normalizePhoneMode(v *string) string { switch strings.ToLower(strings.TrimSpace(*v)) { case "cellular": return "cellular" + case "volte": + return "volte" default: return "wifi" } diff --git a/internal/cardpolicy/policy.go b/internal/cardpolicy/policy.go index fed3502b..8fbdfa2c 100644 --- a/internal/cardpolicy/policy.go +++ b/internal/cardpolicy/policy.go @@ -8,7 +8,7 @@ type Policy struct { AirplaneEnabled bool IPVersion string APN string - PhoneMode string // wifi | cellular + PhoneMode string // wifi | cellular | volte DataStrategy string // always | on_demand } diff --git a/internal/config/config.go b/internal/config/config.go index 7fc5538a..b22ed3e2 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -233,7 +233,7 @@ type DeviceConfig struct { AirplaneEnabled bool `mapstructure:"-"` ConnectHoldRF bool `mapstructure:"-"` // USB 热插/控制口重建时暂扣射频,不落文件 SMSEnabled bool `mapstructure:"-"` // SMS 恒开,运行时强制 true - PhoneMode string `mapstructure:"-"` // wifi | cellular + PhoneMode string `mapstructure:"-"` // wifi | cellular | volte DataStrategy string `mapstructure:"-"` // always | on_demand // USB Audio (自动发现,无需手动配置) diff --git a/internal/db/card_policy.go b/internal/db/card_policy.go index eb5a6c34..e0125d3b 100644 --- a/internal/db/card_policy.go +++ b/internal/db/card_policy.go @@ -17,9 +17,9 @@ type CardPolicy struct { AirplaneEnabled bool `gorm:"column:airplane_enabled" json:"airplane_enabled"` IPVersion string `gorm:"column:ip_version" json:"ip_version"` APN string `gorm:"column:apn" json:"apn"` - PhoneMode string `gorm:"column:phone_mode;default:wifi" json:"phone_mode"` // wifi | cellular + PhoneMode string `gorm:"column:phone_mode;default:wifi" json:"phone_mode"` // wifi | cellular | volte DataStrategy string `gorm:"column:data_strategy;default:on_demand" json:"data_strategy"` // always | on_demand - Source string `gorm:"column:source" json:"source"` // auto | user + Source string `gorm:"column:source" json:"source"` // auto | user CreatedAt time.Time `gorm:"column:created_at" json:"created_at"` UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"` } @@ -69,7 +69,7 @@ func NormalizeCardPolicy(p *CardPolicy) { p.IPVersion = "v4" } switch strings.TrimSpace(p.PhoneMode) { - case "wifi", "cellular": + case "wifi", "cellular", "volte": p.PhoneMode = strings.TrimSpace(p.PhoneMode) default: p.PhoneMode = "wifi" diff --git a/internal/db/card_policy_test.go b/internal/db/card_policy_test.go index 7d7eb50b..e2f01c38 100644 --- a/internal/db/card_policy_test.go +++ b/internal/db/card_policy_test.go @@ -56,6 +56,24 @@ func TestNormalizeCardPolicyAirplaneIndependent(t *testing.T) { } } +func TestNormalizeCardPolicyAcceptsVoLTE(t *testing.T) { + p := CardPolicy{ICCID: "x", PhoneMode: "volte"} + NormalizeCardPolicy(&p) + if p.PhoneMode != "volte" { + t.Fatalf("volte 应保留,得 %q", p.PhoneMode) + } + p.PhoneMode = "VoLTE" + NormalizeCardPolicy(&p) + if p.PhoneMode != "wifi" { + t.Fatalf("大小写不匹配应回 wifi,得 %q", p.PhoneMode) + } + p.PhoneMode = "gsm" + NormalizeCardPolicy(&p) + if p.PhoneMode != "wifi" { + t.Fatalf("非法值应回 wifi,得 %q", p.PhoneMode) + } +} + func TestResolveCardPolicyAutoCreates(t *testing.T) { openTestDB(t) iccid := "8986009999999999999" diff --git a/internal/device/phone_mode.go b/internal/device/phone_mode.go new file mode 100644 index 00000000..f24263af --- /dev/null +++ b/internal/device/phone_mode.go @@ -0,0 +1,22 @@ +package device + +import "strings" + +const ( + PhoneModeWiFi = "wifi" + PhoneModeCellular = "cellular" + PhoneModeVoLTE = "volte" +) + +func IsNativeVoLTEMode(mode string) bool { + return strings.TrimSpace(mode) == PhoneModeVoLTE +} + +func PhoneModeCampsOnCell(mode string) bool { + switch strings.TrimSpace(mode) { + case PhoneModeCellular, PhoneModeVoLTE: + return true + default: + return false + } +} diff --git a/internal/device/policy_projection.go b/internal/device/policy_projection.go index b312842b..117133fe 100644 --- a/internal/device/policy_projection.go +++ b/internal/device/policy_projection.go @@ -24,8 +24,8 @@ func shouldSuppressCellularRadio(cfg config.DeviceConfig) bool { if cfg.AirplaneEnabled { return true } - // WiFi calling 关射频。蜂窝软件电话要保持驻网,即使还没开流量。 - return cfg.VoWiFiEnabled && cfg.PhoneMode != "cellular" + // WiFi calling 关射频。蜂窝软件电话和原生 VoLTE 都要驻网。 + return cfg.VoWiFiEnabled && !PhoneModeCampsOnCell(cfg.PhoneMode) } // applyPolicyToWorker 把卡策略投影进 worker.Config 的运行时有效字段。 @@ -44,10 +44,10 @@ func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error { w.Config.PhoneMode = p.PhoneMode w.Config.DataStrategy = p.DataStrategy if p.VoWiFiEnabled { - if p.PhoneMode == "cellular" { + if PhoneModeCampsOnCell(p.PhoneMode) { if p.AirplaneEnabled { w.Config.NetworkEnabled = false - } else if p.DataStrategy == "always" { + } else if p.PhoneMode == "cellular" && p.DataStrategy == "always" { w.Config.NetworkEnabled = true } } else { @@ -106,8 +106,8 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR case effective.AirplaneEnabled: // 飞行优先:蜂窝软件电话可以保持开启,只关射频和流量。 p.enterAirplaneModeFromPolicy(worker, reason) - case effective.VoWiFiEnabled && effective.PhoneMode == "cellular": - // 蜂窝:射频保持在线以驻网。网络开着才连数据;on_demand 拨号时再开数据。 + case effective.VoWiFiEnabled && PhoneModeCampsOnCell(effective.PhoneMode): + // 蜂窝软件电话 / 原生 VoLTE:射频保持在线以驻网。网络开着才连上网数据。 p.exitAirplaneModeIfNeeded(worker, reason) if err := p.applyNetworkPreference(worker); err != nil { logger.Warn("应用网络偏好失败", "device", worker.ID, "err", err) @@ -124,10 +124,16 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR logger.Warn("应用网络偏好失败", "device", worker.ID, "err", err) } } - if effective.VoWiFiEnabled && !cellularSoftwarePhoneHeld(worker, pol) { - p.scheduleDesiredVoWiFiRecover(worker.ID, reason, time.Now()) - } else { + if IsNativeVoLTEMode(effective.PhoneMode) && effective.VoWiFiEnabled && !effective.AirplaneEnabled { p.clearDesiredVoWiFiRecoverState(worker.ID) + p.scheduleNativeVoLTE(worker.ID, reason) + } else { + p.stopNativeVoLTE(worker.ID, reason) + if effective.VoWiFiEnabled && !cellularSoftwarePhoneHeld(worker, pol) { + p.scheduleDesiredVoWiFiRecover(worker.ID, reason, time.Now()) + } else { + p.clearDesiredVoWiFiRecoverState(worker.ID) + } } return policyApplyResult{Applied: true, ICCID: iccid, Reason: reason} } diff --git a/internal/device/policy_projection_test.go b/internal/device/policy_projection_test.go index e4f2dac1..8cdfc769 100644 --- a/internal/device/policy_projection_test.go +++ b/internal/device/policy_projection_test.go @@ -26,6 +26,19 @@ func TestApplyPolicyCellularAirplaneKeepsSoftwarePhone(t *testing.T) { } } +func TestApplyPolicyVoLTECampsWithoutForcingData(t *testing.T) { + w := &Worker{ID: "wwan1"} + applyPolicyToWorker(w, cardpolicy.Policy{ + ICCID: "x", VoWiFiEnabled: true, PhoneMode: "volte", + }) + if w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() { + t.Fatalf("VoLTE 应驻网且不强制开流量: %+v suppressed=%v", w.Config, w.cellularRadioIsSuppressed()) + } + if w.Config.PhoneMode != "volte" { + t.Fatalf("PhoneMode=%q", w.Config.PhoneMode) + } +} + func TestApplyPolicyCellularIdleKeepsCamped(t *testing.T) { w := &Worker{ID: "wwan0"} applyPolicyToWorker(w, cardpolicy.Policy{ diff --git a/internal/device/pool.go b/internal/device/pool.go index 5ecd05bc..3c8430fd 100644 --- a/internal/device/pool.go +++ b/internal/device/pool.go @@ -24,6 +24,7 @@ import ( "github.com/yibaiba/hideck/internal/pcsc" "github.com/yibaiba/hideck/internal/proxy/server" qmicore "github.com/yibaiba/hideck/internal/qmi" + "github.com/yibaiba/hideck/internal/volte" "github.com/yibaiba/hideck/internal/vowifihost" "github.com/yibaiba/hideck/pkg/logger" "github.com/yibaiba/hideck/pkg/smscodec" @@ -196,6 +197,7 @@ type Pool struct { rescanAndReconnectForTest func() error voiceGateway *voicehost.Gateway + volteCtl *volte.Controller // VoWiFi host 侧整合(多实例) vowifiHost *vowifihost.Manager @@ -265,6 +267,7 @@ func NewPoolWithDynamicInterfaceMapper(cfg *config.Config, mapper DynamicInterfa p.voWiFiHost().ConfigureAdapter(p) p.voWiFiHost().ConfigureRuntimeRecycleHandler(p.handleVoWiFiRuntimeRecycle) p.voWiFiHost().ConfigureRuntimeDependencies(p.GetVoiceGateway(), vowifiDeliveryStore{}, poolVoWiFiRuntimeDispatcher{pool: p}) + p.volteCtl = volte.NewController(p) return p } @@ -1956,7 +1959,7 @@ func (p *Pool) SetWorkerNetworkPolicy(deviceID string, networkEnabled bool, ipVe w.Config.AirplaneEnabled = false // 蜂窝软件电话本身就要走 SIM 数据,允许和网络同时开。 // WiFi calling 仍与数据互斥,避免射频/默认路由被两边抢。 - if w.Config.PhoneMode != "cellular" { + if !PhoneModeCampsOnCell(w.Config.PhoneMode) { w.Config.VoWiFiEnabled = false } } @@ -1989,6 +1992,11 @@ func (p *Pool) SetWorkerVoWiFiPolicy(deviceID string, vowifiEnabled bool) *Worke w.setCellularRadioSuppressed(shouldSuppressCellularRadio(w.Config)) return w } + if IsNativeVoLTEMode(w.Config.PhoneMode) { + w.Config.AirplaneEnabled = false + w.setCellularRadioSuppressed(shouldSuppressCellularRadio(w.Config)) + return w + } w.Config.AirplaneEnabled = true w.Config.NetworkEnabled = false } @@ -2008,7 +2016,7 @@ func (p *Pool) SetWorkerAirplanePolicy(deviceID string, airplaneEnabled bool) *W w.Config.AirplaneEnabled = airplaneEnabled if airplaneEnabled { w.Config.NetworkEnabled = false - if w.Config.PhoneMode != "cellular" { + if !PhoneModeCampsOnCell(w.Config.PhoneMode) { w.Config.VoWiFiEnabled = false } } else if w.Config.PhoneMode == "cellular" && w.Config.DataStrategy == "always" { diff --git a/internal/device/pool_vowifi_reconcile.go b/internal/device/pool_vowifi_reconcile.go index 4e78ad06..7029baa3 100644 --- a/internal/device/pool_vowifi_reconcile.go +++ b/internal/device/pool_vowifi_reconcile.go @@ -217,6 +217,10 @@ func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason stri "err", err) return false } + if IsNativeVoLTEMode(pol.PhoneMode) || IsNativeVoLTEMode(w.Config.PhoneMode) { + p.clearDesiredVoWiFiRecoverState(deviceID) + return false + } if !pol.VoWiFiEnabled { p.clearDesiredVoWiFiRecoverState(deviceID) // logger.Info("VoWiFi 目标态恢复跳过:当前卡策略未开启 VoWiFi", diff --git a/internal/device/pool_vowifi_runtime.go b/internal/device/pool_vowifi_runtime.go index b518581d..c8599d79 100644 --- a/internal/device/pool_vowifi_runtime.go +++ b/internal/device/pool_vowifi_runtime.go @@ -159,6 +159,10 @@ func (p *Pool) EnableVoWiFi(deviceID string) 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) + } + p.stopNativeVoLTE(deviceID, "enable_vowifi") if w := p.GetWorker(deviceID); w != nil && w.Config.PhoneMode == "cellular" { if w.Config.AirplaneEnabled { logger.Info("蜂窝飞行:待机不建 SWu 隧道", "device", deviceID) diff --git a/internal/device/volte.go b/internal/device/volte.go new file mode 100644 index 00000000..6a68f1e4 --- /dev/null +++ b/internal/device/volte.go @@ -0,0 +1,190 @@ +package device + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/iniwex5/quectel-qmi-go/pkg/qmi" + "github.com/yibaiba/hideck/internal/modem" + "github.com/yibaiba/hideck/internal/volte" + "github.com/yibaiba/hideck/pkg/logger" +) + +func (p *Pool) NativeVoLTEController() *volte.Controller { + if p == nil { + return nil + } + return p.volteCtl +} + +func (p *Pool) IsNativeVoLTE(deviceID string) bool { + w := p.GetWorker(strings.TrimSpace(deviceID)) + if w == nil { + return false + } + return IsNativeVoLTEMode(w.Config.PhoneMode) && w.Config.VoWiFiEnabled +} + +func (p *Pool) NativeVoLTEStatus(deviceID string) volte.Status { + if p == nil || p.volteCtl == nil { + return volte.Status{DeviceID: deviceID, Phase: volte.PhaseIdle} + } + return p.volteCtl.Status(deviceID) +} + +func (p *Pool) EnableNativeVoLTE(deviceID string) error { + if p == nil || p.volteCtl == nil { + return fmt.Errorf("VoLTE 控制器未初始化") + } + deviceID = strings.TrimSpace(deviceID) + w := p.GetWorker(deviceID) + if w == nil { + return fmt.Errorf("设备 %s 不存在", deviceID) + } + if p.IsESIMSwitching(deviceID) { + return fmt.Errorf("设备 %s 正在切卡,暂不允许启动 VoLTE", deviceID) + } + class, err := ClassifyWorkerLebaraUK(w) + if err != nil { + return err + } + if class.BlocksVoWiFi() || class.IsLebara { + return ErrLebaraUKRFLocked + } + if err := p.waitQMICoreReady(deviceID, 30*time.Second); err != nil { + logger.Warn("VoLTE 等待 QMI 就绪失败,继续尝试 AT", "device", deviceID, "err", err) + } + return p.volteCtl.Enable(p.Context(), deviceID) +} + +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) + } + }() +} + +func (p *Pool) stopNativeVoLTE(deviceID, reason string) { + if p == nil || p.volteCtl == nil { + return + } + p.volteCtl.Disable(deviceID) + logger.Debug("已停止原生 VoLTE 会话", "device", deviceID, "reason", reason) +} + +func (p *Pool) ExecuteAT(deviceID, cmd string, timeout time.Duration) (string, error) { + w := p.GetWorker(deviceID) + if w == nil { + return "", fmt.Errorf("设备 %s 不存在", deviceID) + } + port := strings.TrimSpace(w.ResolvedATPort()) + if port == "" { + return "", fmt.Errorf("设备 %s 没有 AT 口", deviceID) + } + session, err := modem.NewSerialAT(port, 115200, 8, 1, "N") + if err != nil { + return "", fmt.Errorf("打开 AT 口 %s: %w", port, err) + } + defer session.Close() + return session.Execute(cmd, timeout) +} + +func (p *Pool) StopSoftwareIMS(deviceID string) error { + if p == nil { + return nil + } + if !p.IsVoWiFiActive(deviceID) && p.GetVoWiFiAppForDevice(deviceID) == nil { + return nil + } + return p.voWiFiHost().Disable(p.Context(), deviceID, "native_volte", true) +} + +func (p *Pool) SetNativeIMS(ctx context.Context, deviceID string, enabled bool) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI", deviceID) + } + return w.QMICore.SetIMSServiceEnabled(ctx, enabled) +} + +func (p *Pool) EnsureIMSClients(ctx context.Context, deviceID string) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI", deviceID) + } + return w.QMICore.EnsureIMSClients(ctx) +} + +func (p *Pool) IMSAStatus(ctx context.Context, deviceID string) (volte.Registration, error) { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return volte.Registration{}, fmt.Errorf("设备 %s 没有 QMI", deviceID) + } + reg, err := w.QMICore.IMSAGetIMSRegistrationStatus(ctx) + if err != nil { + return volte.Registration{}, err + } + out := volte.Registration{Registered: reg != nil && reg.HasStatus && reg.Status == qmi.IMSARegistrationStateRegistered} + svc, svcErr := w.QMICore.IMSAGetIMSServicesStatus(ctx) + if svcErr == nil && svc != nil && svc.HasVoiceServiceStatus { + out.VoiceAvailable = svc.VoiceServiceStatus == qmi.IMSAServiceAvailabilityAvailable + } + return out, nil +} + +func (p *Pool) AudioDevice(deviceID string) string { + w := p.GetWorker(deviceID) + if w == nil { + return "" + } + return strings.TrimSpace(w.Config.AudioDevice) +} + +func (p *Pool) VOICEDial(ctx context.Context, deviceID, number string) (uint8, error) { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return 0, fmt.Errorf("设备 %s 没有 QMI VOICE", deviceID) + } + return w.QMICore.VOICEDialCall(ctx, number) +} + +func (p *Pool) VOICEAnswer(ctx context.Context, deviceID string, callID uint8) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI VOICE", deviceID) + } + _, err := w.QMICore.VOICEAnswerCall(ctx, callID) + return err +} + +func (p *Pool) VOICEHangup(ctx context.Context, deviceID string, callID uint8) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI VOICE", deviceID) + } + _, err := w.QMICore.VOICEEndCall(ctx, callID) + return err +} + +func (p *Pool) VOICEBurstDTMF(ctx context.Context, deviceID string, callID uint8, digits string) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI VOICE", deviceID) + } + _, err := w.QMICore.VOICEBurstDTMF(ctx, callID, digits) + return err +} + +func (p *Pool) OnVoiceStatus(deviceID string, handler func(*qmi.VoiceAllCallInfo)) error { + w := p.GetWorker(deviceID) + if w == nil || w.QMICore == nil { + return fmt.Errorf("设备 %s 没有 QMI VOICE", deviceID) + } + return w.QMICore.OnVoiceCallStatus(handler) +} diff --git a/internal/device/vowifi_teardown.go b/internal/device/vowifi_teardown.go index 80597406..e47a05a1 100644 --- a/internal/device/vowifi_teardown.go +++ b/internal/device/vowifi_teardown.go @@ -139,6 +139,7 @@ func (p *Pool) DisableVoWiFi(deviceID ...string) error { if p.IsESIMSwitching(target) { return fmt.Errorf("设备 %s 正在切卡,暂不允许停用 VoWiFi", target) } + p.stopNativeVoLTE(target, "disable_vowifi") if err := p.voWiFiHost().Disable(p.ctx, target, "disable", false); err != nil { return err } diff --git a/internal/qmi/manager.go b/internal/qmi/manager.go index f79bb4a6..c65e2c24 100644 --- a/internal/qmi/manager.go +++ b/internal/qmi/manager.go @@ -2091,6 +2091,34 @@ func (m *Manager) SetIMSServiceEnabled(ctx context.Context, enabled bool) error return m.qmiMgr.SetIMSServiceEnabled(ctx, enabled) } +func (m *Manager) EnsureIMSClients(ctx context.Context) error { + if m == nil || m.qmiMgr == nil { + return qmimanager.ErrServiceNotReady("IMS") + } + return m.qmiMgr.EnsureIMSClients(ctx) +} + +func (m *Manager) IMSAGetIMSRegistrationStatus(ctx context.Context) (*qmi.IMSARegistrationStatus, error) { + if m == nil || m.qmiMgr == nil { + return nil, qmimanager.ErrServiceNotReady("IMSA") + } + return m.qmiMgr.IMSAGetIMSRegistrationStatus(ctx) +} + +func (m *Manager) IMSAGetIMSServicesStatus(ctx context.Context) (*qmi.IMSAServicesStatus, error) { + if m == nil || m.qmiMgr == nil { + return nil, qmimanager.ErrServiceNotReady("IMSA") + } + return m.qmiMgr.IMSAGetIMSServicesStatus(ctx) +} + +func (m *Manager) VOICEBurstDTMF(ctx context.Context, callID uint8, digits string) (uint8, error) { + if m == nil || m.qmiMgr == nil { + return 0, qmimanager.ErrServiceNotReady("VOICE") + } + return m.qmiMgr.VOICEBurstDTMF(ctx, callID, digits) +} + func (m *Manager) VOICEAnswerCall(ctx context.Context, callID uint8) (uint8, error) { if m == nil || m.qmiMgr == nil { return 0, qmimanager.ErrServiceNotReady("VOICE") diff --git a/internal/volte/at.go b/internal/volte/at.go new file mode 100644 index 00000000..09c39bd1 --- /dev/null +++ b/internal/volte/at.go @@ -0,0 +1,135 @@ +package volte + +import ( + "fmt" + "strconv" + "strings" +) + +type IMSConfig struct { + IMSEnabled bool + VoLTEEnabled bool + Raw string +} + +type USBConfig struct { + VID string + PID string + Fields []string + UACEnabled bool + EnableCommand string + Raw string +} + +func ParseIMSConfig(resp string) (IMSConfig, error) { + line, ok := findQCFGLine(resp, "ims") + if !ok { + return IMSConfig{}, fmt.Errorf("volte: missing +QCFG: \"ims\" in %q", compactAT(resp)) + } + parts := splitQCFGArgs(line) + if len(parts) < 2 { + return IMSConfig{}, fmt.Errorf("volte: malformed IMS config %q", line) + } + imsOn, err := parse01(parts[0]) + if err != nil { + return IMSConfig{}, fmt.Errorf("volte: ims enable: %w", err) + } + volteOn := imsOn + if len(parts) > 1 { + volteOn, err = parse01(parts[1]) + if err != nil { + return IMSConfig{}, fmt.Errorf("volte: volte enable: %w", err) + } + } + return IMSConfig{IMSEnabled: imsOn, VoLTEEnabled: volteOn, Raw: line}, nil +} + +func IMSEnableCommand() string { + return `AT+QCFG="ims",1,1` +} + +func IMSQueryCommand() string { + return `AT+QCFG="ims"?` +} + +func USBConfigQueryCommand() string { + return `AT+QCFG="usbcfg"?` +} + +func ParseUSBConfig(resp string) (USBConfig, error) { + line, ok := findQCFGLine(resp, "usbcfg") + if !ok { + return USBConfig{}, fmt.Errorf("volte: missing +QCFG: \"usbcfg\" in %q", compactAT(resp)) + } + parts := splitQCFGArgs(line) + if len(parts) < 3 { + return USBConfig{}, fmt.Errorf("volte: malformed usbcfg %q", line) + } + cfg := USBConfig{ + VID: parts[0], + PID: parts[1], + Fields: parts, + Raw: line, + } + last := strings.TrimSpace(parts[len(parts)-1]) + cfg.UACEnabled = last == "1" + if !cfg.UACEnabled { + enabled := append([]string(nil), parts...) + enabled[len(enabled)-1] = "1" + cfg.EnableCommand = `AT+QCFG=` + strings.Join(quoteUSBCFG(enabled), ",") + } + return cfg, nil +} + +func findQCFGLine(resp, key string) (string, bool) { + key = strings.ToLower(strings.TrimSpace(key)) + for _, raw := range strings.Split(resp, "\n") { + line := strings.TrimSpace(raw) + lower := strings.ToLower(line) + prefix := `+qcfg: "` + key + `"` + if !strings.HasPrefix(lower, prefix) { + continue + } + _, rest, ok := strings.Cut(line, ",") + if !ok { + return "", false + } + return strings.TrimSpace(rest), true + } + return "", false +} + +func splitQCFGArgs(args string) []string { + parts := strings.Split(args, ",") + out := make([]string, 0, len(parts)) + for _, part := range parts { + out = append(out, strings.TrimSpace(part)) + } + return out +} + +func parse01(v string) (bool, error) { + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil { + return false, err + } + switch n { + case 0: + return false, nil + case 1: + return true, nil + default: + return false, fmt.Errorf("expected 0 or 1, got %s", v) + } +} + +func quoteUSBCFG(parts []string) []string { + out := make([]string, len(parts)+1) + out[0] = `"usbcfg"` + copy(out[1:], parts) + return out +} + +func compactAT(resp string) string { + return strings.Join(strings.Fields(resp), " ") +} diff --git a/internal/volte/at_test.go b/internal/volte/at_test.go new file mode 100644 index 00000000..fd7c7d69 --- /dev/null +++ b/internal/volte/at_test.go @@ -0,0 +1,37 @@ +package volte + +import "testing" + +func TestParseIMSConfig(t *testing.T) { + got, err := ParseIMSConfig("AT+QCFG=\"ims\"?\r\n+QCFG: \"ims\",0,0\r\n\r\nOK\r\n") + if err != nil { + t.Fatal(err) + } + if got.IMSEnabled || got.VoLTEEnabled { + t.Fatalf("want disabled, got %+v", got) + } + got, err = ParseIMSConfig("+QCFG: \"IMS\",1,1\nOK") + if err != nil || !got.IMSEnabled || !got.VoLTEEnabled { + t.Fatalf("want enabled, got %+v err=%v", got, err) + } + if _, err := ParseIMSConfig("ERROR"); err == nil { + t.Fatal("missing line should fail") + } +} + +func TestParseUSBConfig(t *testing.T) { + got, err := ParseUSBConfig(`+QCFG: "usbcfg",0x2C7C,0x125,1,1,1,1,1,0,0`) + if err != nil { + t.Fatal(err) + } + if got.UACEnabled { + t.Fatal("last bit 0 should be UAC off") + } + if got.EnableCommand != `AT+QCFG="usbcfg",0x2C7C,0x125,1,1,1,1,1,0,1` { + t.Fatalf("enable command = %q", got.EnableCommand) + } + on, err := ParseUSBConfig(`+QCFG: "usbcfg",0x2C7C,0x0125,1,1,1,1,1,0,1`) + if err != nil || !on.UACEnabled || on.EnableCommand != "" { + t.Fatalf("UAC on: %+v err=%v", on, err) + } +} diff --git a/internal/volte/controller.go b/internal/volte/controller.go new file mode 100644 index 00000000..661a39bf --- /dev/null +++ b/internal/volte/controller.go @@ -0,0 +1,206 @@ +package volte + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" + "github.com/yibaiba/hideck/pkg/logger" +) + +type Controller struct { + host Host + mu sync.Mutex + sess map[string]*session + globalIncoming []func(voicehost.IncomingCall) + globalEvents []func(voicehost.CallEvent) +} + +type session struct { + status Status + voice *voiceSession +} + +func NewController(host Host) *Controller { + return &Controller{host: host, sess: make(map[string]*session)} +} + +func (c *Controller) Enable(ctx context.Context, deviceID string) error { + deviceID = strings.TrimSpace(deviceID) + if c == nil || c.host == nil || deviceID == "" { + return errors.New("volte: controller is not configured") + } + if ctx == nil { + ctx = context.Background() + } + c.mu.Lock() + s := c.sess[deviceID] + if s == nil { + s = &session{status: Status{DeviceID: deviceID, Phase: PhaseEnabling}} + c.sess[deviceID] = s + } + s.status.Phase = PhaseEnabling + s.status.LastError = "" + c.mu.Unlock() + + if err := c.host.StopSoftwareIMS(deviceID); err != nil { + return c.fail(deviceID, fmt.Errorf("stop software IMS: %w", err)) + } + if err := c.applyIMS(ctx, deviceID); err != nil { + return c.fail(deviceID, err) + } + if err := c.applyUAC(deviceID); err != nil { + logger.Warn("VoLTE UAC 查询失败", "device", deviceID, "err", err) + c.setError(deviceID, err) + } + c.attachVoice(deviceID) + c.refreshRegistration(ctx, deviceID) + return nil +} + +func (c *Controller) Disable(deviceID string) { + deviceID = strings.TrimSpace(deviceID) + if c == nil || deviceID == "" { + return + } + c.mu.Lock() + delete(c.sess, deviceID) + c.mu.Unlock() +} + +func (c *Controller) Status(deviceID string) Status { + if c == nil { + return Status{DeviceID: deviceID, Phase: PhaseIdle} + } + c.mu.Lock() + defer c.mu.Unlock() + s := c.sess[strings.TrimSpace(deviceID)] + if s == nil { + return Status{DeviceID: deviceID, Phase: PhaseIdle} + } + return s.status +} + +func (c *Controller) Active(deviceID string) bool { + st := c.Status(deviceID) + return st.Phase == PhaseRegistered || st.Phase == PhaseUnverified || st.Phase == PhaseEnabling +} + +func (c *Controller) applyIMS(ctx context.Context, deviceID string) error { + resp, err := c.host.ExecuteAT(deviceID, IMSQueryCommand(), 8*time.Second) + if err != nil { + return fmt.Errorf("query IMS: %w", err) + } + cfg, err := ParseIMSConfig(resp) + if err != nil { + return err + } + if !cfg.IMSEnabled || !cfg.VoLTEEnabled { + if _, err := c.host.ExecuteAT(deviceID, IMSEnableCommand(), 8*time.Second); err != nil { + return fmt.Errorf("enable IMS: %w", err) + } + resp, err = c.host.ExecuteAT(deviceID, IMSQueryCommand(), 8*time.Second) + if err != nil { + return fmt.Errorf("re-query IMS: %w", err) + } + cfg, err = ParseIMSConfig(resp) + if err != nil { + return err + } + } + c.patch(deviceID, func(st *Status) { + st.IMSEnabled = cfg.IMSEnabled + st.VoLTEEnabled = cfg.VoLTEEnabled + if !cfg.IMSEnabled || !cfg.VoLTEEnabled { + st.RebootRequired = true + } + }) + if err := c.host.SetNativeIMS(ctx, deviceID, true); err != nil { + logger.Warn("QMI 打开原生 IMS 失败,继续用 AT 结果", "device", deviceID, "err", err) + } + if err := c.host.EnsureIMSClients(ctx, deviceID); err != nil { + logger.Warn("QMI IMS/IMSA 客户端不可用", "device", deviceID, "err", err) + c.patch(deviceID, func(st *Status) { st.QMIIMSUnavailable = true }) + } + return nil +} + +func (c *Controller) applyUAC(deviceID string) error { + resp, err := c.host.ExecuteAT(deviceID, USBConfigQueryCommand(), 8*time.Second) + if err != nil { + return err + } + cfg, err := ParseUSBConfig(resp) + if err != nil { + return err + } + reboot := false + if !cfg.UACEnabled && cfg.EnableCommand != "" { + if _, err := c.host.ExecuteAT(deviceID, cfg.EnableCommand, 8*time.Second); err != nil { + return fmt.Errorf("enable UAC: %w", err) + } + reboot = true + } + audio := strings.TrimSpace(c.host.AudioDevice(deviceID)) + c.patch(deviceID, func(st *Status) { + st.UACEnabled = cfg.UACEnabled || reboot + st.AudioDevice = audio + if reboot { + st.RebootRequired = true + } + }) + return nil +} + +func (c *Controller) refreshRegistration(ctx context.Context, deviceID string) { + reg, err := c.host.IMSAStatus(ctx, deviceID) + c.patch(deviceID, func(st *Status) { + if err != nil { + if st.IMSEnabled && st.VoLTEEnabled { + st.Phase = PhaseUnverified + } + if st.LastError == "" { + st.LastError = err.Error() + } + return + } + st.IMSRegistered = reg.Registered + st.VoiceAvailable = reg.VoiceAvailable + if reg.Registered { + st.Phase = PhaseRegistered + st.LastError = "" + } else if st.IMSEnabled && st.VoLTEEnabled { + st.Phase = PhaseUnverified + } + }) +} + +func (c *Controller) fail(deviceID string, err error) error { + c.patch(deviceID, func(st *Status) { + st.Phase = PhaseFailed + st.LastError = err.Error() + }) + return err +} + +func (c *Controller) setError(deviceID string, err error) { + if err == nil { + return + } + c.patch(deviceID, func(st *Status) { st.LastError = err.Error() }) +} + +func (c *Controller) patch(deviceID string, fn func(*Status)) { + c.mu.Lock() + defer c.mu.Unlock() + s := c.sess[deviceID] + if s == nil { + s = &session{status: Status{DeviceID: deviceID}} + c.sess[deviceID] = s + } + fn(&s.status) +} diff --git a/internal/volte/controller_test.go b/internal/volte/controller_test.go new file mode 100644 index 00000000..ca7bf0fd --- /dev/null +++ b/internal/volte/controller_test.go @@ -0,0 +1,108 @@ +package volte + +import ( + "context" + "testing" + "time" + + "github.com/iniwex5/quectel-qmi-go/pkg/qmi" +) + +type fakeHost struct { + imsQuery string + usbQuery string + commands []string + stopIMS int + setNative int + ensureErr error + reg Registration + regErr error + audio string +} + +func (f *fakeHost) ExecuteAT(_ string, cmd string, _ time.Duration) (string, error) { + f.commands = append(f.commands, cmd) + switch cmd { + case IMSQueryCommand(): + return f.imsQuery, nil + case USBConfigQueryCommand(): + return f.usbQuery, nil + default: + if cmd == IMSEnableCommand() { + f.imsQuery = `+QCFG: "ims",1,1` + } + if len(cmd) > 10 && cmd[:10] == `AT+QCFG="u` { + f.usbQuery = `+QCFG: "usbcfg",0x2C7C,0x125,1,1,1,1,1,0,1` + } + return "OK", nil + } +} +func (f *fakeHost) StopSoftwareIMS(string) error { f.stopIMS++; return nil } +func (f *fakeHost) SetNativeIMS(context.Context, string, bool) error { + f.setNative++ + return nil +} +func (f *fakeHost) EnsureIMSClients(context.Context, string) error { return f.ensureErr } +func (f *fakeHost) IMSAStatus(context.Context, string) (Registration, error) { + return f.reg, f.regErr +} +func (f *fakeHost) AudioDevice(string) string { return f.audio } +func (f *fakeHost) VOICEDial(context.Context, string, string) (uint8, error) { + return 1, nil +} +func (f *fakeHost) VOICEAnswer(context.Context, string, uint8) error { return nil } +func (f *fakeHost) VOICEHangup(context.Context, string, uint8) error { return nil } +func (f *fakeHost) VOICEBurstDTMF(context.Context, string, uint8, string) error { + return nil +} +func (f *fakeHost) OnVoiceStatus(string, func(*qmi.VoiceAllCallInfo)) error { return nil } + +func TestControllerEnablesIMSAndUACWithoutRebootClaim(t *testing.T) { + host := &fakeHost{ + imsQuery: `+QCFG: "ims",0,0`, + usbQuery: `+QCFG: "usbcfg",0x2C7C,0x125,1,1,1,1,1,0,0`, + reg: Registration{Registered: true, VoiceAvailable: true}, + } + ctl := NewController(host) + if err := ctl.Enable(context.Background(), "wwan1"); err != nil { + t.Fatal(err) + } + if host.stopIMS != 1 || host.setNative != 1 { + t.Fatalf("stop=%d setNative=%d", host.stopIMS, host.setNative) + } + st := ctl.Status("wwan1") + if !st.IMSEnabled || !st.VoLTEEnabled || !st.IMSRegistered || st.Phase != PhaseRegistered { + t.Fatalf("status %+v", st) + } + if !st.RebootRequired { + t.Fatal("UAC enable should mark reboot_required") + } + var sawEnableIMS, sawEnableUAC bool + for _, cmd := range host.commands { + if cmd == IMSEnableCommand() { + sawEnableIMS = true + } + if cmd == `AT+QCFG="usbcfg",0x2C7C,0x125,1,1,1,1,1,0,1` { + sawEnableUAC = true + } + } + if !sawEnableIMS || !sawEnableUAC { + t.Fatalf("commands %v", host.commands) + } +} + +func TestControllerUnverifiedWhenIMSAMissing(t *testing.T) { + host := &fakeHost{ + imsQuery: `+QCFG: "ims",1,1`, + usbQuery: `+QCFG: "usbcfg",0x2C7C,0x125,1,1,1,1,1,0,1`, + regErr: context.DeadlineExceeded, + } + ctl := NewController(host) + if err := ctl.Enable(context.Background(), "wwan1"); err != nil { + t.Fatal(err) + } + st := ctl.Status("wwan1") + if st.Phase != PhaseUnverified || !st.IMSEnabled { + t.Fatalf("want unverified, got %+v", st) + } +} diff --git a/internal/volte/host.go b/internal/volte/host.go new file mode 100644 index 00000000..3a1b0f52 --- /dev/null +++ b/internal/volte/host.go @@ -0,0 +1,28 @@ +package volte + +import ( + "context" + "time" + + "github.com/iniwex5/quectel-qmi-go/pkg/qmi" +) + +type Registration struct { + Registered bool + VoiceAvailable bool + Raw string +} + +type Host interface { + ExecuteAT(deviceID, cmd string, timeout time.Duration) (string, error) + StopSoftwareIMS(deviceID string) error + SetNativeIMS(ctx context.Context, deviceID string, enabled bool) error + EnsureIMSClients(ctx context.Context, deviceID string) error + IMSAStatus(ctx context.Context, deviceID string) (Registration, error) + AudioDevice(deviceID string) string + VOICEDial(ctx context.Context, deviceID, number string) (uint8, error) + VOICEAnswer(ctx context.Context, deviceID string, callID uint8) error + VOICEHangup(ctx context.Context, deviceID string, callID uint8) error + VOICEBurstDTMF(ctx context.Context, deviceID string, callID uint8, digits string) error // digits is a single DTMF key + OnVoiceStatus(deviceID string, handler func(*qmi.VoiceAllCallInfo)) error +} diff --git a/internal/volte/mux.go b/internal/volte/mux.go new file mode 100644 index 00000000..300d7702 --- /dev/null +++ b/internal/volte/mux.go @@ -0,0 +1,111 @@ +package volte + +import ( + "context" + "strings" + + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" +) + +type VoiceBackend interface { + SubscribeIncomingCalls(func(voicehost.IncomingCall)) func() + SubscribeCallEvents(func(voicehost.CallEvent)) func() + BeginCall(context.Context, voicehost.BeginCallRequest) (voicehost.CallSnapshot, error) + ActiveCall(deviceID string) *voicehost.CallSnapshot + AnswerIncomingCall(context.Context, voicehost.AnswerRequest) (voicehost.AnswerResult, error) + RejectIncomingCall(voicehost.RejectRequest) error + HangupCall(context.Context, string, string) error + SendCallDTMF(string, string, string) error + StartCallCapture(string, string, string) error + DeviceStatus(deviceID string) map[string]interface{} +} + +type Mux struct { + IMS VoiceBackend + Native VoiceBackend + IsNative func(deviceID string) bool +} + +func (m *Mux) native(deviceID string) bool { + if m == nil || m.IsNative == nil { + return false + } + return m.IsNative(strings.TrimSpace(deviceID)) +} + +func (m *Mux) pick(deviceID string) VoiceBackend { + if m.native(deviceID) && m.Native != nil { + return m.Native + } + return m.IMS +} + +func (m *Mux) SubscribeIncomingCalls(handler func(voicehost.IncomingCall)) func() { + var unsubs []func() + if m != nil && m.IMS != nil { + unsubs = append(unsubs, m.IMS.SubscribeIncomingCalls(handler)) + } + if m != nil && m.Native != nil { + unsubs = append(unsubs, m.Native.SubscribeIncomingCalls(handler)) + } + return func() { + for _, u := range unsubs { + if u != nil { + u() + } + } + } +} + +func (m *Mux) SubscribeCallEvents(handler func(voicehost.CallEvent)) func() { + var unsubs []func() + if m != nil && m.IMS != nil { + unsubs = append(unsubs, m.IMS.SubscribeCallEvents(handler)) + } + if m != nil && m.Native != nil { + unsubs = append(unsubs, m.Native.SubscribeCallEvents(handler)) + } + return func() { + for _, u := range unsubs { + if u != nil { + u() + } + } + } +} + +func (m *Mux) BeginCall(ctx context.Context, request voicehost.BeginCallRequest) (voicehost.CallSnapshot, error) { + return m.pick(request.DeviceID).BeginCall(ctx, request) +} + +func (m *Mux) ActiveCall(deviceID string) *voicehost.CallSnapshot { + return m.pick(deviceID).ActiveCall(deviceID) +} + +func (m *Mux) AnswerIncomingCall(ctx context.Context, request voicehost.AnswerRequest) (voicehost.AnswerResult, error) { + return m.pick(request.DeviceID).AnswerIncomingCall(ctx, request) +} + +func (m *Mux) RejectIncomingCall(request voicehost.RejectRequest) error { + return m.pick(request.DeviceID).RejectIncomingCall(request) +} + +func (m *Mux) HangupCall(ctx context.Context, deviceID, callID string) error { + return m.pick(deviceID).HangupCall(ctx, deviceID, callID) +} + +func (m *Mux) SendCallDTMF(deviceID, callID, digit string) error { + return m.pick(deviceID).SendCallDTMF(deviceID, callID, digit) +} + +func (m *Mux) StartCallCapture(deviceID, callID, basePath string) error { + return m.pick(deviceID).StartCallCapture(deviceID, callID, basePath) +} + +func (m *Mux) DeviceStatus(deviceID string) map[string]interface{} { + backend := m.pick(deviceID) + if backend == nil { + return map[string]interface{}{"device_id": deviceID, "ready": false} + } + return backend.DeviceStatus(deviceID) +} diff --git a/internal/volte/mux_test.go b/internal/volte/mux_test.go new file mode 100644 index 00000000..8308978d --- /dev/null +++ b/internal/volte/mux_test.go @@ -0,0 +1,63 @@ +package volte + +import ( + "context" + "testing" + + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" +) + +type stubBackend struct { + name string + last string +} + +func (s *stubBackend) SubscribeIncomingCalls(func(voicehost.IncomingCall)) func() { + return func() {} +} +func (s *stubBackend) SubscribeCallEvents(func(voicehost.CallEvent)) func() { return func() {} } +func (s *stubBackend) BeginCall(_ context.Context, req voicehost.BeginCallRequest) (voicehost.CallSnapshot, error) { + s.last = req.DeviceID + return voicehost.CallSnapshot{CallID: s.name + "-" + req.DeviceID, DeviceID: req.DeviceID}, nil +} +func (s *stubBackend) ActiveCall(string) *voicehost.CallSnapshot { return nil } +func (s *stubBackend) AnswerIncomingCall(context.Context, voicehost.AnswerRequest) (voicehost.AnswerResult, error) { + return voicehost.AnswerResult{}, nil +} +func (s *stubBackend) RejectIncomingCall(voicehost.RejectRequest) error { return nil } +func (s *stubBackend) HangupCall(context.Context, string, string) error { return nil } +func (s *stubBackend) SendCallDTMF(string, string, string) error { return nil } +func (s *stubBackend) StartCallCapture(string, string, string) error { return nil } +func (s *stubBackend) DeviceStatus(string) map[string]interface{} { + return map[string]interface{}{"backend": s.name} +} + +func TestMuxRoutesByMode(t *testing.T) { + ims := &stubBackend{name: "ims"} + native := &stubBackend{name: "native"} + mux := &Mux{IMS: ims, Native: native, IsNative: func(id string) bool { return id == "wwan1" }} + + got, err := mux.BeginCall(context.Background(), voicehost.BeginCallRequest{DeviceID: "wwan0"}) + if err != nil || got.CallID != "ims-wwan0" { + t.Fatalf("wifi path: %+v err=%v", got, err) + } + got, err = mux.BeginCall(context.Background(), voicehost.BeginCallRequest{DeviceID: "wwan1"}) + if err != nil || got.CallID != "native-wwan1" { + t.Fatalf("volte path: %+v err=%v", got, err) + } +} + +func TestMapQMIState(t *testing.T) { + state, event := mapQMIState(qmiCallConversation) + if state != "connected" || event != "CallAnswered" { + t.Fatalf("conversation -> %s %s", state, event) + } + state, event = mapQMIState(qmiCallEnd) + if state != "completed" || event != "CallEnded" { + t.Fatalf("end -> %s %s", state, event) + } + state, event = mapQMIState(qmiCallOriginating) + if state != "ringing" || event != "CallRinging" { + t.Fatalf("originating -> %s %s", state, event) + } +} diff --git a/internal/volte/status.go b/internal/volte/status.go new file mode 100644 index 00000000..8a33cade --- /dev/null +++ b/internal/volte/status.go @@ -0,0 +1,27 @@ +package volte + +const ( + PhaseIdle = "idle" + PhaseEnabling = "enabling" + PhaseRegistered = "registered" + PhaseUnverified = "ims_enabled_unverified" + PhaseFailed = "failed" +) + +type Status struct { + DeviceID string `json:"device_id"` + Phase string `json:"phase"` + IMSEnabled bool `json:"ims_enabled"` + VoLTEEnabled bool `json:"volte_enabled"` + IMSRegistered bool `json:"ims_registered"` + VoiceAvailable bool `json:"voice_available"` + UACEnabled bool `json:"uac_enabled"` + AudioDevice string `json:"audio_device,omitempty"` + RebootRequired bool `json:"reboot_required"` + QMIIMSUnavailable bool `json:"qmi_ims_unavailable"` + LastError string `json:"last_error,omitempty"` +} + +func (s Status) Ready() bool { + return s.IMSRegistered || (s.IMSEnabled && s.VoLTEEnabled && s.Phase == PhaseUnverified) +} diff --git a/internal/volte/voice.go b/internal/volte/voice.go new file mode 100644 index 00000000..3e6d7544 --- /dev/null +++ b/internal/volte/voice.go @@ -0,0 +1,349 @@ +package volte + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/iniwex5/quectel-qmi-go/pkg/qmi" + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" +) + +const ( + qmiCallIncoming qmi.VoiceCallState = 0x01 + qmiCallOriginating qmi.VoiceCallState = 0x02 + qmiCallAlerting qmi.VoiceCallState = 0x03 + qmiCallConversation qmi.VoiceCallState = 0x04 + qmiCallEnd qmi.VoiceCallState = 0x08 + qmiDirMO qmi.VoiceCallDirection = 0x01 + qmiDirMT qmi.VoiceCallDirection = 0x02 +) + +type voiceSession struct { + mu sync.Mutex + active map[string]nativeCall + incoming []func(voicehost.IncomingCall) + events []func(voicehost.CallEvent) +} + +type nativeCall struct { + ID string + QMI uint8 + Direction string + Peer string + State string + Start time.Time +} + +func (c *Controller) attachVoice(deviceID string) { + c.mu.Lock() + s := c.sess[deviceID] + if s == nil { + c.mu.Unlock() + return + } + if s.voice == nil { + s.voice = &voiceSession{active: make(map[string]nativeCall)} + } + vs := s.voice + c.mu.Unlock() + _ = c.host.OnVoiceStatus(deviceID, func(info *qmi.VoiceAllCallInfo) { + c.handleVoiceInfo(deviceID, vs, info) + }) +} + +func (c *Controller) SubscribeIncomingCalls(handler func(voicehost.IncomingCall)) func() { + return c.addIncoming("", handler) +} + +func (c *Controller) addIncoming(deviceID string, handler func(voicehost.IncomingCall)) func() { + if c == nil || handler == nil { + return func() {} + } + c.mu.Lock() + defer c.mu.Unlock() + if deviceID == "" { + for _, s := range c.sess { + if s.voice == nil { + s.voice = &voiceSession{active: make(map[string]nativeCall)} + } + s.voice.incoming = append(s.voice.incoming, handler) + } + c.globalIncoming = append(c.globalIncoming, handler) + return func() {} + } + s := c.ensureLocked(deviceID) + s.voice.incoming = append(s.voice.incoming, handler) + return func() {} +} + +func (c *Controller) SubscribeCallEvents(handler func(voicehost.CallEvent)) func() { + if c == nil || handler == nil { + return func() {} + } + c.mu.Lock() + defer c.mu.Unlock() + c.globalEvents = append(c.globalEvents, handler) + for _, s := range c.sess { + if s.voice == nil { + s.voice = &voiceSession{active: make(map[string]nativeCall)} + } + s.voice.events = append(s.voice.events, handler) + } + return func() {} +} + +func (c *Controller) ensureLocked(deviceID string) *session { + s := c.sess[deviceID] + if s == nil { + s = &session{status: Status{DeviceID: deviceID, Phase: PhaseIdle}} + c.sess[deviceID] = s + } + if s.voice == nil { + s.voice = &voiceSession{active: make(map[string]nativeCall)} + } + return s +} + +func (c *Controller) BeginCall(ctx context.Context, request voicehost.BeginCallRequest) (voicehost.CallSnapshot, error) { + deviceID := strings.TrimSpace(request.DeviceID) + if c == nil || c.host == nil { + return voicehost.CallSnapshot{}, errors.New("volte: controller is not configured") + } + st := c.Status(deviceID) + if !st.IMSEnabled || !st.VoLTEEnabled { + return voicehost.CallSnapshot{}, errors.New("volte: native IMS is not enabled") + } + if ctx == nil { + ctx = context.Background() + } + qmiID, err := c.host.VOICEDial(ctx, deviceID, request.Callee) + if err != nil { + return voicehost.CallSnapshot{}, err + } + id := callID(deviceID, qmiID) + now := time.Now() + nc := nativeCall{ID: id, QMI: qmiID, Direction: "outbound", Peer: request.Callee, State: "calling", Start: now} + c.storeCall(deviceID, nc) + c.emitEvent(deviceID, voicehost.CallEvent{ + Type: "CallRinging", DeviceID: deviceID, CallID: id, Callee: request.Callee, + Direction: "outbound", State: "calling", Time: now, + RecordingError: audioError(st), + }) + return voicehost.CallSnapshot{ + CallID: id, DeviceID: deviceID, State: "calling", Direction: "outbound", + Peer: request.Callee, StartTime: now, + }, nil +} + +func (c *Controller) ActiveCall(deviceID string) *voicehost.CallSnapshot { + call, ok := c.lookupActive(strings.TrimSpace(deviceID)) + if !ok { + return nil + } + snap := voicehost.CallSnapshot{ + CallID: call.ID, DeviceID: deviceID, State: call.State, Direction: call.Direction, + Peer: call.Peer, StartTime: call.Start, Duration: time.Since(call.Start), + } + return &snap +} + +func (c *Controller) HangupCall(ctx context.Context, deviceID, id string) error { + call, ok := c.lookup(deviceID, id) + if !ok { + return fmt.Errorf("volte: call %s not found", id) + } + if ctx == nil { + ctx = context.Background() + } + return c.host.VOICEHangup(ctx, deviceID, call.QMI) +} + +func (c *Controller) AnswerIncomingCall(ctx context.Context, request voicehost.AnswerRequest) (voicehost.AnswerResult, error) { + call, ok := c.lookup(request.DeviceID, request.CallID) + if !ok { + return voicehost.AnswerResult{}, fmt.Errorf("volte: call %s not found", request.CallID) + } + if ctx == nil { + ctx = context.Background() + } + if err := c.host.VOICEAnswer(ctx, request.DeviceID, call.QMI); err != nil { + return voicehost.AnswerResult{}, err + } + return voicehost.AnswerResult{CallID: call.ID, State: "connected"}, nil +} + +func (c *Controller) RejectIncomingCall(request voicehost.RejectRequest) error { + call, ok := c.lookup(request.DeviceID, request.CallID) + if !ok { + return fmt.Errorf("volte: call %s not found", request.CallID) + } + return c.host.VOICEHangup(context.Background(), request.DeviceID, call.QMI) +} + +func (c *Controller) SendCallDTMF(deviceID, id, digit string) error { + call, ok := c.lookup(deviceID, id) + if !ok { + return fmt.Errorf("volte: call %s not found", id) + } + return c.host.VOICEBurstDTMF(context.Background(), deviceID, call.QMI, digit) +} + +func (c *Controller) StartCallCapture(string, string, string) error { + return errors.New("volte: capture is unavailable until UAC audio is present") +} + +func (c *Controller) DeviceStatus(deviceID string) map[string]interface{} { + st := c.Status(deviceID) + return map[string]interface{}{ + "device_id": deviceID, + "ready": st.Ready(), + "registered": st.IMSRegistered, + "phase": st.Phase, + "backend": "native_volte", + } +} + +func (c *Controller) handleVoiceInfo(deviceID string, vs *voiceSession, info *qmi.VoiceAllCallInfo) { + if info == nil || vs == nil { + return + } + now := time.Now() + for _, item := range info.Calls { + id := callID(deviceID, item.ID) + peer := remoteNumber(info, item.ID) + state, eventType := mapQMIState(item.State) + dir := "outbound" + if item.Direction == qmiDirMT { + dir = "inbound" + } + prev, existed := vs.get(id) + vs.put(nativeCall{ID: id, QMI: item.ID, Direction: dir, Peer: peer, State: state, Start: startedAt(prev, now)}) + if item.Direction == qmiDirMT && item.State == qmiCallIncoming && !existed { + c.emitIncoming(deviceID, voicehost.IncomingCall{ + DeviceID: deviceID, CallID: id, Caller: peer, State: "ringing", ReceivedAt: now, + }) + } + if eventType != "" { + c.emitEvent(deviceID, voicehost.CallEvent{ + Type: eventType, DeviceID: deviceID, CallID: id, Caller: peer, Callee: peer, + Direction: dir, State: state, Time: now, RecordingError: audioError(c.Status(deviceID)), + }) + } + } +} + +func mapQMIState(state qmi.VoiceCallState) (string, string) { + switch state { + case qmiCallIncoming, qmiCallAlerting, qmiCallOriginating: + return "ringing", "CallRinging" + case qmiCallConversation: + return "connected", "CallAnswered" + case qmiCallEnd: + return "completed", "CallEnded" + default: + return "calling", "" + } +} + +func callID(deviceID string, qmiID uint8) string { + return fmt.Sprintf("volte-%s-%d", deviceID, qmiID) +} + +func remoteNumber(info *qmi.VoiceAllCallInfo, id uint8) string { + for _, n := range info.RemotePartyNumbers { + if n.CallID == id { + return n.Number + } + } + return "" +} + +func startedAt(prev nativeCall, now time.Time) time.Time { + if !prev.Start.IsZero() { + return prev.Start + } + return now +} + +func audioError(st Status) string { + if strings.TrimSpace(st.AudioDevice) != "" && st.UACEnabled && !st.RebootRequired { + return "" + } + if st.RebootRequired { + return "VoLTE 音频需要 UAC,模组可能要重启后才有声卡" + } + return "VoLTE 音频不可用:未检测到 UAC 声卡" +} + +func (c *Controller) storeCall(deviceID string, call nativeCall) { + c.mu.Lock() + s := c.ensureLocked(deviceID) + s.voice.put(call) + c.mu.Unlock() +} + +func (c *Controller) lookup(deviceID, id string) (nativeCall, bool) { + c.mu.Lock() + defer c.mu.Unlock() + s := c.sess[strings.TrimSpace(deviceID)] + if s == nil || s.voice == nil { + return nativeCall{}, false + } + return s.voice.get(id) +} + +func (c *Controller) lookupActive(deviceID string) (nativeCall, bool) { + c.mu.Lock() + defer c.mu.Unlock() + s := c.sess[deviceID] + if s == nil || s.voice == nil { + return nativeCall{}, false + } + for _, call := range s.voice.active { + if call.State != "completed" { + return call, true + } + } + return nativeCall{}, false +} + +func (c *Controller) emitEvent(deviceID string, event voicehost.CallEvent) { + c.mu.Lock() + handlers := append([]func(voicehost.CallEvent){}, c.globalEvents...) + if s := c.sess[deviceID]; s != nil && s.voice != nil { + handlers = append(handlers, s.voice.events...) + } + c.mu.Unlock() + for _, h := range handlers { + h(event) + } +} + +func (c *Controller) emitIncoming(deviceID string, call voicehost.IncomingCall) { + c.mu.Lock() + handlers := append([]func(voicehost.IncomingCall){}, c.globalIncoming...) + if s := c.sess[deviceID]; s != nil && s.voice != nil { + handlers = append(handlers, s.voice.incoming...) + } + c.mu.Unlock() + for _, h := range handlers { + h(call) + } +} + +func (vs *voiceSession) put(call nativeCall) { + vs.mu.Lock() + vs.active[call.ID] = call + vs.mu.Unlock() +} + +func (vs *voiceSession) get(id string) (nativeCall, bool) { + vs.mu.Lock() + defer vs.mu.Unlock() + call, ok := vs.active[id] + return call, ok +} diff --git a/third_party/quectel-qmi-go/pkg/manager/manager.go b/third_party/quectel-qmi-go/pkg/manager/manager.go index df3eed41..f2e50290 100755 --- a/third_party/quectel-qmi-go/pkg/manager/manager.go +++ b/third_party/quectel-qmi-go/pkg/manager/manager.go @@ -1244,6 +1244,49 @@ func (m *Manager) SetIMSServiceEnabled(ctx context.Context, enabled bool) error }) } +// EnsureIMSClients allocates IMS and IMSA on demand. Startup still skips these +// services because some SKUs return CTL 0x001f; VoLTE can retry later. +func (m *Manager) EnsureIMSClients(ctx context.Context) error { + if m == nil || m.client == nil { + return fmt.Errorf("manager not initialized") + } + if ctx == nil { + ctx = context.Background() + } + m.mu.Lock() + if m.ims == nil { + if m.hasQMIService(qmi.ServiceIMS) { + ims, err := qmi.NewIMSService(m.client) + if err != nil { + m.mu.Unlock() + return fmt.Errorf("allocate IMS: %w", err) + } + m.ims = ims + } + } + if m.imsa == nil { + if m.hasQMIService(qmi.ServiceIMSA) { + imsa, err := qmi.NewIMSAService(m.client) + if err != nil { + m.mu.Unlock() + return fmt.Errorf("allocate IMSA: %w", err) + } + m.imsa = imsa + } + } + imsa := m.imsa + m.mu.Unlock() + if imsa == nil { + return ErrServiceNotReady("IMSA") + } + if cfg, ok := m.imsaIndicationRegistration(); ok { + if err := imsa.RegisterIndications(ctx, cfg); err != nil { + return fmt.Errorf("register IMSA indications: %w", err) + } + } + return nil +} + func (m *Manager) shouldAllocateWDA() bool { dataCfg := m.dataConfig() return strings.TrimSpace(m.cfg.Device.NetInterface) != "" && (dataCfg.EnableIPv4 || dataCfg.EnableIPv6) diff --git a/web/src/components/CardPolicyPanel.vue b/web/src/components/CardPolicyPanel.vue index dffd407b..a750eadf 100644 --- a/web/src/components/CardPolicyPanel.vue +++ b/web/src/components/CardPolicyPanel.vue @@ -263,8 +263,8 @@ const airplaneHint = computed(() => { -
+ {{ selected?.native_volte?.reboot_required + ? '原生 IMS 已写入。UAC 声卡要重启模组后才出现,现在可以试信令,音频可能不可用。' + : '会驻网并用模组原生 IMS 打电话,不走软件 WiFi calling。打开「网络」才会用上网流量。' }} +
这张分享卡不能驻国内网,否则 IMSI 会切到 20404,WiFi calling 会废