forked from brocaar/chirpstack-application-server
/
device_profile.go
373 lines (326 loc) · 12.7 KB
/
device_profile.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package external
import (
"database/sql"
"time"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/empty"
"github.com/lib/pq/hstore"
"github.com/brocaar/chirpstack-api/go/v3/ns"
"github.com/jmoiron/sqlx"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
pb "github.com/brocaar/chirpstack-api/go/v3/as/external/api"
"github.com/kamicuu/chirpstack-application-server/internal/api/external/auth"
"github.com/kamicuu/chirpstack-application-server/internal/api/helpers"
"github.com/kamicuu/chirpstack-application-server/internal/codec"
"github.com/kamicuu/chirpstack-application-server/internal/storage"
)
// DeviceProfileServiceAPI exports the ServiceProfile related functions.
type DeviceProfileServiceAPI struct {
validator auth.Validator
}
// NewDeviceProfileServiceAPI creates a new DeviceProfileServiceAPI.
func NewDeviceProfileServiceAPI(validator auth.Validator) *DeviceProfileServiceAPI {
return &DeviceProfileServiceAPI{
validator: validator,
}
}
// Create creates the given device-profile.
func (a *DeviceProfileServiceAPI) Create(ctx context.Context, req *pb.CreateDeviceProfileRequest) (*pb.CreateDeviceProfileResponse, error) {
if req.DeviceProfile == nil {
return nil, grpc.Errorf(codes.InvalidArgument, "deviceProfile expected")
}
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfilesAccess(auth.Create, req.DeviceProfile.OrganizationId, 0),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
var err error
var uplinkInterval time.Duration
if req.DeviceProfile.UplinkInterval != nil {
uplinkInterval, err = ptypes.Duration(req.DeviceProfile.UplinkInterval)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
}
dp := storage.DeviceProfile{
OrganizationID: req.DeviceProfile.OrganizationId,
NetworkServerID: req.DeviceProfile.NetworkServerId,
Name: req.DeviceProfile.Name,
PayloadCodec: codec.Type(req.DeviceProfile.PayloadCodec),
PayloadEncoderScript: req.DeviceProfile.PayloadEncoderScript,
PayloadDecoderScript: req.DeviceProfile.PayloadDecoderScript,
Tags: hstore.Hstore{
Map: make(map[string]sql.NullString),
},
UplinkInterval: uplinkInterval,
DeviceProfile: ns.DeviceProfile{
SupportsClassB: req.DeviceProfile.SupportsClassB,
ClassBTimeout: req.DeviceProfile.ClassBTimeout,
PingSlotPeriod: req.DeviceProfile.PingSlotPeriod,
PingSlotDr: req.DeviceProfile.PingSlotDr,
PingSlotFreq: req.DeviceProfile.PingSlotFreq,
SupportsClassC: req.DeviceProfile.SupportsClassC,
ClassCTimeout: req.DeviceProfile.ClassCTimeout,
MacVersion: req.DeviceProfile.MacVersion,
RegParamsRevision: req.DeviceProfile.RegParamsRevision,
RxDelay_1: req.DeviceProfile.RxDelay_1,
RxDrOffset_1: req.DeviceProfile.RxDrOffset_1,
RxDatarate_2: req.DeviceProfile.RxDatarate_2,
RxFreq_2: req.DeviceProfile.RxFreq_2,
MaxEirp: req.DeviceProfile.MaxEirp,
MaxDutyCycle: req.DeviceProfile.MaxDutyCycle,
SupportsJoin: req.DeviceProfile.SupportsJoin,
RfRegion: req.DeviceProfile.RfRegion,
Supports_32BitFCnt: req.DeviceProfile.Supports_32BitFCnt,
FactoryPresetFreqs: req.DeviceProfile.FactoryPresetFreqs,
AdrAlgorithmId: req.DeviceProfile.AdrAlgorithmId,
},
}
for k, v := range req.DeviceProfile.Tags {
dp.Tags.Map[k] = sql.NullString{Valid: true, String: v}
}
// as this also performs a remote call to create the device-profile
// on the network-server, wrap it in a transaction
err = storage.Transaction(func(tx sqlx.Ext) error {
return storage.CreateDeviceProfile(ctx, tx, &dp)
})
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
dpID, err := uuid.FromBytes(dp.DeviceProfile.Id)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
return &pb.CreateDeviceProfileResponse{
Id: dpID.String(),
}, nil
}
// Get returns the device-profile matching the given id.
func (a *DeviceProfileServiceAPI) Get(ctx context.Context, req *pb.GetDeviceProfileRequest) (*pb.GetDeviceProfileResponse, error) {
dpID, err := uuid.FromString(req.Id)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, "uuid error: %s", err)
}
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfileAccess(auth.Read, dpID),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
dp, err := storage.GetDeviceProfile(ctx, storage.DB(), dpID, false, false)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
resp := pb.GetDeviceProfileResponse{
DeviceProfile: &pb.DeviceProfile{
Id: dpID.String(),
Name: dp.Name,
OrganizationId: dp.OrganizationID,
NetworkServerId: dp.NetworkServerID,
PayloadCodec: string(dp.PayloadCodec),
PayloadEncoderScript: dp.PayloadEncoderScript,
PayloadDecoderScript: dp.PayloadDecoderScript,
SupportsClassB: dp.DeviceProfile.SupportsClassB,
ClassBTimeout: dp.DeviceProfile.ClassBTimeout,
PingSlotPeriod: dp.DeviceProfile.PingSlotPeriod,
PingSlotDr: dp.DeviceProfile.PingSlotDr,
PingSlotFreq: dp.DeviceProfile.PingSlotFreq,
SupportsClassC: dp.DeviceProfile.SupportsClassC,
ClassCTimeout: dp.DeviceProfile.ClassCTimeout,
MacVersion: dp.DeviceProfile.MacVersion,
RegParamsRevision: dp.DeviceProfile.RegParamsRevision,
RxDelay_1: dp.DeviceProfile.RxDelay_1,
RxDrOffset_1: dp.DeviceProfile.RxDrOffset_1,
RxDatarate_2: dp.DeviceProfile.RxDatarate_2,
RxFreq_2: dp.DeviceProfile.RxFreq_2,
MaxEirp: dp.DeviceProfile.MaxEirp,
MaxDutyCycle: dp.DeviceProfile.MaxDutyCycle,
SupportsJoin: dp.DeviceProfile.SupportsJoin,
RfRegion: dp.DeviceProfile.RfRegion,
Supports_32BitFCnt: dp.DeviceProfile.Supports_32BitFCnt,
FactoryPresetFreqs: dp.DeviceProfile.FactoryPresetFreqs,
Tags: make(map[string]string),
UplinkInterval: ptypes.DurationProto(dp.UplinkInterval),
AdrAlgorithmId: dp.DeviceProfile.AdrAlgorithmId,
},
}
resp.CreatedAt, err = ptypes.TimestampProto(dp.CreatedAt)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
resp.UpdatedAt, err = ptypes.TimestampProto(dp.UpdatedAt)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
for k, v := range dp.Tags.Map {
resp.DeviceProfile.Tags[k] = v.String
}
return &resp, nil
}
// Update updates the given device-profile.
func (a *DeviceProfileServiceAPI) Update(ctx context.Context, req *pb.UpdateDeviceProfileRequest) (*empty.Empty, error) {
if req.DeviceProfile == nil {
return nil, grpc.Errorf(codes.InvalidArgument, "deviceProfile expected")
}
dpID, err := uuid.FromString(req.DeviceProfile.Id)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, "uuid error: %s", err)
}
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfileAccess(auth.Update, dpID),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
// As this also performs a remote call to update the device-profile
// on the network-server, wrap it in a transaction.
// This also locks the local device-profile record in the database.
err = storage.Transaction(func(tx sqlx.Ext) error {
dp, err := storage.GetDeviceProfile(ctx, tx, dpID, true, false)
if err != nil {
return err
}
var uplinkInterval time.Duration
if req.DeviceProfile.UplinkInterval != nil {
uplinkInterval, err = ptypes.Duration(req.DeviceProfile.UplinkInterval)
if err != nil {
return err
}
}
dp.Name = req.DeviceProfile.Name
dp.PayloadCodec = codec.Type(req.DeviceProfile.PayloadCodec)
dp.PayloadEncoderScript = req.DeviceProfile.PayloadEncoderScript
dp.PayloadDecoderScript = req.DeviceProfile.PayloadDecoderScript
dp.Tags = hstore.Hstore{
Map: make(map[string]sql.NullString),
}
dp.UplinkInterval = uplinkInterval
dp.DeviceProfile = ns.DeviceProfile{
Id: dpID.Bytes(),
SupportsClassB: req.DeviceProfile.SupportsClassB,
ClassBTimeout: req.DeviceProfile.ClassBTimeout,
PingSlotPeriod: req.DeviceProfile.PingSlotPeriod,
PingSlotDr: req.DeviceProfile.PingSlotDr,
PingSlotFreq: req.DeviceProfile.PingSlotFreq,
SupportsClassC: req.DeviceProfile.SupportsClassC,
ClassCTimeout: req.DeviceProfile.ClassCTimeout,
MacVersion: req.DeviceProfile.MacVersion,
RegParamsRevision: req.DeviceProfile.RegParamsRevision,
RxDelay_1: req.DeviceProfile.RxDelay_1,
RxDrOffset_1: req.DeviceProfile.RxDrOffset_1,
RxDatarate_2: req.DeviceProfile.RxDatarate_2,
RxFreq_2: req.DeviceProfile.RxFreq_2,
MaxEirp: req.DeviceProfile.MaxEirp,
MaxDutyCycle: req.DeviceProfile.MaxDutyCycle,
SupportsJoin: req.DeviceProfile.SupportsJoin,
RfRegion: req.DeviceProfile.RfRegion,
Supports_32BitFCnt: req.DeviceProfile.Supports_32BitFCnt,
FactoryPresetFreqs: req.DeviceProfile.FactoryPresetFreqs,
AdrAlgorithmId: req.DeviceProfile.AdrAlgorithmId,
}
for k, v := range req.DeviceProfile.Tags {
dp.Tags.Map[k] = sql.NullString{Valid: true, String: v}
}
return storage.UpdateDeviceProfile(ctx, tx, &dp)
})
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
return &empty.Empty{}, nil
}
// Delete deletes the device-profile matching the given id.
func (a *DeviceProfileServiceAPI) Delete(ctx context.Context, req *pb.DeleteDeviceProfileRequest) (*empty.Empty, error) {
dpID, err := uuid.FromString(req.Id)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, "uuid error: %s", err)
}
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfileAccess(auth.Delete, dpID),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
// as this also performs a remote call to delete the device-profile
// on the network-server, wrap it in a transaction
err = storage.Transaction(func(tx sqlx.Ext) error {
return storage.DeleteDeviceProfile(ctx, tx, dpID)
})
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
return &empty.Empty{}, nil
}
// List lists the available device-profiles.
func (a *DeviceProfileServiceAPI) List(ctx context.Context, req *pb.ListDeviceProfileRequest) (*pb.ListDeviceProfileResponse, error) {
if req.ApplicationId != 0 {
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfilesAccess(auth.List, 0, req.ApplicationId),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
} else {
if err := a.validator.Validate(ctx,
auth.ValidateDeviceProfilesAccess(auth.List, req.OrganizationId, 0),
); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
}
filters := storage.DeviceProfileFilters{
Limit: int(req.Limit),
Offset: int(req.Offset),
OrganizationID: req.OrganizationId,
ApplicationID: req.ApplicationId,
}
sub, err := a.validator.GetSubject(ctx)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
switch sub {
case auth.SubjectUser:
user, err := a.validator.GetUser(ctx)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
// Filter on user ID when org and app ID are not set and user is not
// global admin.
if !user.IsAdmin && filters.OrganizationID == 0 && filters.ApplicationID == 0 {
filters.UserID = user.ID
}
case auth.SubjectAPIKey:
// Nothing to do as the validator function already validated that the
// API key is either of type admin, org (for the req.OrganizationId) or
// app (for the req.ApplicationId).
default:
return nil, grpc.Errorf(codes.Unauthenticated, "invalid token subject: %s", sub)
}
count, err := storage.GetDeviceProfileCount(ctx, storage.DB(), filters)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
dps, err := storage.GetDeviceProfiles(ctx, storage.DB(), filters)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
resp := pb.ListDeviceProfileResponse{
TotalCount: int64(count),
}
for _, dp := range dps {
row := pb.DeviceProfileListItem{
Id: dp.DeviceProfileID.String(),
Name: dp.Name,
OrganizationId: dp.OrganizationID,
NetworkServerId: dp.NetworkServerID,
NetworkServerName: dp.NetworkServerName,
}
row.CreatedAt, err = ptypes.TimestampProto(dp.CreatedAt)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
row.UpdatedAt, err = ptypes.TimestampProto(dp.UpdatedAt)
if err != nil {
return nil, helpers.ErrToRPCError(err)
}
resp.Result = append(resp.Result, &row)
}
return &resp, nil
}