78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/util/guid"
|
|
)
|
|
|
|
type MQTT struct {
|
|
mc mqtt.Client
|
|
}
|
|
|
|
func (t *MQTT) InitMQTT() error {
|
|
ip, err := g.Cfg().Get(nil, "MQTT.ip")
|
|
if err != nil {
|
|
g.Log().Line().Print(nil, err)
|
|
return err
|
|
}
|
|
port, err := g.Cfg().Get(nil, "MQTT.port")
|
|
if err != nil {
|
|
g.Log().Line().Print(nil, err)
|
|
return err
|
|
}
|
|
user, err := g.Cfg().Get(nil, "MQTT.user")
|
|
if err != nil {
|
|
g.Log().Line().Print(nil, err)
|
|
return err
|
|
}
|
|
passwd, err := g.Cfg().Get(nil, "MQTT.passwd")
|
|
if err != nil {
|
|
g.Log().Line().Print(nil, err)
|
|
return err
|
|
}
|
|
opts := mqtt.NewClientOptions()
|
|
opts.AddBroker(fmt.Sprintf("mqtt://%s:%d", ip, port))
|
|
opts.SetKeepAlive(time.Hour * 24)
|
|
opts.SetPingTimeout(time.Second * 30)
|
|
opts.SetClientID(guid.S())
|
|
opts.SetUsername(user.String())
|
|
opts.SetPassword(passwd.String())
|
|
//opts.SetDefaultPublishHandler(messagePubHandler)
|
|
//opts.OnConnect = connectHandler
|
|
opts.OnConnectionLost = t.connectLostHandler
|
|
t.mc = mqtt.NewClient(opts)
|
|
if token := t.mc.Connect(); token.Wait() && token.Error() != nil {
|
|
g.Log().Line().Print(nil, token.Error())
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// MQTT 推送订单结果消息
|
|
//func (t *MQTT) Publish(client mqtt.Client,msg *vo.MQTTOrder) string {
|
|
|
|
// 返回支付结果消息
|
|
/*
|
|
func publishResult(client mqtt.Client, msg *vo.MQTTOrder) string {
|
|
//command.Msg_Id = guid.S()
|
|
command.SendTime = time.Now()
|
|
j, err := json.Marshal(msg)
|
|
if err == nil {
|
|
token := client.Publish(command.Topic, 0, false, string(j))
|
|
token.Wait()
|
|
return ""
|
|
} else {
|
|
return err.Error()
|
|
}
|
|
}
|
|
*/
|
|
func (t *MQTT) connectLostHandler(client mqtt.Client, err error) {
|
|
token := t.mc.Connect()
|
|
g.Log().Line().Print(nil, "MQTT 重新连接成功")
|
|
token.Wait()
|
|
}
|