-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
165 lines (145 loc) · 4.38 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
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
package airthings
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"golang.org/x/oauth2/clientcredentials"
)
type Client struct {
Endpoint string
http *http.Client
conf *clientcredentials.Config
}
func Authorize(ctx context.Context, clientId, clientSecret string, scopes []string) (*Client, error) {
if scopes == nil {
scopes = []string{"read:device:current_values"}
}
conf := &clientcredentials.Config{
ClientID: clientId,
ClientSecret: clientSecret,
Scopes: scopes,
TokenURL: "https://accounts-api.airthings.com/v1/token",
}
httpClient := conf.Client(ctx)
return &Client{Endpoint: "https://ext-api.airthings.com/", http: httpClient, conf: conf}, nil
}
type Authentication struct {
GrantType string `json:"grant_type"`
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Code string `json:"code"`
RedirectUri string `json:"redirect_uri"`
RefreshToken string `json:"refresh_token"`
Scope []string `json:"scope"`
}
type ListDevicesOptions struct {
ShowInactive bool
OrganizationId string
UserGroupId string
}
// ListDevices get devices belonging to the account
func (c *Client) ListDevices(opts ListDevicesOptions) ([]Device, error) {
var query []string
if opts.ShowInactive {
query = append(query, "showInactive=true")
}
if opts.OrganizationId != "" {
query = append(query, fmt.Sprintf("organizationId=%s", url.QueryEscape(opts.OrganizationId)))
}
if opts.UserGroupId != "" {
query = append(query, fmt.Sprintf("userGroupId=%s", url.QueryEscape(opts.UserGroupId)))
}
var response struct {
Devices []Device `json:"devices"`
}
err := c.get("/v1/devices?"+strings.Join(query, "&"), &response)
return response.Devices, err
}
type GetDeviceOptions struct {
SerialNumber string
OrganizationId string
UserGroupId string
}
var ErrNoSerialNumber = errors.New("missing serial number")
// GetDevice returns information about a particular device
func (c *Client) GetDevice(opts GetDeviceOptions) (Device, error) {
if opts.SerialNumber == "" {
return Device{}, ErrNoSerialNumber
}
var query []string
if opts.OrganizationId != "" {
query = append(query, fmt.Sprintf("organizationId=%s", url.QueryEscape(opts.OrganizationId)))
}
if opts.UserGroupId != "" {
query = append(query, fmt.Sprintf("userGroupId=%s", url.QueryEscape(opts.UserGroupId)))
}
var device Device
err := c.get(fmt.Sprintf("/v1/devices/%s?%s", opts.SerialNumber, strings.Join(query, "&")), &device)
return device, err
}
type GetLatestSamplesOptions struct {
SerialNumber string // required
OrganizationId string
UserGroupId string
}
func (c *Client) GetLatestSamples(opts GetLatestSamplesOptions) (map[SensorType]interface{}, error) {
if opts.SerialNumber == "" {
return nil, ErrNoSerialNumber
}
var query []string
if opts.OrganizationId != "" {
query = append(query, fmt.Sprintf("organizationId=%s", url.QueryEscape(opts.OrganizationId)))
}
if opts.UserGroupId != "" {
query = append(query, fmt.Sprintf("userGroupId=%s", url.QueryEscape(opts.UserGroupId)))
}
var response struct {
Data map[SensorType]interface{} `json:"data"`
}
err := c.get(fmt.Sprintf("/v1/devices/%s/latest-samples?%s", opts.SerialNumber, strings.Join(query, "&")), &response)
return response.Data, err
}
type Device struct {
SerialNumber string `json:"id"` // this is the serial number
DeviceType DeviceType `json:"deviceType"`
Sensors []SensorType `json:"sensors"`
Segment DeviceSegment `json:"segment"`
Location DeviceLocation `json:"location"`
}
type DeviceSegment struct {
Id string `json:"id"`
Name string `json:"name"`
StartedAt string `json:"started"`
Active bool `json:"active"`
}
type DeviceLocation struct {
Id string `json:"id"`
Name string `json:"name"`
}
func (c *Client) get(path string, output interface{}) error {
for attempts := 0; attempts < 3; attempts++ {
res, err := c.http.Get(c.Endpoint + path)
if err != nil {
return err
}
if res.StatusCode >= 500 {
res.Body.Close()
continue
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return fmt.Errorf("bad response: %d %s", res.StatusCode, res.Status)
}
buf, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read: %w", err)
}
return json.Unmarshal(buf, output)
}
return fmt.Errorf("failed after 3 attempts")
}