-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
85 lines (67 loc) · 1.86 KB
/
main.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
package subscribe
import (
"os"
"os/signal"
"syscall"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/pterm/pterm"
"github.com/snapp-incubator/pakhshi/pkg/client"
"github.com/spf13/cobra"
)
const (
// TopicFlag used with cobra to read the topic flag from user.
TopicFlag = "topic"
// QoSFlag used with cobra to read the qos flag from user.
QoSFlag = "qos"
// Timeout for disconnecting from brokers.
Timeout = 10
)
type Config struct {
Brokers []string
QoS byte
Topic string
}
func main(cfg Config) {
opts := mqtt.NewClientOptions()
for _, broker := range cfg.Brokers {
opts.AddBroker(broker)
}
c := client.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
pterm.Error.Println("mqtt connection failed:", token.Error().Error())
return
}
pterm.Info.Printf("subscribing on %s\n", cfg.Topic)
if token := c.Subscribe(cfg.Topic, cfg.QoS, func(c mqtt.Client, m mqtt.Message) {
pterm.Info.Printf("received: %s\n", string(m.Payload()))
}); token.Wait() && token.Error() != nil {
pterm.Error.Println("mqtt subcription failed:", token.Error().Error())
return
}
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
c.Disconnect(Timeout)
}
// Register migrate command.
func Register(root *cobra.Command, brokers *[]string) {
// nolint: exhaustivestruct
cmd :=
&cobra.Command{
Use: "subscribe",
Short: "subscribe on multiple brokers at the same time",
Run: func(cmd *cobra.Command, args []string) {
qos, _ := cmd.Flags().GetInt8(QoSFlag)
topic, _ := cmd.Flags().GetString(TopicFlag)
cfg := Config{
Brokers: *brokers,
QoS: byte(qos),
Topic: topic,
}
main(cfg)
},
}
cmd.Flags().StringP(TopicFlag, "t", "hello", "topic to subscribe on")
cmd.Flags().Int8P(QoSFlag, "q", 0, "subscription qos")
root.AddCommand(cmd)
}