Go

Getting Started

go get github.com/eclipse/paho.mqtt.golang

Import libraries

Add the following code to the top of your page

package main
import (
"encoding/json"
"fmt"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)

Define Variables

var jsonData []byte
var deviceId string = "PASTE_DEVICE_ID_HERE"
var deviceToken string = "PASTE_DEVICE_TOKEN_HERE"
var brokerHost string = "tls://broker.qubitro.com:8883"

Setup MQTT Client

options := mqtt.NewClientOptions().AddBroker(brokerHost)
options.SetClientID(deviceId)
options.SetUsername(deviceId)
options.SetPassword(deviceToken)
options.AutoReconnect = true
client := mqtt.NewClient(options)

Define Callbacks

Define callbacks depending on your scenario.

See the examples below or visit the package documentation.

options.OnConnect = func(c mqtt.Client) {
fmt.Println("Connected to Qubitro")
}
options.SetConnectionLostHandler(func(lost mqtt.Client, err error) {
fmt.Println(err.Error())
})

Prepare Data

type Data struct {
Temperature float64
CpuUsage float64
}
data := &Data{
Temperature: 40.5,
CpuUsage: 78,
}

Examples

Publish

Qubitro MQTT Publish Example Go

Subscribe

Qubitro MQTT Subscribe Example Go

Message

Disconnect

client.Disconnect(250)