/
maintenance.go
84 lines (78 loc) · 2.27 KB
/
maintenance.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
package client
import (
"context"
"net/http"
"github.com/plgd-dev/cloud/grpc-gateway/pb"
"github.com/plgd-dev/sdk/schema/maintenance"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Reboot makes reboot on device. JWT token must be stored in context for grpc call.
func (c *Client) Reboot(
ctx context.Context,
deviceID string,
) error {
return c.updateMaintenanceResource(ctx, deviceID, maintenance.MaintenanceUpdateRequest{
Reboot: true,
})
}
// FactoryReset makes factory reset on device. JWT token must be stored in context for grpc call.
func (c *Client) FactoryReset(
ctx context.Context,
deviceID string,
) error {
return c.updateMaintenanceResource(ctx, deviceID, maintenance.MaintenanceUpdateRequest{
FactoryReset: true,
})
}
//https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
func httpCoreToGrpc(statusCode int) codes.Code {
switch statusCode {
case http.StatusBadRequest:
return codes.Internal
case http.StatusUnauthorized:
return codes.Unauthenticated
case http.StatusForbidden:
return codes.PermissionDenied
case http.StatusNotFound:
return codes.Unimplemented
case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
return codes.Unavailable
}
return codes.Unknown
}
func (c *Client) updateMaintenanceResource(
ctx context.Context,
deviceID string,
req maintenance.MaintenanceUpdateRequest,
) (ret error) {
it := c.GetResourceLinksIterator(ctx, []string{deviceID}, maintenance.MaintenanceResourceType)
defer it.Close()
var found bool
for {
var v pb.ResourceLink
if !it.Next(&v) {
break
}
found = true
var resp maintenance.Maintenance
err := c.UpdateResource(ctx, v.GetDeviceId(), v.GetHref(), req, &resp)
if err != nil {
return err
}
if resp.LastHTTPError >= http.StatusBadRequest {
defer func() {
if r := recover(); r != nil {
ret = status.Errorf(httpCoreToGrpc(resp.LastHTTPError), "returns HTTP code %v", resp.LastHTTPError)
}
}()
str := http.StatusText(resp.LastHTTPError)
return status.Errorf(httpCoreToGrpc(resp.LastHTTPError), str)
}
return it.Err
}
if !found {
return status.Errorf(codes.NotFound, "cannot find maintenance resource(%v)", maintenance.MaintenanceResourceType)
}
return it.Err
}