-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
124 lines (105 loc) · 2.54 KB
/
client.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
124
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
core "github.com/PhilGruber/dimmy/core"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
)
type listRequest struct {
Value float64 `json:"Value"`
Type string `json:"Type"`
Hidden bool `json:"Hidden"`
Target float64 `json:"Target"`
}
func loadClientConfig() (*string, *int) {
var filename string
var port = 8080
var host = "localhost"
if _, err := os.Stat("/etc/dimmy.conf"); err == nil {
filename = "/etc/dimmy.conf"
} else if _, err := os.Stat("dimmyd.conf"); err == nil {
filename = "dimmy.conf"
} else {
return &host, &port
}
file, err := os.Open(filename)
if err != nil {
return &host, &port
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Println("Error: " + err.Error())
}
}(file)
reader := bufio.NewReader(file)
var line string
for {
line, err = reader.ReadString('\n')
if err != nil {
break
}
line = strings.TrimSpace(line)
if strings.Contains(line, "=") {
kv := strings.Split(line, "=")
if kv[0] == "host" {
host = kv[1]
}
if kv[0] == "port" {
port, _ = strconv.Atoi(kv[1])
}
}
}
return &host, &port
}
func main() {
host, port := loadClientConfig()
host = flag.String("host", "", "hostname to connect to")
port = flag.Int("port", *port, "port to connect to")
value := flag.String("value", "100", "Value to send to device")
device := flag.String("device", "", "Device to send command to")
duration := flag.Int("duration", 0, "Duration of the dimming curve (seconds)")
list := flag.Bool("list", false, "List devices and their status")
flag.Parse()
request := core.SwitchRequest{
Device: *device,
Value: *value,
Duration: *duration,
}
jsonRequest, _ := json.Marshal(request)
url := fmt.Sprintf("http://%s:%d/api/", *host, *port)
if *list {
fmt.Println("Getting device list from " + url)
response, err := http.Get(url + "status")
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("Error: " + err.Error())
}
}(response.Body)
if err != nil {
log.Println("Error: " + err.Error())
}
body, err := io.ReadAll(response.Body)
var devices map[string]listRequest
err = json.Unmarshal(body, &devices)
if err != nil {
log.Fatal("Error: " + err.Error())
}
for name, device := range devices {
fmt.Printf("[%-10s] %-30s %5.1f\n", device.Type, name, device.Value)
}
}
_, err := http.Post(url+"switch", "application/json", bytes.NewBuffer(jsonRequest))
if err != nil {
log.Fatal("Error: " + err.Error())
}
}