backend.go 5.14 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
package backend
Lei Li's avatar
Lei Li committed
2
3

import (
Lei Li's avatar
Lei Li committed
4
5
	"crypto/tls"
	"crypto/x509"
Lei Li's avatar
Lei Li committed
6
7
8
9
	"fmt"
	"strings"
	"time"

Lei Li's avatar
Lei Li committed
10
	"agent/cmd/agent/config"
Lei Li's avatar
Lei Li committed
11
	"agent/cmd/agent/global"
Lei Li's avatar
Lei Li committed
12
	"agent/cmd/agent/option"
Lei Li's avatar
Lei Li committed
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
	"linkfog.com/public/lib/l"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

type Backend struct {
	isRunning      bool
	client         MQTT.Client
	ReconnectTimes int
	Status         int
	signal         chan struct{}
}

type BackendOpt func(*Backend)

var backendMod *Backend

func New(opts ...BackendOpt) *Backend {
	b := Backend{
		signal: make(chan struct{}),
	}
	for _, opt := range opts {
		opt(&b)
	}

	clientOpts := MQTT.NewClientOptions()
	for _, b := range global.HostInfoTail.MQTTInfo.BrokerInfo {
		clientOpts.AddBroker(fmt.Sprintf("ssl://%s", b.BrokerIP))
	}
Lei Li's avatar
Lei Li committed
42

Lei Li's avatar
Lei Li committed
43
	// NOTE: 自测使用
Lei Li's avatar
Lei Li committed
44
45
46
	if config.Edition == "dev" {
		clientOpts.AddBroker(fmt.Sprintf("%s:%d", option.Opt.MQTTBrokerURL, option.Opt.MQTTBrokerPort))
	}
Lei Li's avatar
Lei Li committed
47
48
49
50
	clientOpts.SetClientID(global.DeviceSerialNumber)
	clientOpts.SetUsername(global.MQTTUsername)
	clientOpts.SetPassword(global.MQTTPassword)

Lei Li's avatar
Lei Li committed
51
52
53
54
55
56
57
58
	// TLS配置
	tlsConfig, err := newTlsConfig()
	if err != nil {
		l.Error(err)
		return nil
	}
	clientOpts.SetTLSConfig(tlsConfig)

Lei Li's avatar
Lei Li committed
59
60
61
62
63
64
65
66
67
68
69
	// 设置session持久化订阅,基于clientid,在客户端断开连接时topic不会自动删除
	clientOpts.SetCleanSession(false)

	// 设置自动重连
	clientOpts.SetAutoReconnect(true)
	clientOpts.SetMaxReconnectInterval(10 * time.Second)

	// 设置回调函数
	clientOpts.SetOnConnectHandler(connectCallback)
	clientOpts.SetConnectionLostHandler(connectInterruptionCallback)
	clientOpts.SetReconnectingHandler(reconnectingCallback)
Lei Li's avatar
Lei Li committed
70
	clientOpts.SetDefaultPublishHandler(handleSubscribeMsgCallback)
Lei Li's avatar
Lei Li committed
71
72
73
74
75
76
77
78
79
80
81
82
83

	// 初始化客户端
	b.client = MQTT.NewClient(clientOpts)

	backendMod = &b
	return &b
}

func (b *Backend) Start() error {
	b.isRunning = true

	for {
		if token := b.client.Connect(); token.Wait() && token.Error() != nil {
Lei Li's avatar
Lei Li committed
84
			l.Warnf("MQTT init connecting err :%v", token.Error())
Lei Li's avatar
Lei Li committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
			b.Status = global.MQTTFailedToConnect
			b.ReconnectTimes++
		} else {
			l.Info("MQTT init connecting success")
			b.Status = global.MQTTConnected
			break
		}

		time.Sleep(2 * time.Minute)
	}

	go func() {
		for {
			select {
			case msg := <-global.HostInfoTail.MQTTInfo.PublishChan:
				topic := translateTopic(msg.Key)
				if len(topic) > 0 {
					b.client.Publish(topic, 1, false, []byte(msg.Payload))
				}
			case <-b.signal:
Lei Li's avatar
Lei Li committed
105
				l.Info("MQTT exit")
Lei Li's avatar
Lei Li committed
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
				return
			}
		}
	}()
	return nil
}

func (b *Backend) Stop() {
	if b.IsRunning() {
		b.isRunning = false
		b.signal <- struct{}{}
		b.client.Disconnect(250)

	}
}

func (b *Backend) Name() string { return global.BackendModuleName }

func (b *Backend) IsRunning() bool {
	return b.isRunning
}

func connectCallback(client MQTT.Client) {
	l.Info("MQTT connected")
	backendMod.Status = global.MQTTConnected
	// 订阅
	if token := client.Subscribe(global.DeviceSerialNumber+"/publish/#", 1, nil); token.Wait() && token.Error() != nil {
		l.Error(token.Error())
	}
	//if token := client.Subscribe("device/sleep", 1, nil); token.Wait() && token.Error() != nil {
	//	l.Error(token.Error())
	//}
}

func connectInterruptionCallback(client MQTT.Client, err error) {
	l.Infof("MQTT connection interruption err:%s", err)
	backendMod.Status = global.MQTTReConnecting
}

func reconnectingCallback(client MQTT.Client, opts *MQTT.ClientOptions) {
	l.Info("MQTT reconnecting")
	backendMod.ReconnectTimes++
}

Lei Li's avatar
Lei Li committed
150
func handleSubscribeMsgCallback(client MQTT.Client, msg MQTT.Message) {
Lei Li's avatar
Lei Li committed
151
	l.Infof("MQTT Received message from topic %s, %s", msg.Topic(), string(msg.Payload()))
Lei Li's avatar
Lei Li committed
152
153
	if strings.HasPrefix(msg.Topic(), global.SubscribePrefixInfo) {
		key := msg.Topic()[strings.Index(msg.Topic(), global.SubscribePrefixInfo)+len(global.SubscribePrefixInfo):]
Lei Li's avatar
Lei Li committed
154
155
		global.HostInfoTail.MQTTInfo.ConsumeChan <- &global.Message{
			Payload: string(msg.Payload()),
Lei Li's avatar
Lei Li committed
156
			Key:     key,
Lei Li's avatar
Lei Li committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
		}
	}
	//} else if msg.Topic() == "device/sleep" {
	//	mp := make(map[string]interface{})
	//	err := json.Unmarshal(msg.Payload(), &mp)
	//	if err != nil {
	//		l.Errorf("MQTT fail to json Unmarshal, err:%v", err)
	//		return
	//	}
	//	if tmp, ok := mp["sleep"].(string); ok {
	//		s, _ := strconv.Atoi(tmp)
	//		time.Sleep(time.Duration(s) * time.Second)
	//	}
	//	mp["sn"] = global.DeviceSerialNumber
	//	data, _ := json.Marshal(mp)
	//	client.Publish("device/awake", 1, false, data)
	//}
}

func translateTopic(key string) (ret string) {
	if l := strings.Index(key, "agent."); l != -1 && l < len(key) {
		ret = strings.Replace(key[l:], ".", "_", -1)
	}

	return ret
}

func (b *Backend) Receive(msg *global.Message) error {
	return nil
}
Lei Li's avatar
Lei Li committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

func newTlsConfig() (*tls.Config, error) {
	// 配置 TLS 以忽略证书验证
	cfg := new(tls.Config)
	cfg.RootCAs = x509.NewCertPool()

	certPemBytes, err := global.CertFS.ReadFile(global.MyCertPem)
	if err != nil {
		return nil, fmt.Errorf("load cert pem err:%s", err)
	}

	certKeyBytes, err := global.CertFS.ReadFile(global.MyCertKey)
	if err != nil {
		return nil, fmt.Errorf("load key pem err:%s", err)
	}

	cert, err := tls.X509KeyPair(certPemBytes, certKeyBytes)
	if err != nil {
		return nil, fmt.Errorf("parse cert/key err:%s", err)
	}

	cfg.Certificates = append(cfg.Certificates, cert)

	cfg.InsecureSkipVerify = true

	return cfg, nil
}