Go

Quick guide for Go library.

Getting Started

Visit the MQTT overview page for conventions, authentication, and more information.

This documentation uses the Paho MQTT library. This library is open-source, so you can check it on GitHub.

Installing the packages

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

Import libraries

Then import it and initialize it with the required packages. Of course, you’ll want to replace DEVICE_ID and DEVICE_TOKENwith your actual device credentials which you can find under your device settings on Qubitro Portal.

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

We strongly recommend using the 8883 port for MQTT over TLS connectivity.

Publish

Subscribe

Message

Disconnect

client.Disconnect(250)

✨ Support and Feedback

If you have further questions or suggestions, feel free to join πŸ‘‡ -> Qubitro Community Discord via this invitation link.

Last updated