-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (97 loc) · 2.42 KB
/
main.go
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"github.com/zalando/go-keyring"
"golang.org/x/crypto/ssh/terminal"
"net/http"
"os"
"syscall"
)
const (
Title = "Home Assistant Scene Switcher"
NotifHintTransient = "int:transient:1"
KeyringAppName = "ha-switchscene"
)
var (
haUrl *string
scene *string
name *string
storeToken *bool
)
func init() {
storeToken = flag.Bool("storeToken", false, "store home assistant token")
haUrl = flag.String("url", "", "home assistant url")
scene = flag.String("scene", "", "scene to switch to")
name = flag.String("name", "scene", "name of scene to switch to")
flag.Parse()
}
func main() {
if *haUrl == "" {
_ = sendNotification("No Home Assistant URL given.", true)
os.Exit(1)
}
if *storeToken {
if err := readAndStoreToken(); err != nil {
fmt.Printf("Could not store token: %s", err)
}
return
}
token, err := keyring.Get(KeyringAppName, *haUrl)
if err != nil {
_ = sendNotification("Could not find credentials in keyring.", true)
fmt.Println(err)
os.Exit(1)
}
if *scene == "" {
_ = sendNotification("No scene given.", true)
os.Exit(1)
}
if err = switchScene(token, *scene); err != nil {
_ = sendNotification("Could not switch scene.", true)
fmt.Println(err)
os.Exit(1)
}
_ = sendNotification(fmt.Sprintf("Switched scene to %s.", *name), false)
}
func readAndStoreToken() error {
fmt.Print("Enter Home Assistant token: ")
bytepw, err := terminal.ReadPassword(syscall.Stdin)
if err != nil {
return err
}
if err = keyring.Set(KeyringAppName, *haUrl, string(bytepw)); err != nil {
return err
}
fmt.Println("\nToken saved to keyring.")
return nil
}
func switchScene(token, scene string) error {
return callService(token, "scene", "turn_on",
map[string]interface{}{
"entity_id": scene,
},
)
}
func callService(token, domain, service string, data map[string]interface{}) error {
url := fmt.Sprintf("%s/api/services/%s/%s", *haUrl, domain, service)
body := new(bytes.Buffer)
if err := json.NewEncoder(body).Encode(data); err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if res.StatusCode >= 300 {
return fmt.Errorf("home assistant error response: %d", res.StatusCode)
}
return nil
}