produce_client.go 1.0 KB
package mqtt

import (
	"fmt"
	pahomqtt "github.com/eclipse/paho.mqtt.golang"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"time"
)

type ProduceClient struct {
	client  pahomqtt.Client
}

func NewProduceClient() *ProduceClient {
	return &ProduceClient{}
}

func (produceClient *ProduceClient) options() *pahomqtt.ClientOptions {
	opts := pahomqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%v:%v", constant.MQTT_HOST, constant.MQTT_PORT))
	opts.SetUsername(constant.MQTT_USER)
	opts.SetPassword(constant.MQTT_PASSWORD)
	opts.SetKeepAlive(2 * time.Second)
	opts.SetPingTimeout(1 * time.Second)
	return opts
}

func (produceClient *ProduceClient) connect(){
	opts := produceClient.options()
	produceClient.client = pahomqtt.NewClient(opts)
	token := produceClient.client.Connect()
	token.Wait()
}

func (produceClient *ProduceClient) Publish(topic string,data interface{}) error {
	produceClient.connect()
	token := produceClient.client.Publish(topic,0,false,data)
	token.Wait()
	return token.Error()
}