This repository has been archived by the owner on Dec 14, 2021. It is now read-only.
/
subscribe.go
79 lines (69 loc) · 2.2 KB
/
subscribe.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
// 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 cmd
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/TheThingsNetwork/ttn/core/types"
"github.com/TheThingsNetwork/ttn/mqtt"
"github.com/TheThingsNetwork/ttn/ttnctl/util"
"github.com/spf13/cobra"
)
var subscribeCmd = &cobra.Command{
Use: "subscribe",
Short: "Subscribe to events for this application",
Long: `ttnctl subscribe can be used to subscribe to events for this application.`,
Run: func(cmd *cobra.Command, args []string) {
assertArgsLength(cmd, args, 0, 0)
accessKey, err := cmd.Flags().GetString("access-key")
if err != nil {
ctx.WithError(err).Fatal("Failed to read access-key flag")
}
util.GetAccount(ctx)
client := util.GetMQTT(ctx, accessKey)
defer client.Disconnect()
token := client.SubscribeActivations(func(client mqtt.Client, appID string, devID string, req types.Activation) {
ctx.Info("Activation")
printKV("AppID", appID)
printKV("DevID", devID)
printKV("AppEUI", req.AppEUI)
printKV("DevEUI", req.DevEUI)
printKV("DevAddr", req.DevAddr)
fmt.Println()
})
token.Wait()
if err := token.Error(); err != nil {
ctx.WithError(err).Fatal("Could not subscribe to activations")
}
ctx.Info("Subscribed to activations")
token = client.SubscribeUplink(func(client mqtt.Client, appID string, devID string, req types.UplinkMessage) {
ctx.Info("Uplink Message")
printKV("AppID", appID)
printKV("DevID", devID)
printKV("Port", req.FPort)
printKV("FCnt", req.FCnt)
printKV("Payload (hex)", req.PayloadRaw)
if len(req.PayloadFields) > 0 {
ctx.Info("Decoded fields")
for k, v := range req.PayloadFields {
printKV(k, v)
}
}
fmt.Println()
})
token.Wait()
if err := token.Error(); err != nil {
ctx.WithError(err).Fatal("Could not subscribe to uplink")
}
ctx.Info("Subscribed to uplink")
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
ctx.WithField("signal", <-sigChan).Info("signal received")
},
}
func init() {
RootCmd.AddCommand(subscribeCmd)
subscribeCmd.Flags().String("access-key", "", "The access key to use")
}