-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
52 lines (42 loc) · 1.02 KB
/
client.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
package zeversolar
import (
"context"
"fmt"
"io"
"net/http"
)
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
// address of inverter web interface
Address string
// client to use for requests
Client Doer
}
func (c *Client) getClient() Doer {
if c.Client == nil {
return http.DefaultClient
}
return c.Client
}
func (c *Client) GetInverterData(ctx context.Context) (*InverterData, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.Address+"/home.cgi", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %s", err)
}
res, err := c.getClient().Do(req)
if err != nil {
return nil, fmt.Errorf("failed to get response: %s", err)
}
defer res.Body.Close()
raw, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %s", err)
}
var point InverterData
if err := point.UnmarshalBinary(raw); err != nil {
return nil, fmt.Errorf("failed to unmarshal point: %s", err)
}
return &point, nil
}