qixiaoning
2025-07-08 fe724b50b3f1b3dfe2219eb9af4bcca96c89a158
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package mqtt
 
import (
    "fmt"
 
    MQTT "github.com/eclipse/paho.mqtt.golang"
)
 
type MQTTClient struct {
    Broker   string
    ClientId string
    Username string
    Passwd   string
    Mqtt     MQTT.Client
}
 
var Client *MQTTClient
 
func init() {
    Client = &MQTTClient{}
}
 
type mqLog struct {
 
}
 
func (l *mqLog) Println(v ...interface{}) {
    fmt.Println(v...)
}
 
func (l *mqLog) Printf(format string, v ...interface{}) {
    fmt.Println(fmt.Sprintf(format, v...))
}
 
func (m *MQTTClient) Init(brokerAddr, clientId, username, password string) {
    m.Broker = brokerAddr
    m.ClientId = clientId
    m.Username = username
    m.Passwd = password
 
    opts := MQTT.NewClientOptions().AddBroker(brokerAddr)
    opts.SetClientID(clientId)
    opts.SetUsername(username)
    opts.SetPassword(password)
 
    opts.SetAutoReconnect(false)
    hl := mqLog{}
    MQTT.ERROR   = &hl
    MQTT.CRITICAL= &hl
    MQTT.WARN    = &hl
    MQTT.DEBUG   = &hl
 
    m.Mqtt = MQTT.NewClient(opts)
 
fmt.Println("connectRetry:", opts.ConnectRetry)
    if token := m.Mqtt.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
        // fmt.Println(token.Error())
    }
}
 
func (m *MQTTClient) Subscribe(topic string, sub chan<- MQTT.Message) {
    fmt.Println("start subscribing...")
    subToken := m.Mqtt.Subscribe(
        topic,
        0,
        func(client MQTT.Client, msg MQTT.Message) {
            sub <- msg
        })
    if subToken.Wait() && subToken.Error() != nil {
        fmt.Println(subToken.Error())
    }
}
 
func (m *MQTTClient) Publish(topic string, msg interface{}) {
    if m.Mqtt.IsConnected() {
        token := m.Mqtt.Publish(topic, 0, false, msg)
        if token.Wait() && token.Error() != nil {
            fmt.Println(token.Error())
        }
    } else {
        fmt.Println("mqtt client reconneted")
        if token := m.Mqtt.Connect(); token.Wait() && token.Error() != nil {
            fmt.Println(token.Error())
        }
    }
}