package libs
import (
"fmt"
"log"
"os"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func InitMQTT(server string, username string, password string, MQTTClientID string) (mqttClient mqtt.Client, err error) {
opt := mqtt.NewClientOptions()
opt.AddBroker(server)
opt.SetUsername(username)
opt.SetPassword(password)
opt.SetClientID(MQTTClientID)
opt.SetConnectTimeout(time.Second * 3)
opt.SetAutoReconnect(true)
opt.SetConnectRetry(true)
opt.SetConnectRetryInterval(time.Second)
opt.SetOrderMatters(false)
opt.SetOnConnectHandler(func(client mqtt.Client) {
// 连接被建立后的回调函数
log.Println("Mqtt is connected!", "clientId:", MQTTClientID, "server:", server)
})
opt.SetConnectionLostHandler(func(client mqtt.Client, err error) {
// 连接被关闭后的回调函数
log.Println("Mqtt is disconnected!", "clientId:", MQTTClientID, "reason", err.Error())
})
mqttClient = mqtt.NewClient(opt)
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
fmt.Printf("mqtt连接失败: %v\n", token.Error())
os.Exit(1)
}
return
}
func InitMQTTAndSubscribe(server string, username string, password string, MQTTClientID string, topic string, callback mqtt.MessageHandler) (mqttClient mqtt.Client, err error) {
opt := mqtt.NewClientOptions()
opt.AddBroker(server)
opt.SetUsername(username)
opt.SetPassword(password)
opt.SetClientID(MQTTClientID)
opt.SetConnectTimeout(time.Second * 3)
opt.SetAutoReconnect(true)
opt.SetConnectRetry(true)
opt.SetConnectRetryInterval(time.Second)
opt.SetOrderMatters(false)
opt.SetOnConnectHandler(func(client mqtt.Client) {
// 连接被建立后的回调函数
log.Println("Mqtt is connected!", "clientId:", MQTTClientID, "server:", server)
if token := client.Subscribe(topic, 0, callback); token.Wait() && token.Error() != nil {
fmt.Printf("订阅失败: %v\n", token.Error())
os.Exit(1)
}
})
opt.SetConnectionLostHandler(func(client mqtt.Client, err error) {
// 连接被关闭后的回调函数
log.Println("Mqtt is disconnected!", "clientId:", MQTTClientID, "reason", err.Error())
})
mqttClient = mqtt.NewClient(opt)
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
fmt.Printf("mqtt连接失败: %v\n", token.Error())
os.Exit(1)
}
return
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
mqtttest.zip (6个子文件)
mqtttest
mqtttest 6.79MB
libs
utils.go 1KB
tools.go 347B
mqtt.go 2KB
config
index.json 166B
main.go 842B
共 6 条
- 1
资源评论
bing03246
- 粉丝: 263
- 资源: 19
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功