// E8 — MIoT device spec parser example. // Demonstrates: parse a device URN → iterate services/properties/actions → query value lists. package main import ( "fmt" "xiaomihome/miot" ) func main() { // 1. Create storage (needed for spec caching) storage := miot.NewMIoTStorage("./data") // 2. Create spec parser parser := miot.NewMIoTSpecParser("zh-Hans", storage, "specs") fmt.Println("Spec 解析器已创建") // 3. Parse a sample device URN urn := "urn:miot-spec-v2:device:light:0000A001:yeelink-light1:1" fmt.Printf("\n解析 URN: %s\n", urn) instance, err := parser.Parse(urn, "") if err != nil { fmt.Printf("Parse error: %v\n", err) fmt.Println("\n提示: 请先在 ./specs/ 目录下放置对应的 JSON 规格文件") return } // 4. Print instance info fmt.Printf("\n=== 设备规格 ===\n") fmt.Printf("URN: %s\n", instance.URN) fmt.Printf("Type: %s\n", instance.Type) fmt.Printf("Description: %s\n", instance.DescriptionTrans) fmt.Printf("Services: %d\n", len(instance.Services)) // 5. Iterate each service for _, svc := range instance.Services { fmt.Printf("\n--- Service: %s ---\n", svc.DescriptionTrans) fmt.Printf(" Type: %s\n", svc.Type) fmt.Printf(" IID: %d\n", svc.IID) fmt.Printf(" Description: %s\n", svc.Description) // Properties if len(svc.Properties) > 0 { fmt.Printf(" Properties (%d):\n", len(svc.Properties)) for _, prop := range svc.Properties { fmt.Printf(" [%d.%d] %s\n", prop.SIID, prop.PIID, prop.DescriptionTrans) fmt.Printf(" Format: %s, Access: %v", prop.Format, prop.Access) if prop.Writable() { fmt.Printf(" [可写]") } if prop.Readable() { fmt.Printf(" [可读]") } fmt.Println() if prop.ValueRange != nil { fmt.Printf(" Range: [%v, %v], Step: %v\n", prop.ValueRange.Min, prop.ValueRange.Max, prop.ValueRange.Step) } if len(prop.ValueList) > 0 { fmt.Printf(" ValueList (%d items):\n", len(prop.ValueList)) names := prop.ValueList.Names() for i, item := range prop.ValueList { fmt.Printf(" - %s: %v (%s)\n", names[i], item.Value, item.Desc) } // Demonstrate GetValueByDescription if firstDesc := prop.ValueList[0].Desc; firstDesc != "" { v := prop.ValueList.GetValueByDescription(firstDesc) fmt.Printf(" GetValueByDescription(%q) = %v\n", firstDesc, v) } } } } // Actions if len(svc.Actions) > 0 { fmt.Printf(" Actions (%d):\n", len(svc.Actions)) for _, act := range svc.Actions { fmt.Printf(" [%d.%d] %s\n", act.SIID, act.AIID, act.DescriptionTrans) if len(act.In) > 0 { fmt.Printf(" In: %v\n", act.In) } if len(act.Out) > 0 { fmt.Printf(" Out: %v\n", act.Out) } } } } // 6. Demonstrate ValuePrecision / ValueFormat if len(instance.Services) > 0 && len(instance.Services[0].Properties) > 0 { prop := instance.Services[0].Properties[0] fmt.Printf("\n=== 值转换演示 (property: %s) ===\n", prop.DescriptionTrans) raw := prop.ValueFormat("1") fmt.Printf(" ValueFormat(\"1\") = %v (type: %T)\n", raw, raw) prec := prop.ValuePrecision(3.14159) fmt.Printf(" ValuePrecision(3.14159) = %v\n", prec) expr := prop.EvalExpr(100.0) fmt.Printf(" EvalExpr(100.0) = %v\n", expr) } fmt.Println("\n示例结束") }