This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
/
powersurge.go
74 lines (61 loc) · 1.61 KB
/
powersurge.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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
)
var (
strip = flag.String("strip", "10.1.1.213", "IP address of the power strip")
host = flag.String("host", "http://www.google.com", "Address of site to use to test connectivity")
socket = flag.Int("socket", 1, "Number of the socket the router is connected to")
password = flag.String("password", "1", "Password for power strip GUI")
interval = flag.String("interval", "10m", "Interval in which to run the test. Example: 10s, 5m, 1h")
cron = flag.Bool("cron", false, "Cron mode. Only tests once and exits.")
resetCount int
)
func TestConnection() bool {
log.Printf("Testing connection to %s..", *host)
_, err := http.Get(*host)
if err != nil {
log.Printf("Error: %v", err)
return false
}
return true
}
func RestartRouter() {
vals := []string{"0", "1"}
http.PostForm(fmt.Sprintf("http://%s/login.html", *strip),
url.Values{"pw": {*password}})
for _, i := range vals {
http.PostForm(fmt.Sprintf("http://%s/", *strip),
url.Values{fmt.Sprintf("cte%d", *socket): {i}})
time.Sleep(3 * time.Second)
}
log.Print("Router is powering back up.")
}
func main() {
flag.Parse()
if *cron {
if !TestConnection() {
RestartRouter()
}
os.Exit(0)
}
for {
if !TestConnection() {
log.Printf("Connection failed. Restarting router. (Incident #%d)", resetCount)
resetCount += 1
if resetCount >= 5 {
log.Fatalf("Something's wrong. Restarted too many times.")
}
RestartRouter()
}
log.Printf("Sleeping for %s..", *interval)
t, _ := time.ParseDuration(*interval)
time.Sleep(t)
}
}