Golang Paho MQTT over Websocket

Viewed 119

Hey I was trying to connect to AWS IoT Core via Golang Paho MQTT client. I tried the normal MQTT connection which was working without problems. Next I wanted to try the connection via MQTT over Websocket but could not find anything relating that in the Paho.Mqtt docs. How do I make the Websocket connection? I could post my code from my normal MQTT connection if necessary. Edit, here is my code:

package main

import (
    "crypto/tls"
    "fmt"
    "time"

    MQTT "github.com/eclipse/paho.mqtt.golang"
)

type Message struct {
    message string
}

/*var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
    fmt.Printf("TOPIC: %s\n", msg.Topic())
    fmt.Printf("MSG: %s\n", msg.Payload())
}*/

func main() {
    cer, err := tls.LoadX509KeyPair("cd5a04e9fd9a094326c9ee0cdc1e1f7b2e3510a9e106968683d333a2a4344ca7-certificate.pem.crt",
        "./cd5a04e9fd9a094326c9ee0cdc1e1f7b2e3510a9e106968683d333a2a4344ca7-private.pem.key")
    check(err)

    cid := "ClientID"

    // AutoReconnect option is true by default
    // CleanSession option is true by default
    // KeepAlive option is 30 seconds by default
    connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
    connOpts.SetClientID(cid)
    connOpts.SetMaxReconnectInterval(1 * time.Second)
    connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})

    host := "a2to6mbspmaw82-ats.iot.eu-west-1.amazonaws.com"
    port := 443

    brokerURL := fmt.Sprintf("wss://%s:%d", host, port)
    connOpts.AddBroker(brokerURL)

    mqttClient := MQTT.NewClient(connOpts)
    if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    var message = "message from lap"

    for message != "bye" {
        token := mqttClient.Publish("some_topic", 0, false, message)
        token.Wait()
        message = "bye"
    }
}

func check(err error) {
    if err != nil {
        panic(err)
    }
}
1 Answers

From the Eclipse Paho GoLang page

The type of connection required is specified by the scheme of the connection URL set in the ClientOptions struct, for example:

  • tcp://mqtt.eclipseprojects.io:1883 - connect to mqtt.eclipseprojects.io on port 1883 using plain TCP
  • ws://mqtt.eclipseprojects.io:1883 - connect to mqtt.eclipseprojects.io on port 1883 using WebSockets
  • tls://mqtt.eclipseprojects.io:8883 - connect to mqtt.eclipseprojects.io on port 8883 using TLS (ssl:// and tcps:// are synonyms for tls://)

The second entry in the list suggests you just pas in the URL with the right schema ( ws:// or probably wss://)

Related