Go

Getting Started

Before getting started, make sure that Go and required libraries are installed by visiting the setup page

Import libraries

Add the following code into the top of your page

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

Define Variables

Basic
TLS
Basic
var jsonData []byte
var deviceId string = "PASTE_DEVICE_ID_HERE"
var deviceToken string = "PASTE_DEVICE_TOKEN_HERE"
var brokerHost string = "tcp://broker.qubitro.com:1883"
TLS
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)