/
gateway.go
617 lines (552 loc) · 13.5 KB
/
gateway.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
package storage
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"regexp"
"strconv"
"time"
"github.com/lib/pq"
"github.com/brocaar/lora-app-server/internal/config"
"github.com/brocaar/loraserver/api/ns"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/brocaar/lorawan"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
var gatewayNameRegexp = regexp.MustCompile(`^[\w-]+$`)
// Gateway represents a gateway.
type Gateway struct {
MAC lorawan.EUI64 `db:"mac"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
Name string `db:"name"`
Description string `db:"description"`
OrganizationID int64 `db:"organization_id"`
Ping bool `db:"ping"`
LastPingID *int64 `db:"last_ping_id"`
LastPingSentAt *time.Time `db:"last_ping_sent_at"`
NetworkServerID int64 `db:"network_server_id"`
GatewayProfileID *string `db:"gateway_profile_id"`
}
// GatewayPing represents a gateway ping.
type GatewayPing struct {
ID int64 `db:"id"`
CreatedAt time.Time `db:"created_at"`
GatewayMAC lorawan.EUI64 `db:"gateway_mac"`
Frequency int `db:"frequency"`
DR int `db:"dr"`
}
// GatewayPingRX represents a ping received by one of the gateways.
type GatewayPingRX struct {
ID int64 `db:"id"`
PingID int64 `db:"ping_id"`
CreatedAt time.Time `db:"created_at"`
GatewayMAC lorawan.EUI64 `db:"gateway_mac"`
ReceivedAt *time.Time `db:"received_at"`
RSSI int `db:"rssi"`
LoRaSNR float64 `db:"lora_snr"`
Location GPSPoint `db:"location"`
Altitude float64 `db:"altitude"`
}
// GPSPoint contains a GPS point.
type GPSPoint struct {
Latitude float64
Longitude float64
}
// Value implements the driver.Valuer interface.
func (l GPSPoint) Value() (driver.Value, error) {
return fmt.Sprintf("(%s,%s)", strconv.FormatFloat(l.Latitude, 'f', -1, 64), strconv.FormatFloat(l.Longitude, 'f', -1, 64)), nil
}
// Scan implements the sql.Scanner interface.
func (l *GPSPoint) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return fmt.Errorf("expected []byte, got %T", src)
}
_, err := fmt.Sscanf(string(b), "(%f,%f)", &l.Latitude, &l.Longitude)
return err
}
// Validate validates the gateway data.
func (g Gateway) Validate() error {
if !gatewayNameRegexp.MatchString(g.Name) {
return ErrGatewayInvalidName
}
return nil
}
// CreateGateway creates the given Gateway.
func CreateGateway(db sqlx.Execer, gw *Gateway) error {
if err := gw.Validate(); err != nil {
return errors.Wrap(err, "validate error")
}
now := time.Now()
gw.CreatedAt = now
gw.UpdatedAt = now
_, err := db.Exec(`
insert into gateway (
mac,
created_at,
updated_at,
name,
description,
organization_id,
ping,
last_ping_id,
last_ping_sent_at,
network_server_id,
gateway_profile_id
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
gw.MAC[:],
gw.CreatedAt,
gw.UpdatedAt,
gw.Name,
gw.Description,
gw.OrganizationID,
gw.Ping,
gw.LastPingID,
gw.LastPingSentAt,
gw.NetworkServerID,
gw.GatewayProfileID,
)
if err != nil {
return handlePSQLError(Insert, err, "insert error")
}
log.WithFields(log.Fields{
"mac": gw.MAC,
"name": gw.Name,
}).Info("gateway created")
return nil
}
// UpdateGateway updates the given Gateway.
func UpdateGateway(db sqlx.Execer, gw *Gateway) error {
if err := gw.Validate(); err != nil {
return errors.Wrap(err, "validate error")
}
now := time.Now()
res, err := db.Exec(`
update gateway
set updated_at = $2,
name = $3,
description = $4,
organization_id = $5,
ping = $6,
last_ping_id = $7,
last_ping_sent_at = $8,
network_server_id = $9,
gateway_profile_id = $10
where
mac = $1`,
gw.MAC[:],
now,
gw.Name,
gw.Description,
gw.OrganizationID,
gw.Ping,
gw.LastPingID,
gw.LastPingSentAt,
gw.NetworkServerID,
gw.GatewayProfileID,
)
if err != nil {
return handlePSQLError(Update, err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
gw.UpdatedAt = now
log.WithFields(log.Fields{
"mac": gw.MAC,
"name": gw.Name,
}).Info("gateway updated")
return nil
}
// DeleteGateway deletes the gateway matching the given MAC.
func DeleteGateway(db sqlx.Ext, mac lorawan.EUI64) error {
n, err := GetNetworkServerForGatewayMAC(db, mac)
if err != nil {
return errors.Wrap(err, "get network-server error")
}
res, err := db.Exec("delete from gateway where mac = $1", mac[:])
if err != nil {
return errors.Wrap(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
nsClient, err := config.C.NetworkServer.Pool.Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey))
if err != nil {
return errors.Wrap(err, "get network-server client error")
}
_, err = nsClient.DeleteGateway(context.Background(), &ns.DeleteGatewayRequest{
Id: mac[:],
})
if err != nil && grpc.Code(err) != codes.NotFound {
return errors.Wrap(err, "delete gateway error")
}
log.WithField("mac", mac).Info("gateway deleted")
return nil
}
// GetGateway returns the gateway for the given mac.
func GetGateway(db sqlx.Queryer, mac lorawan.EUI64, forUpdate bool) (Gateway, error) {
var fu string
if forUpdate {
fu = " for update"
}
var gw Gateway
err := sqlx.Get(db, &gw, "select * from gateway where mac = $1"+fu, mac[:])
if err != nil {
if err == sql.ErrNoRows {
return gw, ErrDoesNotExist
}
}
return gw, nil
}
// GetGatewayCount returns the total number of gateways.
func GetGatewayCount(db sqlx.Queryer, search string) (int, error) {
var count int
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Get(db, &count, `
select
count(*)
from gateway
where
$1 = ''
or (
$1 != ''
and (
name ilike $1
or encode(mac, 'hex') ilike $1
)
)
`,
search,
)
if err != nil {
return 0, errors.Wrap(err, "select error")
}
return count, nil
}
// GetGateways returns a slice of gateways sorted by name.
func GetGateways(db sqlx.Queryer, limit, offset int, search string) ([]Gateway, error) {
var gws []Gateway
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Select(db, &gws, `
select
*
from gateway
where
$3 = ''
or (
$3 != ''
and (
name ilike $3
or encode(mac, 'hex') ilike $3
)
)
order by
name
limit $1 offset $2`,
limit,
offset,
search,
)
if err != nil {
return nil, errors.Wrap(err, "select error")
}
return gws, nil
}
// GetGatewaysForMACs returns a map of gateways given a slice of MACs.
func GetGatewaysForMACs(db sqlx.Queryer, macs []lorawan.EUI64) (map[lorawan.EUI64]Gateway, error) {
out := make(map[lorawan.EUI64]Gateway)
var macsB [][]byte
for i := range macs {
macsB = append(macsB, macs[i][:])
}
var gws []Gateway
err := sqlx.Select(db, &gws, "select * from gateway where mac = any($1)", pq.ByteaArray(macsB))
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
if len(gws) != len(macs) {
log.WithFields(log.Fields{
"expected": len(macs),
"returned": len(gws),
}).Warning("requested number of gateways does not match returned")
}
for i := range gws {
out[gws[i].MAC] = gws[i]
}
return out, nil
}
// GetGatewayCountForOrganizationID returns the total number of gateways
// given an organization ID.
func GetGatewayCountForOrganizationID(db sqlx.Queryer, organizationID int64, search string) (int, error) {
var count int
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Get(db, &count, `
select
count(*)
from gateway
where
organization_id = $1
and (
$2 = ''
or (
$2 != ''
and (
name ilike $2
or encode(mac, 'hex') ilike $2
)
)
)`,
organizationID,
search,
)
if err != nil {
return 0, errors.Wrap(err, "select error")
}
return count, nil
}
// GetGatewaysForOrganizationID returns a slice of gateways sorted by name
// for the given organization ID.
func GetGatewaysForOrganizationID(db sqlx.Queryer, organizationID int64, limit, offset int, search string) ([]Gateway, error) {
var gws []Gateway
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Select(db, &gws, `
select
*
from gateway
where
organization_id = $1
and (
$4 = ''
or (
$4 != ''
and (
name ilike $4
or encode(mac, 'hex') ilike $4
)
)
)
order by
name
limit $2 offset $3`,
organizationID,
limit,
offset,
search,
)
if err != nil {
return nil, errors.Wrap(err, "select error")
}
return gws, nil
}
// GetGatewayCountForUser returns the total number of gateways to which the
// given user has access.
func GetGatewayCountForUser(db sqlx.Queryer, username string, search string) (int, error) {
var count int
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Get(db, &count, `
select
count(g.*)
from gateway g
inner join organization o
on o.id = g.organization_id
inner join organization_user ou
on ou.organization_id = o.id
inner join "user" u
on u.id = ou.user_id
where
u.username = $1
and (
$2 = ''
or (
$2 != ''
and (
g.name ilike $2
or encode(g.mac, 'hex') ilike $2
)
)
)`,
username,
search,
)
if err != nil {
return 0, errors.Wrap(err, "select error")
}
return count, nil
}
// GetGatewaysForUser returns a slice of gateways sorted by name to which the
// given user has access.
func GetGatewaysForUser(db sqlx.Queryer, username string, limit, offset int, search string) ([]Gateway, error) {
var gws []Gateway
if search != "" {
search = "%" + search + "%"
}
err := sqlx.Select(db, &gws, `
select
g.*
from gateway g
inner join organization o
on o.id = g.organization_id
inner join organization_user ou
on ou.organization_id = o.id
inner join "user" u
on u.id = ou.user_id
where
u.username = $1
and (
$4 = ''
or (
$4 != ''
and (
g.name ilike $4
or encode(g.mac, 'hex') ilike $4
)
)
)
order by
g.name
limit $2 offset $3`,
username,
limit,
offset,
search,
)
if err != nil {
return nil, errors.Wrap(err, "select error")
}
return gws, nil
}
// CreateGatewayPing creates the given gateway ping.
func CreateGatewayPing(db sqlx.Queryer, ping *GatewayPing) error {
ping.CreatedAt = time.Now()
err := sqlx.Get(db, &ping.ID, `
insert into gateway_ping (
created_at,
gateway_mac,
frequency,
dr
) values ($1, $2, $3, $4)
returning id`,
ping.CreatedAt,
ping.GatewayMAC[:],
ping.Frequency,
ping.DR,
)
if err != nil {
return handlePSQLError(Insert, err, "insert error")
}
log.WithFields(log.Fields{
"gateway_mac": ping.GatewayMAC,
"frequency": ping.Frequency,
"dr": ping.DR,
"id": ping.ID,
}).Info("gateway ping created")
return nil
}
// GetGatewayPing returns the ping matching the given id.
func GetGatewayPing(db sqlx.Queryer, id int64) (GatewayPing, error) {
var ping GatewayPing
err := sqlx.Get(db, &ping, "select * from gateway_ping where id = $1", id)
if err != nil {
return ping, handlePSQLError(Select, err, "select error")
}
return ping, nil
}
// CreateGatewayPingRX creates the received ping.
func CreateGatewayPingRX(db sqlx.Queryer, rx *GatewayPingRX) error {
rx.CreatedAt = time.Now()
err := sqlx.Get(db, &rx.ID, `
insert into gateway_ping_rx (
ping_id,
created_at,
gateway_mac,
received_at,
rssi,
lora_snr,
location,
altitude
) values ($1, $2, $3, $4, $5, $6, $7, $8)
returning id`,
rx.PingID,
rx.CreatedAt,
rx.GatewayMAC[:],
rx.ReceivedAt,
rx.RSSI,
rx.LoRaSNR,
rx.Location,
rx.Altitude,
)
if err != nil {
return handlePSQLError(Insert, err, "insert error")
}
return nil
}
// DeleteAllGatewaysForOrganizationID deletes all gateways for a given
// organization id.
func DeleteAllGatewaysForOrganizationID(db sqlx.Ext, organizationID int64) error {
var gws []Gateway
err := sqlx.Select(db, &gws, "select * from gateway where organization_id = $1", organizationID)
if err != nil {
return handlePSQLError(Select, err, "select error")
}
for _, gw := range gws {
err = DeleteGateway(db, gw.MAC)
if err != nil {
return errors.Wrap(err, "delete gateway error")
}
}
return nil
}
// GetGatewayPingRXForPingID returns the received gateway pings for the given
// ping ID.
func GetGatewayPingRXForPingID(db sqlx.Queryer, pingID int64) ([]GatewayPingRX, error) {
var rx []GatewayPingRX
err := sqlx.Select(db, &rx, "select * from gateway_ping_rx where ping_id = $1", pingID)
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
return rx, nil
}
// GetLastGatewayPingAndRX returns the last gateway ping and RX for the given
// gateway MAC.
func GetLastGatewayPingAndRX(db sqlx.Queryer, mac lorawan.EUI64) (GatewayPing, []GatewayPingRX, error) {
gw, err := GetGateway(db, mac, false)
if err != nil {
return GatewayPing{}, nil, errors.Wrap(err, "get gateway error")
}
if gw.LastPingID == nil {
return GatewayPing{}, nil, ErrDoesNotExist
}
ping, err := GetGatewayPing(db, *gw.LastPingID)
if err != nil {
return GatewayPing{}, nil, errors.Wrap(err, "get gateway ping error")
}
rx, err := GetGatewayPingRXForPingID(db, ping.ID)
if err != nil {
return GatewayPing{}, nil, errors.Wrap(err, "get gateway ping rx for ping id error")
}
return ping, rx, nil
}