summaryrefslogtreecommitdiff
path: root/vendor/xengineering.eu/homematic-go/homematic/device.go
blob: fc7f38360bd77bb5673e9b754f4ffddbe46494e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
}