refactor(logger): 日志改用 logrus 全局包级调用,移除 Logger 注入接口

为什么:并入宿主项目后须与宿主日志体系一致——宿主统一用 pkg/logger 初始化
logrus 全局实例并直接 logrus.Xxx 包级调用;包一层 Logger 接口会让 logrus 的
caller 定位(报告调用文件:行号)失准。

改动:
- 删除 logger 包(Logger 接口 / Default / SetDefault,默认本就是 logrus.StandardLogger)
- 11 个结构体移除 lgr logger.Logger 字段、SetLogger 方法及构造中的 lgr 初始化
- 192 处 lgr.Xxxf 调用改为 logrus.Xxxf,日志消息文本保持不变
- xiaomi.Client 移除 Logger() 访问器,air_conditioner 回读日志去掉判空调用直连 logrus
- miot_i18n.go 两处标准库 log.Printf 改为 logrus.Errorf,统一日志出口
- go.mod:logrus 从 indirect 提升为直接依赖
- goimports/goformat 全树规范化:此前部分文件未 gofmt(单行 if、对齐),本次顺带
  格式化,纯空白/换行变化,无逻辑改动

验证:go build / go vet / go test ./... 全部通过(bridge、miot、xiaomi、devices、specs)
This commit is contained in:
2026-09-15 20:16:26 +08:00
parent 7ae32bd012
commit 2b7de69403
46 changed files with 1166 additions and 903 deletions
+89 -96
View File
@@ -19,7 +19,7 @@ import (
"sync/atomic"
"time"
"xiaomihome/logger"
"github.com/sirupsen/logrus"
)
// ============================================================================
@@ -27,23 +27,23 @@ import (
// ============================================================================
const (
otHeader = 0x2131
otHeaderLen = 32
otPort = 54321
otProbeLen = 32
otMsgLen = 1400
otSupportWildcardSub = 0xFE
otHeader = 0x2131
otHeaderLen = 32
otPort = 54321
otProbeLen = 32
otMsgLen = 1400
otSupportWildcardSub = 0xFE
// Keep-alive intervals (seconds)
kaIntervalMin = 10.0
kaIntervalMax = 50.0
fastPingInterval = 5.0
kaIntervalMin = 10.0
kaIntervalMax = 50.0
fastPingInterval = 5.0
constructStatePending = 15.0
// Network instability detection
networkUnstableCntTh = 10
networkUnstableTimeTh = 120.0
networkUnstableResumeTh = 300.0
networkUnstableCntTh = 10
networkUnstableTimeTh = 120.0
networkUnstableResumeTh = 300.0
// Scan intervals (seconds)
otProbeIntervalMin = 5.0
@@ -90,26 +90,26 @@ func (s LanDeviceState) String() string {
// LanDevice manages the encrypted UDP communication and keep-alive for one
// MIoT SPEC-v2 WiFi device on the local network.
type LanDevice struct {
DID string
Token []byte
IP string
IfName string
DID string
Token []byte
IP string
IfName string
manager *MIoTLan
cipher cipher.Block
aesIV []byte
manager *MIoTLan
cipher cipher.Block
aesIV []byte
offset int
subscribed bool
subTS int
offset int
subscribed bool
subTS int
supportedWildcardSub bool
subLocked bool
subLocked bool
state LanDeviceState
online bool
onlineHistory []onlineEvent
unstableTimer *time.Timer
onlineHistory []onlineEvent
unstableTimer *time.Timer
kaTimer *time.Timer
kaInterval float64
@@ -138,15 +138,15 @@ func newLanDevice(mgr *MIoTLan, did, tokenHex, ip string) (*LanDevice, error) {
}
d := &LanDevice{
DID: did,
Token: token,
IP: ip,
manager: mgr,
cipher: block,
aesIV: aesIV[:],
state: LanDeviceDead,
online: false,
kaInterval: kaIntervalMin,
DID: did,
Token: token,
IP: ip,
manager: mgr,
cipher: block,
aesIV: aesIV[:],
state: LanDeviceDead,
online: false,
kaInterval: kaIntervalMin,
onlineHistory: make([]onlineEvent, 0),
}
@@ -156,7 +156,7 @@ func newLanDevice(mgr *MIoTLan, did, tokenHex, ip string) (*LanDevice, error) {
d.updateKeepAlive(LanDeviceDead)
})
mgr.lgr.Debugf("[lan] device added: did=%s", d.DID)
logrus.Debugf("[lan] device added: did=%s", d.DID)
return d, nil
}
@@ -165,7 +165,7 @@ func (d *LanDevice) KeepAlive(ip, ifName string) {
d.IP = ip
if d.IfName != ifName {
d.IfName = ifName
d.manager.lgr.Debugf("[lan] device if_name changed: %s, did=%s", d.IfName, d.DID)
logrus.Debugf("[lan] device if_name changed: %s, did=%s", d.IfName, d.DID)
}
d.updateKeepAlive(LanDeviceFresh)
}
@@ -316,12 +316,12 @@ func (d *LanDevice) Subscribe() {
func (d *LanDevice) subscribeHandler(msg map[string]interface{}, subTS int) {
result, _ := msg["result"].(map[string]interface{})
if result == nil {
d.manager.lgr.Warnf("[lan] subscribe error: no result, did=%s, msg=%v", d.DID, msg)
logrus.Warnf("[lan] subscribe error: no result, did=%s, msg=%v", d.DID, msg)
return
}
code, _ := result["code"].(float64)
if code != 0 {
d.manager.lgr.Warnf("[lan] subscribe error: code=%v, did=%s, msg=%v", code, d.DID, msg)
logrus.Warnf("[lan] subscribe error: code=%v, did=%s, msg=%v", code, d.DID, msg)
return
}
d.subscribed = true
@@ -330,7 +330,7 @@ func (d *LanDevice) subscribeHandler(msg map[string]interface{}, subTS int) {
"online": d.online,
"push_available": d.subscribed,
})
d.manager.lgr.Debugf("[lan] subscribe success: if=%s, did=%s", d.IfName, d.DID)
logrus.Debugf("[lan] subscribe success: if=%s, did=%s", d.IfName, d.DID)
}
// Unsubscribe sends a miIO.unsub request to the device.
@@ -351,11 +351,11 @@ func (d *LanDevice) Unsubscribe() {
result, _ := msg["result"].(map[string]interface{})
if result != nil {
if code, _ := result["code"].(float64); code != 0 {
d.manager.lgr.Warnf("[lan] unsubscribe error: code=%v, did=%s, msg=%v", code, d.DID, msg)
logrus.Warnf("[lan] unsubscribe error: code=%v, did=%s, msg=%v", code, d.DID, msg)
return
}
}
d.manager.lgr.Debugf("[lan] unsubscribe success: if=%s, did=%s", d.IfName, d.DID)
logrus.Debugf("[lan] unsubscribe success: if=%s, did=%s", d.IfName, d.DID)
}, nil, 5000)
d.subscribed = false
d.manager.broadcastDeviceState(d.DID, map[string]interface{}{
@@ -374,7 +374,7 @@ func (d *LanDevice) OnDelete() {
d.unstableTimer.Stop()
d.unstableTimer = nil
}
d.manager.lgr.Debugf("[lan] device deleted: did=%s", d.DID)
logrus.Debugf("[lan] device deleted: did=%s", d.DID)
}
// UpdateInfo updates the device token if it has changed.
@@ -396,12 +396,12 @@ func (d *LanDevice) UpdateInfo(info map[string]interface{}) {
aesIV := md5Sum(append(aesKey[:], d.Token...))
block, err := aes.NewCipher(aesKey[:])
if err != nil {
d.manager.lgr.Warnf("[lan] update token cipher error: %v, did=%s", err, d.DID)
logrus.Warnf("[lan] update token cipher error: %v, did=%s", err, d.DID)
return
}
d.cipher = block
d.aesIV = aesIV[:]
d.manager.lgr.Debugf("[lan] token updated: did=%s", d.DID)
logrus.Debugf("[lan] token updated: did=%s", d.DID)
}
// ============================================================================
@@ -413,7 +413,7 @@ func (d *LanDevice) updateKeepAlive(state LanDeviceState) {
d.state = state
if d.state != LanDeviceFresh {
d.manager.lgr.Debugf("[lan] device status: did=%s, state=%s", d.DID, d.state)
logrus.Debugf("[lan] device status: did=%s, state=%s", d.DID, d.state)
}
// Cancel existing timer
@@ -441,11 +441,11 @@ func (d *LanDevice) updateKeepAlive(state LanDeviceState) {
})
// Fast ping
if d.IfName == "" {
d.manager.lgr.Debugf("[lan] if_name not set for device: did=%s", d.DID)
logrus.Debugf("[lan] if_name not set for device: did=%s", d.DID)
return
}
if d.IP == "" {
d.manager.lgr.Debugf("[lan] ip not set for device: did=%s", d.DID)
logrus.Debugf("[lan] ip not set for device: did=%s", d.DID)
return
}
d.manager.ping(d.IfName, d.IP)
@@ -464,7 +464,7 @@ func (d *LanDevice) nextKATimeout() float64 {
}
func (d *LanDevice) changeOnline(online bool) {
d.manager.lgr.Debugf("[lan] change online: did=%s, online=%v", d.DID, online)
logrus.Debugf("[lan] change online: did=%s, online=%v", d.DID, online)
tsNow := int(time.Now().Unix())
d.onlineHistory = append(d.onlineHistory, onlineEvent{ts: tsNow, online: online})
if len(d.onlineHistory) > networkUnstableCntTh {
@@ -483,9 +483,9 @@ func (d *LanDevice) changeOnline(online bool) {
float64(tsNow-d.onlineHistory[0].ts) > networkUnstableTimeTh {
d.setOnline(true)
} else {
d.manager.lgr.Debugf("[lan] unstable device detected: did=%s", d.DID)
logrus.Debugf("[lan] unstable device detected: did=%s", d.DID)
d.unstableTimer = time.AfterFunc(time.Duration(networkUnstableResumeTh*float64(time.Second)), func() {
d.manager.lgr.Debugf("[lan] unstable resume threshold passed: did=%s", d.DID)
logrus.Debugf("[lan] unstable resume threshold passed: did=%s", d.DID)
d.setOnline(true)
})
}
@@ -531,8 +531,8 @@ type MIoTLan struct {
initMu sync.Mutex
// Network state
availableIFs map[string]bool
scanTimer *time.Timer
availableIFs map[string]bool
scanTimer *time.Timer
lastScanInterval float64
// LAN state votes
@@ -541,8 +541,6 @@ type MIoTLan struct {
// Profile models (loaded from YAML, models that should NOT use LAN control)
profileModels map[string]bool
lgr logger.Logger
}
type pendingRequest struct {
@@ -604,10 +602,8 @@ func NewMIoTLan(netIFs []string, network *MIoTNetwork, mipsService *MipsService,
lanStateSubs: make(map[string]func(bool)),
lanCtrlVotes: make(map[string]bool),
profileModels: make(map[string]bool),
lgr: logger.Default(),
}
for _, ifName := range netIFs {
m.netIFs[ifName] = true
}
@@ -620,7 +616,7 @@ func NewMIoTLan(netIFs []string, network *MIoTNetwork, mipsService *MipsService,
// Auto-init if no central hub gateway exists and we have interfaces
if len(mipsService.GetServices("")) == 0 && len(netIFs) > 0 {
m.lgr.Infof("[lan] no central hub gateway service, scheduling init")
logrus.Infof("[lan] no central hub gateway service, scheduling init")
go func() {
m.Init()
}()
@@ -629,9 +625,6 @@ func NewMIoTLan(netIFs []string, network *MIoTNetwork, mipsService *MipsService,
return m, nil
}
// SetLogger sets a custom logger for MIoTLan.
func (m *MIoTLan) SetLogger(l logger.Logger) { m.lgr = l }
// VirtualDID returns the virtual device ID used for LAN communication.
func (m *MIoTLan) VirtualDID() string {
return m.virtualDID
@@ -656,12 +649,12 @@ func (m *MIoTLan) Init() {
m.mu.Lock()
if m.initDone {
m.mu.Unlock()
m.lgr.Infof("[lan] already initialized")
logrus.Infof("[lan] already initialized")
return
}
if len(m.netIFs) == 0 {
m.mu.Unlock()
m.lgr.Infof("[lan] no net_ifs configured")
logrus.Infof("[lan] no net_ifs configured")
return
}
@@ -675,13 +668,13 @@ func (m *MIoTLan) Init() {
}
if !hasVote {
m.mu.Unlock()
m.lgr.Infof("[lan] no vote for lan ctrl")
logrus.Infof("[lan] no vote for lan ctrl")
return
}
if len(m.mipsService.GetServices("")) > 0 {
m.mu.Unlock()
m.lgr.Infof("[lan] central hub gateway service exists, skip LAN init")
logrus.Infof("[lan] central hub gateway service exists, skip LAN init")
return
}
@@ -691,7 +684,7 @@ func (m *MIoTLan) Init() {
}
if len(m.availableIFs) == 0 {
m.mu.Unlock()
m.lgr.Infof("[lan] no available network interfaces")
logrus.Infof("[lan] no available network interfaces")
return
}
@@ -705,7 +698,7 @@ func (m *MIoTLan) Init() {
}
if !hasValid {
m.mu.Unlock()
m.lgr.Infof("[lan] no valid net_ifs matching configured list")
logrus.Infof("[lan] no valid net_ifs matching configured list")
return
}
@@ -729,7 +722,7 @@ func (m *MIoTLan) Init() {
go h(true)
}
m.lgr.Infof("[lan] initialized: netIFs=%v, available=%v", m.netIFs, m.availableIFs)
logrus.Infof("[lan] initialized: netIFs=%v, available=%v", m.netIFs, m.availableIFs)
}
// Deinit stops the LAN controller.
@@ -740,7 +733,7 @@ func (m *MIoTLan) Deinit() {
m.mu.Lock()
if !m.initDone {
m.mu.Unlock()
m.lgr.Infof("[lan] not initialized")
logrus.Infof("[lan] not initialized")
return
}
m.initDone = false
@@ -773,7 +766,7 @@ func (m *MIoTLan) Deinit() {
go h(false)
}
m.lgr.Infof("[lan] deinitialized")
logrus.Infof("[lan] deinitialized")
}
// ============================================================================
@@ -781,7 +774,7 @@ func (m *MIoTLan) Deinit() {
// ============================================================================
func (m *MIoTLan) internalLoop() {
m.lgr.Infof("[lan] internal loop started")
logrus.Infof("[lan] internal loop started")
m.initSockets()
// Start scan timer
@@ -794,7 +787,7 @@ func (m *MIoTLan) internalLoop() {
if cmd == nil {
// Stop signal
m.deinitInternal()
m.lgr.Infof("[lan] internal loop stopped")
logrus.Infof("[lan] internal loop stopped")
return
}
cmd()
@@ -866,13 +859,13 @@ func (m *MIoTLan) createSocketLocked(ifName string) {
ni := m.network.GetNetworkInfo()
info, ok := ni[ifName]
if !ok || info.IP == "" {
m.lgr.Infof("[lan] no IP for interface: %s", ifName)
logrus.Infof("[lan] no IP for interface: %s", ifName)
return
}
conn, err := createBoundSocket(info.IP, m.localPort)
if err != nil {
m.lgr.Warnf("[lan] create socket error: if=%s, err=%v", ifName, err)
logrus.Warnf("[lan] create socket error: if=%s, err=%v", ifName, err)
return
}
@@ -885,7 +878,7 @@ func (m *MIoTLan) createSocketLocked(ifName string) {
// Start reader goroutine for this socket
go m.socketReader(ifName, conn)
m.lgr.Infof("[lan] socket created: if=%s, ip=%s, port=%d", ifName, info.IP, m.localPort)
logrus.Infof("[lan] socket created: if=%s, ip=%s, port=%d", ifName, info.IP, m.localPort)
}
func (m *MIoTLan) destroySocketLocked(ifName string) {
@@ -895,7 +888,7 @@ func (m *MIoTLan) destroySocketLocked(ifName string) {
}
delete(m.socks, ifName)
conn.Close()
m.lgr.Infof("[lan] socket destroyed: if=%s", ifName)
logrus.Infof("[lan] socket destroyed: if=%s", ifName)
}
// createBoundSocket creates a UDP socket bound to a specific IP address.
@@ -944,7 +937,7 @@ func (m *MIoTLan) send(ifName, targetIP string, data []byte) {
} else {
conn, ok := m.socks[ifName]
if !ok {
m.lgr.Debugf("[lan] invalid socket: if=%s", ifName)
logrus.Debugf("[lan] invalid socket: if=%s", ifName)
return
}
conn.WriteToUDP(data, &net.UDPAddr{IP: net.ParseIP(targetIP), Port: otPort})
@@ -1118,7 +1111,7 @@ func (m *MIoTLan) handleRawMessage(data []byte, dataLen int, ip, ifName string)
if dataLen > otProbeLen {
msg, err := dev.DecryptPacket(data[:dataLen])
if err != nil {
m.lgr.Debugf("[lan] decrypt error: did=%s, err=%v", did, err)
logrus.Debugf("[lan] decrypt error: did=%s, err=%v", did, err)
return
}
m.handleMessage(did, msg)
@@ -1128,7 +1121,7 @@ func (m *MIoTLan) handleRawMessage(data []byte, dataLen int, ip, ifName string)
func (m *MIoTLan) handleMessage(did string, msg map[string]interface{}) {
msgID, ok := msg["id"]
if !ok {
m.lgr.Debugf("[lan] message without id: did=%s, msg=%v", did, msg)
logrus.Debugf("[lan] message without id: did=%s, msg=%v", did, msg)
return
}
id, ok := toInt(msgID)
@@ -1169,7 +1162,7 @@ func (m *MIoTLan) handleMessage(did string, msg map[string]interface{}) {
return
}
m.lgr.Debugf("[lan] message: did=%s, method=%s", did, method)
logrus.Debugf("[lan] message: did=%s, method=%s", did, method)
switch method {
case "properties_changed":
@@ -1264,7 +1257,7 @@ func (m *MIoTLan) scanDevices() {
scanTime := m.nextScanTime()
m.scanTimer = time.AfterFunc(time.Duration(scanTime*float64(time.Second)), m.scanDevices)
m.lgr.Debugf("[lan] next scan in %.0fs", scanTime)
logrus.Debugf("[lan] next scan in %.0fs", scanTime)
}
func (m *MIoTLan) nextScanTime() float64 {
@@ -1280,7 +1273,7 @@ func (m *MIoTLan) nextScanTime() float64 {
// ============================================================================
func (m *MIoTLan) onNetworkInfoChange(status InterfaceStatus, info *NetworkInfo) {
m.lgr.Infof("[lan] network info change: status=%s, if=%s", status, info.Name)
logrus.Infof("[lan] network info change: status=%s, if=%s", status, info.Name)
m.mu.Lock()
// Rebuild available IFs
@@ -1304,7 +1297,7 @@ func (m *MIoTLan) onNetworkInfoChange(status InterfaceStatus, info *NetworkInfo)
}
if !valid {
m.mu.Unlock()
m.lgr.Infof("[lan] no valid net_ifs after change")
logrus.Infof("[lan] no valid net_ifs after change")
go m.Deinit()
return
}
@@ -1340,12 +1333,12 @@ func (m *MIoTLan) onNetworkInfoChange(status InterfaceStatus, info *NetworkInfo)
// ============================================================================
func (m *MIoTLan) onMipsServiceChange(groupID string, state MipsServiceState, data map[string]interface{}) {
m.lgr.Infof("[lan] mips service change: groupID=%s, state=%s, data=%v", groupID, state, data)
logrus.Infof("[lan] mips service change: groupID=%s, state=%s, data=%v", groupID, state, data)
if len(m.mipsService.GetServices("")) > 0 {
m.lgr.Infof("[lan] central hub gateway found, deinit LAN")
logrus.Infof("[lan] central hub gateway found, deinit LAN")
go m.Deinit()
} else {
m.lgr.Infof("[lan] no central hub gateway, init LAN")
logrus.Infof("[lan] no central hub gateway, init LAN")
go m.Init()
}
}
@@ -1356,7 +1349,7 @@ func (m *MIoTLan) onMipsServiceChange(groupID string, state MipsServiceState, da
// VoteForLanCtrl votes for or against LAN control.
func (m *MIoTLan) VoteForLanCtrl(key string, vote bool) {
m.lgr.Infof("[lan] vote for lan ctrl: key=%s, vote=%v", key, vote)
logrus.Infof("[lan] vote for lan ctrl: key=%s, vote=%v", key, vote)
m.mu.Lock()
m.lanCtrlVotes[key] = vote
hasVote := false
@@ -1377,7 +1370,7 @@ func (m *MIoTLan) VoteForLanCtrl(key string, vote bool) {
// UpdateSubscribeOption enables or disables device subscriptions.
func (m *MIoTLan) UpdateSubscribeOption(enable bool) {
m.lgr.Infof("[lan] update subscribe option: %v", enable)
logrus.Infof("[lan] update subscribe option: %v", enable)
m.mu.Lock()
oldEnable := m.enableSub
m.enableSub = enable
@@ -1406,12 +1399,12 @@ func (m *MIoTLan) UpdateDevices(devices map[string]map[string]interface{}) {
for did, info := range devices {
if !isNumeric(did) {
m.lgr.Infof("[lan] invalid did (non-numeric): %s", did)
logrus.Infof("[lan] invalid did (non-numeric): %s", did)
continue
}
model, _ := info["model"].(string)
if model != "" && m.profileModels[model] {
m.lgr.Debugf("[lan] model not supported for LAN ctrl: did=%s, model=%s", did, model)
logrus.Debugf("[lan] model not supported for LAN ctrl: did=%s, model=%s", did, model)
continue
}
if existing, ok := m.devices[did]; ok {
@@ -1419,13 +1412,13 @@ func (m *MIoTLan) UpdateDevices(devices map[string]map[string]interface{}) {
} else {
tokenStr, _ := info["token"].(string)
if len(tokenStr) != 32 {
m.lgr.Debugf("[lan] invalid token for device: did=%s", did)
logrus.Debugf("[lan] invalid token for device: did=%s", did)
continue
}
ip, _ := info["ip"].(string)
dev, err := newLanDevice(m, did, tokenStr, ip)
if err != nil {
m.lgr.Warnf("[lan] create device error: did=%s, err=%v", did, err)
logrus.Warnf("[lan] create device error: did=%s, err=%v", did, err)
continue
}
m.devices[did] = dev
@@ -1491,7 +1484,7 @@ func (m *MIoTLan) SubProp(did string, handler func(map[string]interface{}, inter
}
m.cmdCh <- func() {
m.matcher.Sub(key, handler, ctx)
m.lgr.Debugf("[lan] sub prop: key=%s", key)
logrus.Debugf("[lan] sub prop: key=%s", key)
}
}
@@ -1503,7 +1496,7 @@ func (m *MIoTLan) UnsubProp(did string, siid, piid int) {
}
m.cmdCh <- func() {
m.matcher.Unsub(key)
m.lgr.Debugf("[lan] unsub prop: key=%s", key)
logrus.Debugf("[lan] unsub prop: key=%s", key)
}
}
@@ -1515,7 +1508,7 @@ func (m *MIoTLan) SubEvent(did string, handler func(map[string]interface{}, inte
}
m.cmdCh <- func() {
m.matcher.Sub(key, handler, ctx)
m.lgr.Debugf("[lan] sub event: key=%s", key)
logrus.Debugf("[lan] sub event: key=%s", key)
}
}
@@ -1527,7 +1520,7 @@ func (m *MIoTLan) UnsubEvent(did string, siid, eiid int) {
}
m.cmdCh <- func() {
m.matcher.Unsub(key)
m.lgr.Debugf("[lan] unsub event: key=%s", key)
logrus.Debugf("[lan] unsub event: key=%s", key)
}
}