summaryrefslogtreecommitdiff
path: root/shelly.go
blob: 0f133bc7e19cf0c8c609c9d0022312c71172d3f2 (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
package main

import (
	"fmt"
	"log"
	"net"
	"strings"
)

func ShellyRun(config ShellyConfigs, rx chan MQTTMessage) {
	for message := range rx {
		ip, command, err := parseMessage(config, message)
		if err != nil {
			log.Println(err)
			continue
		}

		log.Printf("Send '%s' to '%s'.", command, ip)
	}
}

func parseMessage(config ShellyConfigs, m MQTTMessage) (ip *net.IP, command string, err error) {
	elements := strings.Split(m.Topic, "/")

	if len(elements) != 3 {
		return nil, "", fmt.Errorf(
			"Expected three topic levels but got %d in '%s'.",
			len(elements), m.Topic,
		)
	}

	switch string(m.Payload) {
	case "extend":
		command = "Cover.Close"
	case "retract":
		command = "Cover.Open"
	case "stop":
		command = "Cover.Stop"
	default:
		return nil, "", fmt.Errorf("Invalid payload '%s'.", m.Payload)
	}

	id := elements[1]

	for _, c := range config {
		if c.ID == id {
			ip := net.ParseIP(c.IP)
			return &ip, command, nil
		}
	}

	return nil, "", fmt.Errorf("Got message for unknown cover '%s'", id)
}