forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmqtt.go
156 lines (133 loc) · 3.67 KB
/
mqtt.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package mqtt
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
gomqtt "github.com/eclipse/paho.mqtt.golang"
)
const (
Host = "192.168.1.101:8000"
UserName = "pibigstar"
Password = "123456"
)
type Client struct {
nativeClient gomqtt.Client
clientOptions *gomqtt.ClientOptions
locker *sync.Mutex
// 消息收到之后处理函数
observer func(c *Client, msg *Message)
}
type Message struct {
ClientID string `json:"clientId"`
Type string `json:"type"`
Data string `json:"data,omitempty"`
Time int64 `json:"time"`
}
func NewClient(clientId string) *Client {
clientOptions := gomqtt.NewClientOptions().
AddBroker(Host).
SetUsername(UserName).
SetPassword(Password).
SetClientID(clientId).
SetCleanSession(false).
SetAutoReconnect(true).
SetKeepAlive(120 * time.Second).
SetPingTimeout(10 * time.Second).
SetWriteTimeout(10 * time.Second).
SetOnConnectHandler(func(client gomqtt.Client) {
// 连接被建立后的回调函数
fmt.Println("Mqtt is connected!", "clientId", clientId)
}).
SetConnectionLostHandler(func(client gomqtt.Client, err error) {
// 连接被关闭后的回调函数
fmt.Println("Mqtt is disconnected!", "clientId", clientId, "reason", err.Error())
})
nativeClient := gomqtt.NewClient(clientOptions)
return &Client{
nativeClient: nativeClient,
clientOptions: clientOptions,
locker: &sync.Mutex{},
}
}
func (client *Client) GetClientID() string {
return client.clientOptions.ClientID
}
func (client *Client) Connect() error {
return client.ensureConnected()
}
// 确保连接
func (client *Client) ensureConnected() error {
if !client.nativeClient.IsConnected() {
client.locker.Lock()
defer client.locker.Unlock()
if !client.nativeClient.IsConnected() {
if token := client.nativeClient.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
}
}
return nil
}
// 发布消息
// retained: 是否保留信息
func (client *Client) Publish(topic string, qos byte, retained bool, data []byte) error {
if err := client.ensureConnected(); err != nil {
return err
}
token := client.nativeClient.Publish(topic, qos, retained, data)
if err := token.Error(); err != nil {
return err
}
// return false is the timeout occurred
if !token.WaitTimeout(time.Second * 10) {
return errors.New("mqtt publish wait timeout")
}
return nil
}
// 消费消息
func (client *Client) Subscribe(observer func(c *Client, msg *Message), qos byte, topics ...string) error {
if len(topics) == 0 {
return errors.New("the topic is empty")
}
if observer == nil {
return errors.New("the observer func is nil")
}
if client.observer != nil {
return errors.New("an existing observer subscribed on this client, you must unsubscribe it before you subscribe a new observer")
}
client.observer = observer
filters := make(map[string]byte)
for _, topic := range topics {
filters[topic] = qos
}
client.nativeClient.SubscribeMultiple(filters, client.messageHandler)
return nil
}
func (client *Client) messageHandler(c gomqtt.Client, msg gomqtt.Message) {
if client.observer == nil {
fmt.Println("not subscribe message observer")
return
}
message, err := decodeMessage(msg.Payload())
if err != nil {
fmt.Println("failed to decode message")
return
}
client.observer(client, message)
}
func decodeMessage(payload []byte) (*Message, error) {
message := new(Message)
decoder := json.NewDecoder(strings.NewReader(string(payload)))
decoder.UseNumber()
if err := decoder.Decode(&message); err != nil {
return nil, err
}
return message, nil
}
func (client *Client) Unsubscribe(topics ...string) {
client.observer = nil
client.nativeClient.Unsubscribe(topics...)
}