/
api.go
93 lines (73 loc) · 1.94 KB
/
api.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
package mercedes
import (
"fmt"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"golang.org/x/oauth2"
)
const (
// BaseURI is the Mercedes api base URI
BaseURI = "https://api.mercedes-benz.com/vehicledata/v2"
SandboxBaseURI = "https://api.mercedes-benz.com/vehicledata_tryout/v2"
)
// API is the Mercedes api client
type API struct {
*request.Helper
sandbox bool
}
// NewAPI creates a new api client
func NewAPI(log *util.Logger, identity *Identity, sandbox bool) *API {
v := &API{
Helper: request.NewHelper(log),
}
// replace client transport with authenticated transport
v.Client.Transport = &oauth2.Transport{
Source: identity,
Base: v.Client.Transport,
}
return v
}
func (v *API) BaseURI() string {
if v.sandbox {
return SandboxBaseURI
}
return BaseURI
}
// Soc implements the /soc response
func (v *API) Soc(vin string) (EVResponse, error) {
var res EVResponse
uri := fmt.Sprintf("%s/vehicles/%s/resources/soc", v.BaseURI(), vin)
err := v.GetJSON(uri, &res)
if err != nil {
res, err = v.allinOne(vin)
}
return res, err
}
// Range implements the /rangeelectric response
func (v *API) Range(vin string) (EVResponse, error) {
var res EVResponse
uri := fmt.Sprintf("%s/vehicles/%s/resources/rangeelectric", v.BaseURI(), vin)
err := v.GetJSON(uri, &res)
if err != nil {
res, err = v.allinOne(vin)
}
return res, err
}
// allinOne is a 'fallback' to gather both metrics range and soc.
// It is used in case for any reason the single endpoints return an error - which happend in the past.
func (v *API) allinOne(vin string) (EVResponse, error) {
var res []EVResponse
uri := fmt.Sprintf("%s/vehicles/%s/containers/electricvehicle", v.BaseURI(), vin)
err := v.GetJSON(uri, &res)
evres := EVResponse{}
for _, r := range res {
if r.Soc.Timestamp != 0 {
evres.Soc = r.Soc
continue
}
if r.RangeElectric.Timestamp != 0 {
evres.RangeElectric = r.RangeElectric
}
}
return evres, err
}