produce_client.go
1.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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()
}