-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiota-device.go
326 lines (284 loc) · 7.52 KB
/
iota-device.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package iotagentsdk
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
u "net/url"
"github.com/niemeyer/golang/src/pkg/container/vector"
log "github.com/rs/zerolog/log"
)
// Constants
const (
urlDevice = urlBase + "/iot/devices"
)
// Request struct for creating a device
type reqCreateDevice struct {
Devices []Device `json:"devices"`
}
// Response struct for listing devices
type respListDevices struct {
Count int `json:"count"`
Devices []Device `json:"devices"`
}
// Function to validate a Device
func (d Device) Validate() error {
mF := &MissingFields{make(vector.StringVector, 0), "Missing fields"}
if d.Id == "" {
mF.Fields.Push("Id")
}
if mF.Fields.Len() == 0 {
return nil
} else {
return mF
}
}
// Method to read a device
func (i IoTA) ReadDevice(fs FiwareService, id DeciveId) (*Device, error) {
url, err := u.JoinPath(fmt.Sprintf(urlDevice, i.Host, i.Port), u.PathEscape(string(id)))
if err != nil {
return nil, err
}
method := "GET"
client := i.Client()
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
req.Header.Add("fiware-service", fs.Service)
req.Header.Add("fiware-servicepath", fs.ServicePath)
res, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
resData, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Error while eding response body %w", err)
}
var apiError ApiError
err = json.Unmarshal(resData, &apiError)
if err != nil {
log.Panic().Err(err).Msg("Could not Marshal struct")
}
return nil, apiError
}
responseData, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
var device Device
json.Unmarshal(responseData, &device)
if err != nil {
log.Panic().Err(err).Msg("Could not Marshal struct")
}
return &device, nil
}
// Method to check if a device exists
func (i IoTA) DeviceExists(fs FiwareService, id DeciveId) bool {
_, err := i.ReadDevice(fs, id)
if err != nil {
return false
}
return true
}
// Method to list devices
func (i IoTA) ListDevices(fs FiwareService) (*respListDevices, error) {
url := fmt.Sprintf(urlDevice, i.Host, i.Port)
method := "GET"
client := i.Client()
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
req.Header.Add("fiware-service", fs.Service)
req.Header.Add("fiware-servicepath", fs.ServicePath)
res, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
resData, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Error while eding response body %w", err)
}
var apiError ApiError
err = json.Unmarshal(resData, &apiError)
if err != nil {
log.Panic().Err(err).Msg("Could not Marshal struct")
}
return nil, apiError
}
responseData, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Error while getting service: %w", err)
}
var respDevices respListDevices
json.Unmarshal(responseData, &respDevices)
return &respDevices, nil
}
// Method to create a device
func (i IoTA) CreateDevices(fs FiwareService, ds []Device) error {
for _, sg := range ds {
err := sg.Validate()
if err != nil {
return err
}
}
rcd := reqCreateDevice{}
rcd.Devices = ds[:]
method := "POST"
payload, err := json.Marshal(rcd)
if err != nil {
log.Panic().Err(err).Msg("Could not Marshal struct")
}
client := i.Client()
req, err := http.NewRequest(method, fmt.Sprintf(urlDevice, i.Host, i.Port), bytes.NewBuffer(payload))
if err != nil {
return fmt.Errorf("Error while creating Request %w", err)
}
req.Header.Add("fiware-service", fs.Service)
req.Header.Add("fiware-servicepath", fs.ServicePath)
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("Error while requesting resource %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
resData, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Error while eding response body %w", err)
}
var apiError ApiError
json.Unmarshal(resData, &apiError)
return apiError
}
return nil
}
// Method to create a device
func (i IoTA) CreateDevice(fs FiwareService, d Device) error {
ds := [1]Device{d}
return i.CreateDevices(fs, ds[:])
}
// Method to update a device
func (i IoTA) UpdateDevice(fs FiwareService, d Device) error {
err := d.Validate()
if err != nil {
return err
}
url, err := u.JoinPath(fmt.Sprintf(urlDevice, i.Host, i.Port), u.PathEscape(string(d.Id)))
// Ensure these fields are not set
d.Id = ""
d.Transport = ""
d.Service = ""
d.ServicePath = ""
method := "PUT"
payload, err := json.Marshal(d)
if err != nil {
log.Panic().Err(err).Msg("Could not Marshal struct")
}
if string(payload) == "{}" {
return nil
}
client := i.Client()
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
return fmt.Errorf("Error while creating Request %w", err)
}
req.Header.Add("fiware-service", fs.Service)
req.Header.Add("fiware-servicepath", fs.ServicePath)
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("Error while requesting resource %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
resData, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Error while eding response body %w", err)
}
var apiError ApiError
json.Unmarshal(resData, &apiError)
return apiError
}
return nil
}
// Method to delete a device
func (i IoTA) DeleteDevice(fs FiwareService, id DeciveId) error {
url, err := u.JoinPath(fmt.Sprintf(urlDevice, i.Host, i.Port), u.PathEscape(string(id)))
if err != nil {
return err
}
method := "DELETE"
client := i.Client()
req, err := http.NewRequest(method, url, nil)
if err != nil {
return fmt.Errorf("Error while getting service: %w", err)
}
req.Header.Add("fiware-service", fs.Service)
req.Header.Add("fiware-servicepath", fs.ServicePath)
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("Error while getting service: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
resData, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Error while eding response body %w", err)
}
var apiError ApiError
json.Unmarshal(resData, &apiError)
return apiError
}
return nil
}
// Method to upsert a device
func (i IoTA) UpsertDevice(fs FiwareService, d Device) error {
exists := i.DeviceExists(fs, d.Id)
if !exists {
log.Debug().Msg("Creating device...")
err := i.CreateDevice(fs, d)
if err != nil {
return err
}
} else {
log.Debug().Msg("Update device...")
dTmp, err := i.ReadDevice(fs, d.Id)
if err != nil {
return err
}
if dTmp.EntityName == "" {
return errors.New("Error before getting updating device: No entity_name")
}
d.Transport = ""
d.EntityName = dTmp.EntityName
err = i.UpdateDevice(fs, d)
if err != nil {
return err
}
}
return nil
}
// Creates a device an updates the given Device
func (i IoTA) CreateDeviceWSE(fs FiwareService, d *Device) error {
if d == nil {
return errors.New("Device reference cannot be nil")
}
err := i.CreateDevice(fs, *d)
if err != nil {
return err
}
dTmp, err := i.ReadDevice(fs, d.Id)
if err != nil {
return err
}
*d = *dTmp
return nil
}