mqtt.go 10.9 KB
Newer Older
Stefan Dähling's avatar
Stefan Dähling committed
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
/*
Copyright 2020 Institute for Automation of Complex Power Systems,
E.ON Energy Research Center, RWTH Aachen University

This project is licensed under either of
- Apache License, Version 2.0
- MIT License
at your option.

Apache License, Version 2.0:

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package agency

import (
	"errors"
	"log"
	"os"
	"strconv"
	"sync"

	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/schemas"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

// MQTT provides functions to subscribe and publish via mqtt
type MQTT struct {
	client     *mqttClient
	mutex      *sync.Mutex                         // mutex for message inbox map
Stefan Dähling's avatar
Stefan Dähling committed
62
	subTopic   map[string]interface{}              // subscribed topics
Stefan Dähling's avatar
Stefan Dähling committed
63
64
65
66
67
68
	msgInTopic map[string]chan schemas.MQTTMessage // message inbox for messages with specified topic
	msgIn      chan schemas.MQTTMessage            // mqtt message inbox
	agentID    int
	cmapLogger *Logger
	logError   *log.Logger
	logInfo    *log.Logger
69
	active     bool
Stefan Dähling's avatar
Stefan Dähling committed
70
71
72
73
74
75
76
77
78
79
80
81
}

// newMQTT returns a new pubsub connector of type mqtt
func newMQTT(agentID int, cli *mqttClient, cmaplog *Logger, logErr *log.Logger,
	logInf *log.Logger) (mq *MQTT) {
	mq = &MQTT{
		client:     cli,
		mutex:      &sync.Mutex{},
		agentID:    agentID,
		cmapLogger: cmaplog,
		logError:   logErr,
		logInfo:    logInf,
82
		active:     true,
Stefan Dähling's avatar
Stefan Dähling committed
83
	}
Stefan Dähling's avatar
Stefan Dähling committed
84
	mq.subTopic = make(map[string]interface{})
Stefan Dähling's avatar
Stefan Dähling committed
85
86
87
88
89
	mq.msgInTopic = make(map[string]chan schemas.MQTTMessage)
	mq.msgIn = make(chan schemas.MQTTMessage)
	return
}

90
91
// close closes the mqtt
func (mq *MQTT) close() {
Stefan Dähling's avatar
Stefan Dähling committed
92
93
94
	for t := range mq.subTopic {
		mq.Unsubscribe(t)
	}
95
	mq.mutex.Lock()
Stefan Dähling's avatar
Stefan Dähling committed
96
	mq.logInfo.Println("Closing MQTT of agent ", mq.agentID)
97
98
99
100
101
	mq.active = false
	mq.mutex.Unlock()
	return
}

Stefan Dähling's avatar
Stefan Dähling committed
102
103
// Subscribe subscribes to a topic
func (mq *MQTT) Subscribe(topic string, qos int) (err error) {
104
105
106
107
108
109
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
110
111
112
113
114
115
116
	_, ok := mq.subTopic[topic]
	mq.mutex.Unlock()
	if ok {
		return
	}
	mq.mutex.Lock()
	mq.subTopic[topic] = nil
117
	mq.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
118
119
120
121
	err = mq.client.subscribe(mq, topic, qos)
	return
}

Stefan Dähling's avatar
Stefan Dähling committed
122
123
124
125
126
127
128
129
// Unsubscribe unsubscribes a topic
func (mq *MQTT) Unsubscribe(topic string) (err error) {
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
130
131
132
133
134
135
136
	_, ok := mq.subTopic[topic]
	mq.mutex.Unlock()
	if !ok {
		return
	}
	mq.mutex.Lock()
	delete(mq.subTopic, topic)
Stefan Dähling's avatar
Stefan Dähling committed
137
138
139
140
141
	mq.mutex.Unlock()
	err = mq.client.unsubscribe(mq, topic)
	return
}

Stefan Dähling's avatar
Stefan Dähling committed
142
143
// SendMessage sends a message
func (mq *MQTT) SendMessage(msg schemas.MQTTMessage, qos int) (err error) {
144
145
146
147
148
149
150
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}
	mq.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
151
152
153
154
	err = mq.client.publish(msg, qos)
	if err != nil {
		return
	}
155
	err = mq.cmapLogger.NewLog("msg", "Sent MQTT message: "+string(msg.Content), string(msg.Content))
Stefan Dähling's avatar
Stefan Dähling committed
156
157
158
159
160
161
162
163
164
165
166
167
168
	return
}

// NewMessage returns a new initiaized message
func (mq *MQTT) NewMessage(topic string, content []byte) (msg schemas.MQTTMessage, err error) {
	msg.Topic = topic
	msg.Content = content
	err = nil
	return
}

// RecvMessages retrieves all messages since last call of this function
func (mq *MQTT) RecvMessages() (num int, msgs []schemas.MQTTMessage, err error) {
169
170
171
172
173
174
175
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}
	mq.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
	num = 0
	err = nil
	for {
		select {
		case msgtemp := <-mq.msgIn:
			msgs = append(msgs, msgtemp)
			num++
		default:
			return
		}
	}
}

// RecvMessageWait retrieves next message and blocks if no message is available
func (mq *MQTT) RecvMessageWait() (msg schemas.MQTTMessage, err error) {
191
192
193
194
195
196
197
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}
	mq.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
198
199
200
201
202
203
204
	err = nil
	msg = <-mq.msgIn
	return
}

// newIncomingMQTTMessage adds message to channel for incoming messages
func (mq *MQTT) newIncomingMQTTMessage(msg schemas.MQTTMessage) {
205
206
207
208
209
210
	mq.mutex.Lock()
	if !mq.active {
		mq.mutex.Unlock()
		return
	}
	mq.mutex.Unlock()
211
	mq.cmapLogger.NewLog("msg", "Received MQTT message: "+string(msg.Content), string(msg.Content))
Stefan Dähling's avatar
Stefan Dähling committed
212
213
214
215
216
217
218
219
220
221
222
223
224
	mq.mutex.Lock()
	inbox, ok := mq.msgInTopic[msg.Topic]
	mq.mutex.Unlock()
	if ok {
		inbox <- msg
	} else {
		mq.msgIn <- msg
	}
	return
}

func (mq *MQTT) registerTopicChannel(topic string, topicChan chan schemas.MQTTMessage) (err error) {
	mq.mutex.Lock()
225
226
227
228
229
230
	if !mq.active {
		mq.mutex.Unlock()
		err = errors.New("mqtt not active")
		return
	}

Stefan Dähling's avatar
Stefan Dähling committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
	if _, ok := mq.msgInTopic[topic]; !ok {
		mq.msgInTopic[topic] = topicChan
	} else {
		err = errors.New("topic is already handled")
	}
	mq.mutex.Unlock()
	return
}

func (mq *MQTT) deregisterTopicChannel(topic string) (err error) {
	mq.mutex.Lock()
	if _, ok := mq.msgInTopic[topic]; ok {
		delete(mq.msgInTopic, topic)
	} else {
		err = errors.New("topic is not handled")
	}
	mq.mutex.Unlock()
	return
}

// mqttClient is the agency client for mqtt
type mqttClient struct {
	client       mqtt.Client              // mqtt client
	brokerSvc    string                   // name of the mqtt broker service
	brokerPort   int                      // port of the mqtt broker
	msgIn        chan schemas.MQTTMessage // mqtt message inbox
	name         string                   // agency name
	active       bool                     // indicates if mqtt is active (switch via env)
	mutex        *sync.Mutex              // mutex for message inbox map
	subscription map[string][]*MQTT       // map for subscription topics to agents' mqtt object
	// numDeliverer int                      // number of go routines for delivery
	logError *log.Logger
	logInfo  *log.Logger
}

// newMQTTClient creates a new mqtt agency client
func newMQTTClient(svc string, port int, name string, logErr *log.Logger,
	logInf *log.Logger) (cli *mqttClient) {
	cli = &mqttClient{
		brokerSvc:  svc,
		brokerPort: port,
		name:       name,
		mutex:      &sync.Mutex{},
		active:     false,
		logError:   logErr,
		logInfo:    logInf,
	}
	act := os.Getenv("CLONEMAP_MQTT")
	if act == "ON" {
		cli.active = true
	}
	cli.msgIn = make(chan schemas.MQTTMessage, 1000)
	cli.subscription = make(map[string][]*MQTT)
	cli.logInfo.Println("Created new MQTT client; status: ", cli.active)
Stefan Dähling's avatar
Stefan Dähling committed
285
	cli.init()
Stefan Dähling's avatar
Stefan Dähling committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
	return
}

func (cli *mqttClient) init() (err error) {
	if cli.active {
		opts := mqtt.NewClientOptions().AddBroker("tcp://" + cli.brokerSvc + ":" +
			strconv.Itoa(cli.brokerPort)).SetClientID(cli.name)
		opts.SetDefaultPublishHandler(cli.newIncomingMQTTMessage)
		cli.client = mqtt.NewClient(opts)
		if token := cli.client.Connect(); token.Wait() && token.Error() != nil {
			err = errors.New("MQTTInitError")
			return
		}
		for i := 0; i < 3; i++ {
			go cli.deliverMsgs()
		}
		// cli.numDeliverer = 3
	}
	return
}

func (cli *mqttClient) close() (err error) {
	if cli.active {
		cli.logInfo.Println("Disconnecting MQTT client")
		cli.client.Disconnect(250)
	}
	err = nil
	return
}

// newIncomingMQTTMessage adds message to channel for incoming messages
func (cli *mqttClient) newIncomingMQTTMessage(client mqtt.Client, msg mqtt.Message) {
	var mqttMsg schemas.MQTTMessage
	mqttMsg.Content = msg.Payload()
	mqttMsg.Topic = msg.Topic()
	cli.msgIn <- mqttMsg
	return
}

// subscribe subscribes to specified topics
func (cli *mqttClient) subscribe(mq *MQTT, topic string, qos int) (err error) {
Stefan Dähling's avatar
Stefan Dähling committed
327
328
329
330
331
332
333
334
335
336
337
338
	if !cli.active {
		return
	}
	cli.mutex.Lock()
	ag, ok := cli.subscription[topic]
	cli.mutex.Unlock()
	if ok {
		subscribed := false
		for i := range ag {
			if ag[i].agentID == mq.agentID {
				subscribed = true
				break
Stefan Dähling's avatar
Stefan Dähling committed
339
			}
Stefan Dähling's avatar
Stefan Dähling committed
340
341
		}
		if !subscribed {
Stefan Dähling's avatar
Stefan Dähling committed
342
343
344
345
346
			ag = append(ag, mq)
			cli.mutex.Lock()
			cli.subscription[topic] = ag
			cli.mutex.Unlock()
		}
Stefan Dähling's avatar
Stefan Dähling committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
	} else {
		cli.mutex.Lock()
		token := cli.client.Subscribe(topic, byte(qos), nil)
		cli.mutex.Unlock()
		if token.Wait() && token.Error() != nil {
			err = token.Error()
			return
		}
		ag = make([]*MQTT, 0)
		ag = append(ag, mq)
		cli.mutex.Lock()
		cli.subscription[topic] = ag
		cli.mutex.Unlock()
	}
	// cli.mutex.Lock()
	// numDel := len(cli.subscription) / 25
	// if numDel > cli.numDeliverer {
	// 	for i := 0; i < numDel-cli.numDeliverer; i++ {
	// 		go cli.deliverMsgs()
	// 	}
	// 	cli.numDeliverer = numDel
	// }
	// cli.mutex.Unlock()

	return
}

// unsubscribe to a topic
func (cli *mqttClient) unsubscribe(mq *MQTT, topic string) (err error) {
	if !cli.active {
		return
	}
	cli.mutex.Lock()
	ag, ok := cli.subscription[topic]
	cli.mutex.Unlock()
	if !ok {
		return
	}
	index := -1
	for i := range ag {
		if mq.agentID == ag[i].agentID {
			index = i
			break
		}
	}
	if index == -1 {
		return
	}
	if index == 0 && len(ag) == 1 {
		// agent is the only one who has subscribed -> unsubscribe
		delete(cli.subscription, topic)
		token := cli.client.Unsubscribe(topic)
		if token.Wait() && token.Error() != nil {
			err = token.Error()
			return
		}
	} else {
		// remove agent from list of subscribed agents
		ag[index] = ag[len(ag)-1]
		ag[len(ag)-1] = nil
		ag = ag[:len(ag)-1]
		cli.mutex.Lock()
		cli.subscription[topic] = ag
		cli.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
	}
	return
}

// publish sends a message
func (cli *mqttClient) publish(msg schemas.MQTTMessage, qos int) (err error) {
	if cli.active {
		token := cli.client.Publish(msg.Topic, byte(qos), false, msg.Content)
		token.Wait()
	}
	return
}

// deliverMsg delivers incoming messages to agents according to their topic
func (cli *mqttClient) deliverMsgs() {
	var msg schemas.MQTTMessage
	for {
		msg = <-cli.msgIn
		cli.mutex.Lock()
		ag, ok := cli.subscription[msg.Topic]
		cli.mutex.Unlock()
		if ok {
			for i := range ag {
				ag[i].newIncomingMQTTMessage(msg)
			}
		}
	}
}