| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- package mqtt_reporter
- import (
- "context"
- "errors"
- "maps"
- "sync"
- "time"
- mqtt "github.com/eclipse/paho.mqtt.golang"
- "hnyfkj.com.cn/rtu/linux/baseapp"
- )
- const (
- MqttQos0 byte = 0 //// 消息最多送达一次
- MqttQos1 byte = 1 //// 消息至少送达一次
- MqttQos2 byte = 2 //// 消息恰好送达一次
- fastInterval = 1 * time.Second //// 快速检测时间间隔
- slowInterval = 5 * time.Second //// 慢速检测时间间隔
- )
- var (
- ErrNotStarted = errors.New("mqtt client not started")
- ErrNotConnected = errors.New("mqtt client not connected")
- ErrClosed = errors.New("mqtt client is closed, cannot perform operation")
- ErrBrokerEmpty = errors.New("mqtt broker is empty")
- ErrTopicEmpty = errors.New("mqtt topic is empty")
- ErrInvalidQoS = errors.New("mqtt qos is invalid")
- ErrNilHandler = errors.New("mqtt message handler is nil")
- )
- type ClientConfig struct {
- Broker string ////////// 连接服务器的地址
- BrokerName string ////////// 连接服务器的名字
- ClientID string ////////// 客户端的唯一标识
- Username string ////////// 登录服务器的用户
- Password string ////////// 登录服务器的密码
- Qos byte ////////// 传输消息质量等级
- Topics map[string]string ////////// 消息主题名和地址
- WillPayload string ////////// 遗嘱消息发送内容
- }
- type subscription struct {
- qos byte
- handler mqtt.MessageHandler //////////// 订阅主题消息处理
- }
- type MessageHandler func(client *Client, msg mqtt.Message)
- type Client struct {
- client mqtt.Client
- config ClientConfig
- ctx context.Context
- cancel context.CancelFunc
- done chan struct{}
- mu sync.Mutex
- subMu sync.Mutex
- subs map[string]subscription ////// 订阅主题与处理回调
- started bool
- closed bool
- }
- func NewClient(config ClientConfig, ctx context.Context) (*Client, error) {
- if config.Broker == "" {
- return nil, ErrBrokerEmpty
- }
- if ctx == nil {
- ctx = context.Background()
- }
- ctx, cancel := context.WithCancel(ctx)
- opts := mqtt.NewClientOptions().
- AddBroker(config.Broker).
- SetUsername(config.Username).SetPassword(config.Password).SetClientID(config.ClientID).
- SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
- SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // 保活超时&Ping心跳间隔
- SetOrderMatters(false)
- if willTopic := config.Topics["Offline"]; willTopic != "" { // 设置遗嘱消息
- if config.Qos != MqttQos0 && config.Qos != MqttQos1 && config.Qos != MqttQos2 {
- cancel()
- return nil, ErrInvalidQoS
- }
- opts = opts.SetWill(willTopic, config.WillPayload, config.Qos, false)
- }
- opts.OnConnect = func(c mqtt.Client) {
- baseapp.Logger.Infof("[%s] MQTT服务器 %s 连接成功", MODULE_NAME, config.BrokerName)
- }
- opts.OnConnectionLost = func(c mqtt.Client, err error) {
- baseapp.Logger.Warnf("[%s] MQTT服务器 %s 连接丢失: %v!", MODULE_NAME, config.BrokerName, err)
- }
- return &Client{
- client: mqtt.NewClient(opts),
- config: config,
- ctx: ctx,
- cancel: cancel,
- done: make(chan struct{}),
- subs: make(map[string]subscription),
- }, nil
- }
- func (c *Client) Start() error {
- c.mu.Lock()
- defer c.mu.Unlock()
- if c.closed {
- return ErrClosed
- }
- if c.started {
- return nil
- }
- c.started = true
- go c.run()
- return nil
- }
- func (c *Client) run() {
- defer func() {
- if c.client.IsConnected() {
- c.client.Disconnect(250)
- }
- close(c.done)
- }()
- for {
- // 1, 是否退出
- if c.ctx.Err() != nil {
- return
- }
- // 2, 已连接时
- if c.client.IsConnected() {
- if !c.waitInterval(fastInterval) {
- return
- }
- continue
- }
- // 3, 尝试连接
- baseapp.Logger.Infof("[%s] 尝试连接MQTT服务器: %s %s ...",
- MODULE_NAME, c.config.BrokerName, c.config.Broker)
- if err := c.connect(); err != nil {
- if c.ctx.Err() != nil {
- return
- }
- baseapp.Logger.Errorf("[%s] MQTT服务器 %s 连接失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
- if !c.waitInterval(slowInterval) {
- return
- }
- continue
- }
- // 4, 重新订阅
- if err := c.resubscribe(); err != nil {
- if c.ctx.Err() != nil {
- return
- }
- baseapp.Logger.Errorf("[%s] MQTT服务器 %s 订阅失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
- c.client.Disconnect(0)
- if !c.waitInterval(slowInterval) {
- return
- }
- continue
- }
- }
- }
- func (c *Client) waitInterval(d time.Duration) bool {
- timer := time.NewTimer(d)
- defer timer.Stop()
- select {
- case <-c.ctx.Done():
- return false
- case <-timer.C:
- return true
- }
- }
- func (c *Client) waitToken(token mqtt.Token) error {
- select {
- case <-c.ctx.Done():
- return c.ctx.Err()
- case <-token.Done():
- return token.Error()
- }
- }
- func (c *Client) connect() error {
- return c.waitToken(c.client.Connect())
- }
- func (c *Client) resubscribe() error {
- c.subMu.Lock()
- defer c.subMu.Unlock()
- c.mu.Lock()
- subs := make(map[string]subscription, len(c.subs))
- maps.Copy(subs, c.subs)
- c.mu.Unlock()
- for topic, sub := range subs {
- if c.ctx.Err() != nil {
- return c.ctx.Err()
- }
- if err := c.waitToken(c.client.Subscribe(topic, sub.qos, sub.handler)); err != nil {
- return err
- }
- }
- return nil
- }
- func (c *Client) IsConnected() bool {
- c.mu.Lock()
- defer c.mu.Unlock()
- return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
- }
- func (c *Client) WaitConnected() error {
- ticker := time.NewTicker(fastInterval)
- defer ticker.Stop()
- for {
- if c.IsConnected() {
- return nil
- }
- c.mu.Lock()
- err := c.checkStateLocked()
- c.mu.Unlock()
- if err != nil {
- return err
- }
- select {
- case <-c.ctx.Done():
- return c.ctx.Err()
- case <-ticker.C:
- }
- }
- }
- func (c *Client) checkStateLocked() error {
- switch {
- case c.closed:
- return ErrClosed
- case !c.started:
- return ErrNotStarted
- case c.ctx.Err() != nil:
- return c.ctx.Err()
- default:
- return nil
- }
- }
- func (c *Client) Publish(topic string, qos byte, retained bool, payload any) error {
- if topic == "" {
- return ErrTopicEmpty
- }
- if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
- return ErrInvalidQoS
- }
- c.mu.Lock()
- if err := c.checkStateLocked(); err != nil {
- c.mu.Unlock()
- return err
- }
- if !c.client.IsConnected() {
- c.mu.Unlock()
- return ErrNotConnected
- }
- token := c.client.Publish(topic, qos, retained, payload)
- c.mu.Unlock()
- return c.waitToken(token)
- }
- /*
- 消息回调需支持并发调用,并尽快返回,尽量避免耗时或阻塞操作, 此类类任务应交由独立的goroutine或通
- 过消息队列来处理,避免阻塞mqtt底层的消息处理。
- */
- func (c *Client) Subscribe(topic string, qos byte, handler MessageHandler) error {
- if topic == "" {
- return ErrTopicEmpty
- }
- if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
- return ErrInvalidQoS
- }
- if handler == nil {
- return ErrNilHandler
- }
- c.subMu.Lock()
- defer c.subMu.Unlock()
- c.mu.Lock()
- if err := c.checkStateLocked(); err != nil {
- c.mu.Unlock()
- return err
- }
- wrappedHandler := func(_ mqtt.Client, msg mqtt.Message) {
- handler(c, msg)
- }
- c.subs[topic] = subscription{qos: qos, handler: wrappedHandler}
- if !c.client.IsConnected() {
- c.mu.Unlock()
- return nil
- }
- token := c.client.Subscribe(topic, qos, wrappedHandler)
- c.mu.Unlock()
- return c.waitToken(token)
- }
- func (c *Client) Close() {
- c.mu.Lock()
- if !c.closed {
- c.closed = true
- c.cancel()
- }
- started := c.started
- c.mu.Unlock()
- if started {
- <-c.done
- }
- }
|