forked from brocaar/chirpstack-application-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventlog.go
124 lines (104 loc) · 2.51 KB
/
eventlog.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
package eventlog
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/brocaar/lora-app-server/internal/config"
"github.com/brocaar/lorawan"
)
const (
deviceEventUplinkPubSubKeyTempl = "lora:as:device:%s:pubsub:event"
)
// Event types.
const (
Uplink = "uplink"
ACK = "ack"
Join = "join"
Error = "error"
Status = "status"
Location = "location"
)
// EventLog contains an event log.
type EventLog struct {
Type string
Payload interface{}
}
// LogEventForDevice logs an event for the given device.
func LogEventForDevice(devEUI lorawan.EUI64, el EventLog) error {
c := config.C.Redis.Pool.Get()
defer c.Close()
key := fmt.Sprintf(deviceEventUplinkPubSubKeyTempl, devEUI)
b, err := json.Marshal(el)
if err != nil {
return errors.Wrap(err, "gob encode error")
}
if _, err := c.Do("PUBLISH", key, b); err != nil {
return errors.Wrap(err, "publish device event error")
}
return nil
}
// GetEventLogForDevice subscribes to the device events for the given DevEUI
// and sends this to the given channel.
func GetEventLogForDevice(ctx context.Context, devEUI lorawan.EUI64, eventsChan chan EventLog) error {
c := config.C.Redis.Pool.Get()
defer c.Close()
key := fmt.Sprintf(deviceEventUplinkPubSubKeyTempl, devEUI)
psc := redis.PubSubConn{Conn: c}
if err := psc.Subscribe(key); err != nil {
return errors.Wrap(err, "subscribe error")
}
done := make(chan error, 1)
go func() {
for {
switch v := psc.Receive().(type) {
case redis.Message:
el, err := redisMessageToEventLog(v)
if err != nil {
log.WithError(err).Error("decode message errror")
} else {
eventsChan <- el
}
case redis.Subscription:
if v.Count == 0 {
done <- nil
return
}
case error:
done <- v
return
}
}
}()
// todo: make this a config value?
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
loop:
for {
select {
case <-ticker.C:
if err := psc.Ping(""); err != nil {
log.WithError(err).Error("subscription ping error")
break loop
}
case <-ctx.Done():
break loop
case err := <-done:
return err
}
}
if err := psc.Unsubscribe(); err != nil {
return errors.Wrap(err, "unsubscribe error")
}
return <-done
}
func redisMessageToEventLog(msg redis.Message) (EventLog, error) {
var el EventLog
if err := json.Unmarshal(msg.Data, &el); err != nil {
return el, errors.Wrap(err, "gob decode error")
}
return el, nil
}