-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheating_manager.go
237 lines (202 loc) · 7.18 KB
/
heating_manager.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
// Config represents the application configuration.
type Config struct {
ShellyURL string `json:"shellyTempURL"` // URL of the Shelly device temperature addon.
ShellyHeatingOnURL string `json:"shellyHeatingOnURL"` // URL to turn Shelly heating on.
ShellyHeatingOffURL string `json:"shellyHeatingOffURL"` // URL to turn Shelly heating off.
TemperatureThreshold float64 `json:"temperatureThreshold"` // Temperature threshold in Celsius.
TemperatureTurnOff float64 `json:"temperatureTurnOff"` // Temperature at which to turn off the heating.
CheckInterval int `json:"checkInterval"` // Check interval in minutes.
WeeklyCheckInterval int `json:"weeklyCheckInterval"` // Weekly check interval in hours.
}
// HeatingManager is the main application struct.
type HeatingManager struct {
Config Config // Configuration.
TemperatureExceeded bool // Indicates if the temperature threshold has been exceeded.
CheckInterval time.Duration // Interval between temperature checks.
LastCheckFile string // File to save and read the last check time.
}
type TempResponse struct {
ID int `json:"id"`
TC float64 `json:"tC"`
TF float64 `json:"tF"`
}
// NewHeatingManager creates a new HeatingManager instance.
func NewHeatingManager() (*HeatingManager, error) {
config, err := loadConfig()
if err != nil {
return nil, err
}
return &HeatingManager{
Config: config,
CheckInterval: time.Duration(config.CheckInterval) * time.Minute,
LastCheckFile: "lastCheck.txt",
}, nil
}
// StartTemperatureMonitoring starts the temperature monitoring loop.
func (hm *HeatingManager) StartTemperatureMonitoring() {
ticker := time.NewTicker(hm.CheckInterval)
defer ticker.Stop()
for range ticker.C {
hm.checkTemperature(hm.Config.ShellyURL)
}
}
// StartWeeklyCheck starts the weekly check loop.
func (hm *HeatingManager) StartWeeklyCheck() {
weeklyCheckTimer := time.NewTimer(hm.nextWeeklyCheckDuration())
defer weeklyCheckTimer.Stop()
for range weeklyCheckTimer.C {
hm.weeklyCheck(hm.Config.ShellyHeatingOnURL, hm.Config.ShellyHeatingOffURL)
weeklyCheckTimer.Reset(hm.nextWeeklyCheckDuration())
}
}
// loadConfig loads the application configuration from a JSON file.
func loadConfig() (Config, error) {
var config Config
configFile, err := os.Open("config.json")
if err != nil {
return config, fmt.Errorf("failed to open config file: %v", err)
}
defer configFile.Close()
err = json.NewDecoder(configFile).Decode(&config)
if err != nil {
return config, fmt.Errorf("failed to parse config file: %v", err)
}
return config, nil
}
// checkTemperature checks the temperature of a Shelly device.
func (hm *HeatingManager) checkTemperature(shellyURL string) {
temperature, err := getTemperature(shellyURL)
if err != nil {
log.Printf("Failed to get temperature: %v", err)
return
}
if temperature > hm.Config.TemperatureThreshold {
fmt.Printf("Temperature has exceeded %.1f°C! Legionella heating will be rescheduled.\n", hm.Config.TemperatureThreshold)
hm.TemperatureExceeded = true
} else {
fmt.Printf("Temperature is OK. Actual temperature: %.1f°C\n", temperature)
}
}
// getTemperature gets the temperature of a Shelly device.
func getTemperature(shellyTempURL string) (float64, error) {
resp, err := http.Get(shellyTempURL)
if err != nil {
return 0, fmt.Errorf("failed to get temperature: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("failed to get temperature: status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, fmt.Errorf("failed to read response body: %v", err)
}
var tempResponse TempResponse
if err := json.Unmarshal(body, &tempResponse); err != nil {
return 0, fmt.Errorf("failed to unmarshal temperature response: %v", err)
}
return tempResponse.TC, nil
}
// weeklyCheck checks if the temperature threshold has been exceeded and turns on the Shelly heating if necessary.
func (hm *HeatingManager) weeklyCheck(shellyHeatingOnURL string, shellyHeatingOffURL string) {
if !hm.TemperatureExceeded {
if err := hm.turnShellyOn(shellyHeatingOnURL, shellyHeatingOffURL); err != nil {
log.Printf("Failed to turn on Shelly: %v", err)
}
}
hm.TemperatureExceeded = false
hm.saveLastCheckTime()
}
// turnShellyOn turns on the Shelly heating, schedules it to turn off after 4 hours, and checks if the temperature exceeds 60°C.
func (hm *HeatingManager) turnShellyOn(shellyHeatingOnURL, shellyHeatingOffURL string) error {
resp, err := http.Get(shellyHeatingOnURL)
if err != nil {
return fmt.Errorf("failed to turn on Shelly: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to turn on Shelly: status code %d", resp.StatusCode)
}
fmt.Println("Shelly turned on.")
// Schedule to turn off after 4 hours
offTimer := time.AfterFunc(4*time.Hour, func() {
if err := hm.turnShellyOff(shellyHeatingOffURL); err != nil {
log.Printf("Failed to turn off Shelly: %v", err)
}
fmt.Println("Shelly turned off.")
hm.TemperatureExceeded = false
})
// Check temperature every minute to see if it exceeds 60°C
checkTimer := time.NewTicker(5 * time.Minute)
go func() {
for range checkTimer.C {
temp, err := getTemperature(hm.Config.ShellyURL)
if err != nil {
log.Printf("Error checking temperature: %v", err)
continue
}
if temp > hm.Config.TemperatureTurnOff {
fmt.Println("Temperature exceeded. Turning off Shelly.")
checkTimer.Stop()
offTimer.Stop()
hm.TemperatureExceeded = false
}
}
}()
return nil
}
// turnShellyOff turns off the Shelly heating.
func (hm *HeatingManager) turnShellyOff(shellyHeatingOffURL string) error {
resp, err := http.Get(shellyHeatingOffURL)
if err != nil {
return fmt.Errorf("failed to turn off Shelly: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to turn off Shelly: status code %d", resp.StatusCode)
}
fmt.Println("Shelly turned off.")
return nil
}
// saveLastCheckTime saves the last check time to a file.
func (hm *HeatingManager) saveLastCheckTime() {
now := time.Now()
err := os.WriteFile(hm.LastCheckFile, []byte(now.Format(time.RFC3339)), 0644)
if err != nil {
log.Printf("Failed to save last check time: %v", err)
}
}
// nextWeeklyCheckDuration calculates the duration until the next weekly check.
func (hm *HeatingManager) nextWeeklyCheckDuration() time.Duration {
lastCheck, err := hm.readLastCheckTime()
if err != nil {
return 0
}
nextCheck := lastCheck.Add(time.Duration(hm.Config.WeeklyCheckInterval) * time.Hour)
if time.Now().After(nextCheck) {
return 0
}
return time.Until(nextCheck)
}
// readLastCheckTime reads the last check time from a file.
func (hm *HeatingManager) readLastCheckTime() (time.Time, error) {
data, err := os.ReadFile(hm.LastCheckFile)
if err != nil {
return time.Time{}, fmt.Errorf("failed to read last check time: %w", err)
}
lastCheck, err := time.Parse(time.RFC3339, string(data))
if err != nil {
return time.Time{}, fmt.Errorf("failed to parse last check time: %w", err)
}
return lastCheck, nil
}