summaryrefslogtreecommitdiff
path: root/shelly.go
blob: 2fa2fa6644fba1377c2e66a7408f094111a37826 (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
93
94
package main

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

	"github.com/gorilla/websocket"
)

func ShellyRun(config ShellyConfigs, tx chan MQTTMessage, route Route) {
	for _, shelly := range config {
		tx <- MQTTMessage{fmt.Sprintf("cover/%s", shelly.ID), []byte("exists"), true}
	}

	for message := range route.Destination {
		ip, command, err := parseMessage(config, message)
		if err != nil {
			log.Println(err)
			continue
		}

		err = shellySendCommand(ip, command)
		if err != nil {
			log.Printf("Could not send command '%s' to %v: %v", command, ip, err)
		}
	}
}

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,
		)
	}

	if elements[0] != "cover" || elements[2] != "movement" {
		return nil, "", fmt.Errorf("Expected cover/<id>/movement but got: %s", 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)
}

func shellySendCommand(ip *net.IP, command string) error {
	template := `
{
	"jsonrpc":"2.0",
	"id": 1,
	"src":"user_1",
	"method":"%s",
	"params": {
		"id":0
	}
}
`
	message := fmt.Appendf([]byte{}, template, command)

	c, _, err := websocket.DefaultDialer.Dial("ws://" + ip.String() + "/rpc", nil)
	if err != nil {
		return fmt.Errorf("Could not connect to Shelly: %w", err)
	}
	defer c.Close()

	err = c.WriteMessage(websocket.TextMessage, message)
	if err != nil {
		return fmt.Errorf("Failed writing websocket message to Shelly: %w", err)
	}

	return nil
}