refactor: 重构 token 管理,新增 NATS adapter 和多示例
按照 TOKEN_REFACTOR.md / FIX_CONFIG.md 方案重构核心层: - miot: Init() 优先读 storage token,新增 RefreshAuthInfo() 和刷新回调 - xiaomi: Config 改用 AuthInfo 结构体(含 UUID/UID/DataDir/OnTokenRefreshed) - xiaomi: NewClient(ctx, Config) 新签名,新增 RefreshToken(),后台自动刷新 - xiaomi/devices: 设备控制接口重构 - 新增示例 12_ac_subscribe,其余示例适配新 Config
This commit is contained in:
@@ -23,13 +23,14 @@ type Switch interface {
|
||||
ToggleChannel(ctx context.Context, ch int) error
|
||||
IsChannelOn(ctx context.Context, ch int) (bool, error)
|
||||
|
||||
OnStateChanged(handler func(on bool)) (string, error)
|
||||
OnStateChanged(handler func(ch int, on bool)) (string, error)
|
||||
}
|
||||
|
||||
// switchDevice is the concrete Switch implementation.
|
||||
type switchDevice struct {
|
||||
BaseDevice
|
||||
channels []siidPiid // "on" property per channel (index 0 = channel 1)
|
||||
channels []siidPiid // "on" property per channel (index 0 = channel 1)
|
||||
stateCache []bool // MQTT 推送维护的本地缓存,索引 0 = 通道 1
|
||||
}
|
||||
|
||||
type siidPiid struct {
|
||||
@@ -63,6 +64,7 @@ func NewSwitch(client *xiaomi.Client, info *xiaomi.DeviceInfo) (Switch, error) {
|
||||
return nil, xiaomi.ErrNotSupported
|
||||
}
|
||||
d.channels = channels
|
||||
d.stateCache = make([]bool, len(channels))
|
||||
|
||||
return d, nil
|
||||
}
|
||||
@@ -129,14 +131,25 @@ func (d *switchDevice) IsChannelOn(ctx context.Context, ch int) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (d *switchDevice) OnStateChanged(handler func(on bool)) (string, error) {
|
||||
p, ok := d.channel(1)
|
||||
if !ok {
|
||||
func (d *switchDevice) OnStateChanged(handler func(ch int, on bool)) (string, error) {
|
||||
if len(d.channels) == 0 {
|
||||
return "", xiaomi.ErrNotSupported
|
||||
}
|
||||
return d.SubProp(p.siid, p.piid, func(did string, prop *xiaomi.PropertyValue) {
|
||||
if b, ok := prop.Value.(bool); ok {
|
||||
handler(b)
|
||||
// 构建 siid/piid → channel index 的快速查找表
|
||||
type chField struct{ siid, piid int }
|
||||
lookup := make(map[chField]int) // key → channel index (0-based)
|
||||
for i, c := range d.channels {
|
||||
lookup[chField{c.siid, c.piid}] = i
|
||||
}
|
||||
return d.SubProp(0, 0, func(did string, prop *xiaomi.PropertyValue) {
|
||||
for k, idx := range lookup {
|
||||
if k.siid == prop.SIID && k.piid == prop.PIID {
|
||||
if b, ok := prop.Value.(bool); ok {
|
||||
d.stateCache[idx] = b
|
||||
handler(idx+1, b) // ch = idx+1
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user