feat: 初始化小米 IoT (MIoT) 智能家居 Go 库
- 实现 MIoT 客户端核心功能(MQTT 连接、设备管理、属性读写) - 支持云端 API 调用与局域网设备发现(mDNS) - 集成国际化(i18n)多语言支持 - 添加 MIoT 设备规约解析器(spec_parser) - 包含单元测试与使用示例
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
// E3 — MIPS cloud subscription example.
|
||||
// Demonstrates: connect to MQTT cloud broker → subscribe to device prop/event → wait for messages.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"miot"
|
||||
"miot/examples/config"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 1. Load config
|
||||
cfg, err := config.LoadConfig(config.DefaultPath())
|
||||
if err != nil {
|
||||
fmt.Printf("Load config error: %v\n", err)
|
||||
return
|
||||
}
|
||||
if cfg.AuthInfo.AccessToken == "" {
|
||||
fmt.Println("请先运行 E1 cloud_oauth 获取 token")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Need a device DID — hardcode or get from config
|
||||
did := "2053225728" // use UID as placeholder, user should replace
|
||||
|
||||
fmt.Printf("使用 DID: %s (如无效请修改)\n", did)
|
||||
|
||||
// 2. Create MIPS cloud client
|
||||
mips := miot.NewMipsCloudClient(
|
||||
"ssl://cn-ha.mqtt.io.mi.com:8883",
|
||||
"ha."+cfg.UUID,
|
||||
miot.OAUTH2_CLIENT_ID,
|
||||
cfg.AuthInfo.AccessToken,
|
||||
)
|
||||
fmt.Println("正在连接 MIPS Cloud...")
|
||||
if err := mips.Connect(); err != nil {
|
||||
fmt.Printf("MIPS Connect error: %v\n", err)
|
||||
return
|
||||
}
|
||||
defer mips.Disconnect()
|
||||
fmt.Println("MIPS Cloud 已连接")
|
||||
|
||||
// 4. Subscribe to property changes (wildcard: all properties)
|
||||
propTopic := fmt.Sprintf("device/%s/up/properties_changed/#", did)
|
||||
fmt.Printf("订阅属性: %s\n", propTopic)
|
||||
_ = mips.Subscribe(propTopic, func(topic string, payload []byte) {
|
||||
fmt.Printf("[属性变化] topic=%s, payload=%s\n", topic, string(payload))
|
||||
})
|
||||
|
||||
// 5. Subscribe to events
|
||||
eventTopic := fmt.Sprintf("device/%s/up/event_occured/#", did)
|
||||
fmt.Printf("订阅事件: %s\n", eventTopic)
|
||||
_ = mips.Subscribe(eventTopic, func(topic string, payload []byte) {
|
||||
fmt.Printf("[事件] topic=%s, payload=%s\n", topic, string(payload))
|
||||
})
|
||||
|
||||
// 6. Subscribe to device state
|
||||
stateTopic := fmt.Sprintf("device/%s/state/#", did)
|
||||
fmt.Printf("订阅状态: %s\n", stateTopic)
|
||||
_ = mips.Subscribe(stateTopic, func(topic string, payload []byte) {
|
||||
fmt.Printf("[状态变化] topic=%s, payload=%s\n", topic, string(payload))
|
||||
})
|
||||
|
||||
// 7. Wait for messages
|
||||
fmt.Println("\n等待设备消息 (60秒)...")
|
||||
time.Sleep(60 * time.Second)
|
||||
fmt.Println("示例结束")
|
||||
}
|
||||
Reference in New Issue
Block a user