Paho MQTT Golang way to loop forever

65 Views Asked by At

In the python version, you can "listen" for messages forever but I'm lost with the golang version. How can I have something similar to client.loop_forever()?

1

There are 1 best solutions below

0
tonys On

As per the comments to your question, you need to set up the Paho client with callbacks to handle the connected and disconnected events and received messages, and then wait-until-exit. For a v3 client, the code looks something like this:

func main() {
    if client,err := subscribe(); err != nil {
       fmt.Printf("error subscribing to MQTT broker (%v)",err)
    } else {
       exit := make(chan os.Signal)

       signal.Notify(exit, syscall.SIGINT, syscall.SIGTERM)

       <-exit

       client.Disconnect(250)
    }
}

func subscribe() (paho.Client, error) {
    topic := "allthethings/#"

    var handler paho.MessageHandler = func(client paho.Client, msg paho.Message) {
        // (process received message)
    }

    var connected paho.OnConnectHandler = func(client paho.Client) {
        for _, url := range client.OptionsReader().Servers() {
            fmt.Printf("connected to %s", url)
        }

        token := client.Subscribe(topic, 0, handler)
        if err := token.Error(); err != nil {
            fmt.Printf("error subscribing to topic %s (%v)", topic, err)
        }
    }

    var disconnected paho.ConnectionLostHandler = func(client paho.Client, err error) {
        fmt.Printf("connection to MQTT broker lost (%v)", err)

        go func() {
            time.Sleep(10 * time.Second)
            token := client.Connect()
            if err := token.Error(); err != nil {
                fmt.Printf("error reconnecting to broker (%v)", err)
            }
        }()
    }

    options := paho.
        NewClientOptions().
        AddBroker(broker).
        SetClientID(clientID).
        SetUsername(uid).
        SetPassword(pwd).
        SetTLSConfig(TLS).
        SetCleanSession(false).
        SetAutoReconnect(false).
        SetConnectRetry(true).
        SetConnectRetryInterval(30 * time.Second).
        SetOnConnectHandler(connected).
        SetConnectionLostHandler(disconnected)

    client := paho.NewClient(options)
    token := client.Connect()
    if err := token.Error(); err != nil {
        return nil, err
    }

    return client, nil
}