-
Notifications
You must be signed in to change notification settings - Fork 0
/
heating_control.go
71 lines (58 loc) · 1.91 KB
/
heating_control.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
// heating_control.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// turnHeatingOn turns on the heating.
func (hm *HeatingManager) turnHeatingOn() error {
if err := hm.getAuthToken(); err != nil {
return fmt.Errorf("error getting auth token: %v", err)
}
url := fmt.Sprintf(hm.Config.HeatPumpControlURL, hm.Config.HeatPumpID)
requestBody, err := json.Marshal(map[string]interface{}{
"heatPumpChargingMode": 1,
})
if err != nil {
return fmt.Errorf("error marshalling request body: %v", err)
}
return hm.makeHeatingControlRequest(url, requestBody)
}
// turnHeatingOff turns off the heating.
func (hm *HeatingManager) turnHeatingOff() error {
if err := hm.getAuthToken(); err != nil {
return fmt.Errorf("error getting auth token: %v", err)
}
url := fmt.Sprintf(hm.Config.HeatPumpControlURL, hm.Config.HeatPumpID)
requestBody, err := json.Marshal(map[string]interface{}{
"heatPumpChargingMode": 2,
})
if err != nil {
return fmt.Errorf("error marshalling request body: %v", err)
}
return hm.makeHeatingControlRequest(url, requestBody)
}
// makeHeatingControlRequest makes a request to control the heating system.
func (hm *HeatingManager) makeHeatingControlRequest(url string, requestBody []byte) error {
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(requestBody))
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}
req.Header.Set("Authorization", "Bearer "+hm.Token)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("error executing request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("failed to modify heat pump state, status code: %d", resp.StatusCode)
}
if resp.StatusCode == http.StatusOK {
fmt.Println("Heat pump state changed successfully.")
}
return nil
}