Skip to content

Commit

Permalink
Merge pull request #1 from svenwltr/resubscribe
Browse files Browse the repository at this point in the history
resubscribe on reconnect
  • Loading branch information
svenwltr authored Sep 12, 2023
2 parents f61f13e + 6035e3f commit fbba0b0
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions cmd/subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,20 @@ func (r *SubscribeRunner) Run(ctx context.Context) error {
opts := mqtt.NewClientOptions()
opts.AddBroker(r.broker)
opts.SetAutoReconnect(true)
opts.SetConnectRetry(true)

client := mqtt.NewClient(opts)
token := client.Connect()
token.Wait()
if token.Error() != nil {
return token.Error()
opts.OnConnect = func(client mqtt.Client) {
token := client.Subscribe(r.topic, 1, handler.Handle)
token.Wait()
if token.Error() != nil {
fmt.Println(token.Error())
}
}

token = client.Subscribe(r.topic, 1, handler.Handle)
opts.OnConnectionLost = handler.onConnectionLost

client := mqtt.NewClient(opts)
token := client.Connect()
token.Wait()
if token.Error() != nil {
return token.Error()
Expand Down Expand Up @@ -161,3 +166,19 @@ func (h *SubscribeHandler) executeTemplate(t *template.Template, data any) (stri
}
return buf.String(), nil
}

func (h *SubscribeHandler) onConnectionLost(mqtt.Client, error) {
fmt.Println("connection lost")
}

type Logger string

func (l Logger) Println(v ...interface{}) {
fmt.Print(l, " ")
fmt.Println(v...)
}

func (l Logger) Printf(format string, v ...interface{}) {
fmt.Print(l, " ")
fmt.Printf(format, v...)
}

0 comments on commit fbba0b0

Please sign in to comment.