- 实现 MIoT 客户端核心功能(MQTT 连接、设备管理、属性读写) - 支持云端 API 调用与局域网设备发现(mDNS) - 集成国际化(i18n)多语言支持 - 添加 MIoT 设备规约解析器(spec_parser) - 包含单元测试与使用示例
66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
// E4 — LAN device control example.
|
|
// Demonstrates: init network → create LAN controller → register device → wait for online → subscribe.
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"miot"
|
|
)
|
|
|
|
func main() {
|
|
// 1. Initialize network monitor
|
|
network := miot.NewMIoTNetwork(nil, nil, 30*time.Second)
|
|
network.Init()
|
|
defer network.Deinit()
|
|
|
|
// 3. Create MIPS service (required by MIoTLan)
|
|
svc := miot.NewMipsService()
|
|
svc.Init()
|
|
defer svc.Deinit()
|
|
|
|
// 4. Create LAN controller
|
|
lan, err := miot.NewMIoTLan(nil, network, svc, true, 0)
|
|
if err != nil {
|
|
fmt.Printf("Create LAN error: %v\n", err)
|
|
return
|
|
}
|
|
defer lan.Deinit()
|
|
|
|
// 5. Register devices with hardcoded values
|
|
// Replace with your actual device DID and token (32 hex chars)
|
|
devices := map[string]map[string]interface{}{
|
|
"12345678": {
|
|
"did": "12345678",
|
|
"token": "00000000000000000000000000000000",
|
|
},
|
|
}
|
|
lan.UpdateDevices(devices)
|
|
fmt.Println("已注册设备,等待上线...")
|
|
|
|
// 6. Subscribe to device state
|
|
lan.SubDeviceState("demo", func(did string, state map[string]interface{}, ctx interface{}) {
|
|
fmt.Printf("[设备状态] DID=%s, State=%v\n", did, state)
|
|
}, nil)
|
|
|
|
// 7. Subscribe to property changes (all properties)
|
|
did := "12345678"
|
|
lan.SubProp(did, func(params map[string]interface{}, ctx interface{}) {
|
|
fmt.Printf("[属性变化] DID=%s, siid=%v, piid=%v, value=%v\n",
|
|
params["did"], params["siid"], params["piid"], params["value"])
|
|
}, 0, 0, nil)
|
|
|
|
// 8. Wait for device to come online
|
|
fmt.Println("等待设备上线 (30秒)...")
|
|
time.Sleep(30 * time.Second)
|
|
|
|
// Print current online devices
|
|
devList := lan.GetDevList()
|
|
fmt.Println("\n=== 在线设备 ===")
|
|
for did, state := range devList {
|
|
fmt.Printf(" DID: %s, State: %v\n", did, state)
|
|
}
|
|
fmt.Println("示例结束")
|
|
}
|