mqtt.go 8.63 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
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
/*
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
	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
}

// 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,
	}
	mq.msgInTopic = make(map[string]chan schemas.MQTTMessage)
	mq.msgIn = make(chan schemas.MQTTMessage)
	return
}

// Subscribe subscribes to a topic
func (mq *MQTT) Subscribe(topic string, qos int) (err error) {
	err = mq.client.subscribe(mq, topic, qos)
	return
}

// SendMessage sends a message
func (mq *MQTT) SendMessage(msg schemas.MQTTMessage, qos int) (err error) {
	err = mq.client.publish(msg, qos)
	if err != nil {
		return
	}
98
	err = mq.cmapLogger.NewLog("msg", "Sent MQTT message: "+string(msg.Content), string(msg.Content))
Stefan Dähling's avatar
Stefan Dähling committed
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
	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) {
	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) {
	err = nil
	msg = <-mq.msgIn
	return
}

// newIncomingMQTTMessage adds message to channel for incoming messages
func (mq *MQTT) newIncomingMQTTMessage(msg schemas.MQTTMessage) {
134
	mq.cmapLogger.NewLog("msg", "Received MQTT message: "+string(msg.Content), string(msg.Content))
Stefan Dähling's avatar
Stefan Dähling committed
135
136
137
138
139
140
141
142
143
144
145
146
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
177
178
179
180
181
182
183
184
185
186
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
285
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
	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()
	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)
	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) {
	if cli.active {
		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
				}
			}
			if !subscribed {
				ag = append(ag, mq)
				cli.mutex.Lock()
				cli.subscription[topic] = ag
				cli.mutex.Unlock()
			}
		} 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
}

// 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)
			}
		}
	}
}