-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (68 loc) · 2.14 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
86
87
88
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gowon-irc/go-gowon"
"github.com/jessevdk/go-flags"
)
type Options struct {
Prefix string `short:"P" long:"prefix" env:"GOWON_PREFIX" default:"." description:"prefix for commands"`
Broker string `short:"b" long:"broker" env:"GOWON_BROKER" default:"localhost:1883" description:"mqtt broker"`
}
const (
moduleName = "qwantz"
mqttConnectRetryInternal = 5
mqttDisconnectTimeout = 1000
)
func qwantzxHandler(m gowon.Message) (string, error) {
return qwantz()
}
func defaultPublishHandler(c mqtt.Client, msg mqtt.Message) {
log.Printf("unexpected message: %s\n", msg)
}
func onConnectionLostHandler(c mqtt.Client, err error) {
log.Println("connection to broker lost")
}
func onRecconnectingHandler(c mqtt.Client, opts *mqtt.ClientOptions) {
log.Println("attempting to reconnect to broker")
}
func onConnectHandler(c mqtt.Client) {
log.Println("connected to broker")
}
func main() {
log.Printf("%s starting\n", moduleName)
opts := Options{}
if _, err := flags.Parse(&opts); err != nil {
log.Fatal(err)
}
mqttOpts := mqtt.NewClientOptions()
mqttOpts.AddBroker(fmt.Sprintf("tcp://%s", opts.Broker))
mqttOpts.SetClientID(fmt.Sprintf("gowon_%s", moduleName))
mqttOpts.SetConnectRetry(true)
mqttOpts.SetConnectRetryInterval(mqttConnectRetryInternal * time.Second)
mqttOpts.SetAutoReconnect(true)
mqttOpts.DefaultPublishHandler = defaultPublishHandler
mqttOpts.OnConnectionLost = onConnectionLostHandler
mqttOpts.OnReconnecting = onRecconnectingHandler
mqttOpts.OnConnect = onConnectHandler
mr := gowon.NewMessageRouter()
mr.AddCommand("qwantz", qwantzxHandler)
mr.Subscribe(mqttOpts, moduleName)
log.Print("connecting to broker")
c := mqtt.NewClient(mqttOpts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
log.Print("connected to broker")
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-sigs
log.Println("signal caught, exiting")
c.Disconnect(mqttDisconnectTimeout)
log.Println("shutdown complete")
}