-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
206 lines (190 loc) · 5.38 KB
/
main.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
// powerwall-cmd is a simple command-line utility which uses the powerwall
// module to access the Tesla Powerwall API.
//
// This is mainly intended as a simple way to test the library functions and as an example of use.
package main
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"strings"
"time"
"github.com/jessevdk/go-flags"
"github.com/foogod/go-powerwall"
)
var options struct {
Debug bool `long:"debug" description:"Enable debug messages"`
Address string `long:"address" required:"true" description:"IP address or hostname of Powerwall gateway (required)"`
Email string `long:"email" description:"Email address to use when logging in"`
Password string `long:"password" description:"Password to use when logging in"`
AuthCache string `long:"authcache" description:"Filename to store/load auth token"`
CertFile string `long:"certfile" description:"Filename of TLS certificate to use for validation"`
RetryTimeout time.Duration `long:"retry-timeout" description:"How long to keep trying to reach the gateway before giving up (default: no retries)"`
RetryInterval time.Duration `long:"retry-interval" description:"How long to wait between retries" default:"1s"`
Args struct {
Command string `positional-arg-name:"command" description:"One of 'status', 'login', 'site_info', 'fetchcert', 'aggregates', 'meters', 'system_status', 'grid_faults', 'grid_status', 'soe', 'operation', 'sitemaster', 'networks'"`
Args []string `positional-arg-name:"args" description:"Optional arguments depending on command"`
} `positional-args:"true" required:"true"`
}
func logDebug(v ...interface{}) {
log.Debug(v...)
}
func logError(msg string, err error) {
log.WithFields(log.Fields{"err": err}).Error(msg)
}
func main() {
var err error
_, err = flags.Parse(&options)
if err != nil {
os.Exit(1)
}
if options.Debug {
log.SetLevel(log.DebugLevel)
}
powerwall.SetLogFunc(logDebug)
powerwall.SetErrFunc(logError)
c := powerwall.NewClient(options.Address, options.Email, options.Password)
c.SetRetry(options.RetryInterval, options.RetryTimeout)
if options.CertFile != "" && options.Args.Command != "fetchcert" {
pemCert, err := ioutil.ReadFile(options.CertFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot read cert file: %s\n", err)
os.Exit(2)
}
block, _ := pem.Decode(pemCert)
if block == nil || block.Type != "CERTIFICATE" {
fmt.Fprintln(os.Stderr, "Unable to decode cert file. Is it in PEM format?")
os.Exit(2)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading cert file: %s\n", err)
os.Exit(2)
}
c.SetTLSCert(cert)
}
authToken := ""
if options.AuthCache != "" {
authdata, err := ioutil.ReadFile(options.AuthCache)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// This is ok
} else {
fmt.Fprintf(os.Stderr, "Cannot read authcache file: %s\n", err)
os.Exit(2)
}
}
authToken = strings.TrimSpace(string(authdata))
c.SetAuthToken(authToken)
}
switch options.Args.Command {
case "fetchcert":
cert, err := c.FetchTLSCert()
if err != nil {
panic(err)
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
err = ioutil.WriteFile(options.CertFile, pemCert, 0644)
if err != nil {
panic(err)
}
case "status":
result, err := c.GetStatus()
if err != nil {
panic(err)
}
writeResult(result)
case "login":
err := c.DoLogin()
if err != nil {
panic(err)
}
// If there's no authcache file, just print the auth token to stdout
if options.AuthCache == "" {
fmt.Println(c.GetAuthToken())
}
case "site_info":
result, err := c.GetSiteInfo()
if err != nil {
panic(err)
}
writeResult(result)
case "aggregates":
result, err := c.GetMetersAggregates()
if err != nil {
panic(err)
}
writeResult(result)
case "meters":
result, err := c.GetMeters(options.Args.Args[0])
if err != nil {
panic(err)
}
writeResult(result)
case "system_status":
result, err := c.GetSystemStatus()
if err != nil {
panic(err)
}
writeResult(result)
case "grid_faults":
result, err := c.GetGridFaults()
if err != nil {
panic(err)
}
writeResult(result)
case "grid_status":
result, err := c.GetGridStatus()
if err != nil {
panic(err)
}
writeResult(result)
case "soe":
result, err := c.GetSOE()
if err != nil {
panic(err)
}
writeResult(result)
case "operation":
result, err := c.GetOperation()
if err != nil {
panic(err)
}
writeResult(result)
case "sitemaster":
result, err := c.GetSitemaster()
if err != nil {
panic(err)
}
writeResult(result)
case "networks":
result, err := c.GetNetworks()
if err != nil {
panic(err)
}
writeResult(result)
default:
fmt.Fprintf(os.Stderr, "Error: Unknown command: %v\n", options.Args.Command)
os.Exit(3)
}
newAuthToken := c.GetAuthToken()
if newAuthToken != authToken && options.AuthCache != "" {
// Auth token has changed. Write it out to the cache file.
err := os.WriteFile(options.AuthCache, []byte(newAuthToken), 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: Cannot write to authcache file: %s\n", err)
}
}
}
func writeResult(value interface{}) {
b, err := json.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
}