-
Notifications
You must be signed in to change notification settings - Fork 0
/
amqp.go
70 lines (59 loc) · 1.59 KB
/
amqp.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
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package handler
import (
"github.com/apex/log"
"github.com/TheThingsNetwork/go-utils/log/apex"
"github.com/TheThingsNetwork/ttn/amqp"
"github.com/TheThingsNetwork/ttn/core/types"
)
func (h *handler) HandleAMQP(username, password, host, exchange, downlinkQueue string) error {
h.amqpClient = amqp.NewClient(apex.Wrap(h.Ctx), username, password, host)
err := h.amqpClient.Connect()
if err != nil {
return err
}
defer func() {
if err != nil {
h.amqpClient.Disconnect()
}
}()
h.amqpUp = make(chan *types.UplinkMessage)
subscriber := h.amqpClient.NewSubscriber(h.amqpExchange, downlinkQueue, downlinkQueue != "", downlinkQueue == "")
err = subscriber.Open()
if err != nil {
return err
}
defer func() {
if err != nil {
subscriber.Close()
}
}()
err = subscriber.SubscribeDownlink(func(_ amqp.Subscriber, _, _ string, req types.DownlinkMessage) {
h.EnqueueDownlink(&req)
})
if err != nil {
return err
}
ctx := h.Ctx.WithField("Protocol", "AMQP")
go func() {
publisher := h.amqpClient.NewPublisher(h.amqpExchange)
err := publisher.Open()
if err != nil {
ctx.WithError(err).Error("Could not open publisher channel")
return
}
defer publisher.Close()
for up := range h.amqpUp {
ctx.WithFields(log.Fields{
"DevID": up.DevID,
"AppID": up.AppID,
}).Debug("Publish Uplink")
err := publisher.PublishUplink(*up)
if err != nil {
ctx.WithError(err).Warn("Could not publish Uplink")
}
}
}()
return nil
}