package homematic import ( "fmt" "strconv" "github.com/beevik/etree" ) type Device struct { Type string Subtype string Address string Parent string Version int } func (d Device) String() string { return fmt.Sprintf( "Homematic device\n"+ "TYPE: %s\n"+ "SUBTYPE: %s\n"+ "ADDRESS: %s\n"+ "PARENT: %s\n"+ "VERSION: %d", d.Type, d.Subtype, d.Address, d.Parent, d.Version, ) } func (d *Device) LoadXML(doc *etree.Document) error { types := doc.FindElements("/struct/member[name='TYPE']/value") if len(types) != 1 { return fmt.Errorf("Expected one type field but got %d.", len(types)) } subtypes := doc.FindElements("/struct/member[name='SUBTYPE']/value") if len(subtypes) != 1 { return fmt.Errorf("Expected one subtype field but got %d.", len(subtypes)) } addresses := doc.FindElements("/struct/member[name='ADDRESS']/value") if len(addresses) != 1 { return fmt.Errorf("Expected one address field but got %d.", len(addresses)) } parents := doc.FindElements("/struct/member[name='PARENT']/value") if len(parents) != 1 { return fmt.Errorf("Expected one parent field but got %d.", len(parents)) } versions := doc.FindElements("/struct/member[name='VERSION']/value/i4") if len(versions) != 1 { return fmt.Errorf("Expected one version field but got %d.", len(versions)) } version, err := strconv.Atoi(versions[0].Text()) if err != nil { return fmt.Errorf( "Cannot convert version value '%s' to an integer: %w", versions[0].Text(), err, ) } d.Type = types[0].Text() d.Subtype = subtypes[0].Text() d.Address = addresses[0].Text() d.Parent = parents[0].Text() d.Version = version return nil } type Devices []Device func (devices Devices) String() string { value := "" for index, device := range devices { if index > 0 { value = value + "\n" } value = value + fmt.Sprintf("%v\n", device) } return value }