backend.go 4.35 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
package backend
Lei Li's avatar
Lei Li committed
2
3
4
5
6
7

import (
	"fmt"
	"strings"
	"time"

Lei Li's avatar
Lei Li committed
8
	"agent/cmd/agent/config"
Lei Li's avatar
Lei Li committed
9
	"agent/cmd/agent/global"
Lei Li's avatar
Lei Li committed
10
	"agent/cmd/agent/option"
Lei Li's avatar
Lei Li committed
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
	"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
40
41
42
43

	if config.Edition == "dev" {
		clientOpts.AddBroker(fmt.Sprintf("%s:%d", option.Opt.MQTTBrokerURL, option.Opt.MQTTBrokerPort))
	}
Lei Li's avatar
Lei Li committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
	clientOpts.SetClientID(global.DeviceSerialNumber)
	clientOpts.SetUsername(global.MQTTUsername)
	clientOpts.SetPassword(global.MQTTPassword)

	// TODO: TLS配置
	// 设置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
60
	clientOpts.SetDefaultPublishHandler(handleSubscribeMsgCallback)
Lei Li's avatar
Lei Li committed
61
62
63
64
65
66
67
68
69
70
71
72
73

	// 初始化客户端
	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
74
			l.Warnf("MQTT init connecting err :%v", token.Error())
Lei Li's avatar
Lei Li committed
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
			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:
				l.Info("MQTT publish exit")
				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
140
func handleSubscribeMsgCallback(client MQTT.Client, msg MQTT.Message) {
Lei Li's avatar
Lei Li committed
141
	l.Infof("MQTT Received message from topic %s, %s", msg.Topic(), string(msg.Payload()))
Lei Li's avatar
Lei Li committed
142
143
	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
144
145
		global.HostInfoTail.MQTTInfo.ConsumeChan <- &global.Message{
			Payload: string(msg.Payload()),
Lei Li's avatar
Lei Li committed
146
			Key:     key,
Lei Li's avatar
Lei Li committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
		}
	}
	//} 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
}