/
publisher.go
55 lines (45 loc) · 1.09 KB
/
publisher.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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt
import (
"time"
"github.com/MainfluxLabs/mainflux/pkg/messaging"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gogo/protobuf/proto"
)
var _ messaging.Publisher = (*publisher)(nil)
type publisher struct {
client mqtt.Client
timeout time.Duration
}
// NewPublisher returns a new MQTT message publisher.
func NewPublisher(address string, timeout time.Duration) (messaging.Publisher, error) {
client, err := newClient(address, "mqtt-publisher", timeout)
if err != nil {
return nil, err
}
ret := publisher{
client: client,
timeout: timeout,
}
return ret, nil
}
func (pub publisher) Publish(msg messaging.Message) error {
data, err := proto.Marshal(&msg)
if err != nil {
return err
}
token := pub.client.Publish(msg.Subtopic, qos, false, data)
if token.Error() != nil {
return token.Error()
}
ok := token.WaitTimeout(pub.timeout)
if !ok {
return messaging.ErrPublishTimeout
}
return token.Error()
}
func (pub publisher) Close() error {
pub.client.Disconnect(uint(pub.timeout))
return nil
}