-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt-eclipse.go
69 lines (54 loc) · 1.9 KB
/
mqtt-eclipse.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
package carrier
import (
"log"
"github.com/eclipse/paho.mqtt.golang"
)
// EclipseClient manage all MQTT client actions
type EclipseClient struct {
client mqtt.Client
config *EclipseConfigModel
}
var (
// EclipseClientSessionMapping singleton pattern
EclipseClientSessionMapping = make(map[string]*EclipseClient)
)
// NewEclipseClient init new instance
func NewEclipseClient(config *EclipseConfigModel) IMQTT {
configHashed := hashObject(config)
currentEclipseClientSession := EclipseClientSessionMapping[configHashed]
if currentEclipseClientSession == nil {
currentEclipseClientSession = &EclipseClient{nil, nil}
clientOptions := mqtt.NewClientOptions().AddBroker(config.URL).SetClientID(config.ClientID).SetUsername(config.Username).SetPassword(config.Password)
client := mqtt.NewClient(clientOptions)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Printf("MQTT client: can't connect to broker of %v\n", token.Error())
}
currentEclipseClientSession.client = client
currentEclipseClientSession.config = config
EclipseClientSessionMapping[configHashed] = currentEclipseClientSession
log.Println("MQTT client: connected")
}
return currentEclipseClientSession
}
// Publish message to channel
func (ec *EclipseClient) Publish(topic, message string) error {
if token := ec.client.Publish(topic, 0, false, message); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
// Subscribe message from channel
func (ec *EclipseClient) Subscribe(topic string, messageHandler mqtt.MessageHandler) error {
if token := ec.client.Subscribe(topic, 0, messageHandler); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
// IsConnected return connection state
func (ec *EclipseClient) IsConnected() bool {
return ec.client.IsConnected()
}
// End this communication
func (ec *EclipseClient) End() {
ec.client.Disconnect(1000) // 1 second
}