-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
92 lines (78 loc) · 2.34 KB
/
Copy pathmain.go
File metadata and controls
92 lines (78 loc) · 2.34 KB
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
package main
import (
"crypto/tls"
"flag"
"fmt"
"net/http"
"os"
"time"
)
type Config struct {
check_interval time.Duration
check_url string
tasmota_ip string
log_success bool
}
func main() {
// Disable SSL verification for Docker
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
config := getConfig()
fmt.Println("Starting...")
fmt.Printf("Checking connection every: %s\n", config.check_interval.String())
fmt.Printf("Using following URL: %s\n", config.check_url)
fmt.Printf("Sending powercycle to: %s\n\n", config.tasmota_ip)
for {
ok, duration := checkConnection(config.check_url)
if ok && config.log_success {
fmt.Printf("%s Got valid response in %s\n", getTime(), duration)
} else if !ok {
fmt.Printf("%s Got invalid response in %s execute power-cycle\n", getTime(), duration)
doPowerCycle(config.tasmota_ip)
}
time.Sleep(config.check_interval)
}
}
func getConfig() (config Config) {
if os.Getenv("check_interval") != "" {
config.check_interval, _ = time.ParseDuration(os.Getenv("check_interval"))
} else {
flag.DurationVar(&config.check_interval, "check_interval", 1*time.Hour, "Interval to check connection")
}
if os.Getenv("check_url") != "" {
config.check_url = os.Getenv("check_url")
} else {
flag.StringVar(&config.check_url, "check_url", "http://google.com", "URL to check connection")
}
if os.Getenv("tasmota_ip") != "" {
config.tasmota_ip = os.Getenv("tasmota_ip")
} else {
flag.StringVar(&config.tasmota_ip, "tasmota_ip", "127.0.0.1", "URL to check connection")
}
if os.Getenv("log_success") != "" {
config.log_success = os.Getenv("log_success") == "true" || os.Getenv("log_success") == "1"
} else {
flag.BoolVar(&config.log_success, "log_success", false, "Log successful connections")
}
flag.Parse()
return config
}
func getTime() (dt string) {
t := time.Now()
return t.Format(time.RFC1123)
}
func checkConnection(url string) (ok bool, duration time.Duration) {
t := time.Now()
_, err := http.Get(url)
if err != nil {
fmt.Println(err)
return false, time.Since(t)
}
return true, time.Since(t)
}
func doPowerCycle(tasmotaIp string) {
fmt.Println("Power off")
http.Get("http://" + tasmotaIp + "/cm?cmnd=Power%20Off")
time.Sleep(5 * time.Second)
fmt.Println("Power on")
http.Get("http://" + tasmotaIp + "/cm?cmnd=Power%20On")
}