summaryrefslogtreecommitdiff
path: root/homematic.go
blob: 4bae0cae494dca10b7dbaeddd66aee8a2dcfdbd2 (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
package main

import (
	"fmt"
	"log"
	"time"

	"xengineering.eu/homematic-go/homematic"
)

func HomematicRun(config HomematicConfig, tx chan MQTTMessage) {
	req, inventory, err := Start(config.CCU)
	if err != nil {
		log.Fatalf("Failed startup process: %v", err)
	}

	cache := NewCache(tx)

	pollingPeriod, err := time.ParseDuration(config.PollingPeriod)
	if err != nil {
		log.Fatalf("Failed to parse Homematic polling period: %v", err)
	}

	for {
		start := time.Now()

		states, _ := Poll(req, inventory)

		cache.Update(states)

		WaitUntil(start.Add(pollingPeriod))
	}

}

func Start(ccu string) (homematic.Requester, homematic.Devices, error) {
	var req homematic.Requester
	var inventory homematic.Devices
	var err error

	req = homematic.NewRequester(ccu)
	log.Printf("Created Homematic requester (%s).", ccu)

	inventory, err = req.ListDevices()
	if err != nil {
		return req, inventory, fmt.Errorf("Failed getting initial device list: %w", err)
	}
	log.Printf("Retrieved Homematic inventory with %d devices.", len(inventory))

	return req, inventory, nil
}

func Poll(req homematic.Requester, inventory homematic.Devices) (States, error) {
	states := make(States)

	for _, device := range inventory {
		if device.Type == `SHUTTER_CONTACT` {
			state, err := req.GetValue(device.Address)
			if err != nil {
				return states, fmt.Errorf("Failed to get value: %w", err)
			}
			states[device.Address] = state
		}
	}

	return states, nil
}

func WaitUntil(deadline time.Time) {
	duration := time.Until(deadline)
	if duration > 0 {
		time.Sleep(duration)
	}
}