-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.go
80 lines (69 loc) · 1.72 KB
/
client.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
70
71
72
73
74
75
76
77
78
79
80
package mqtt
import (
"context"
"fmt"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/kubemq-hub/builder/connector/common"
"github.com/kubemq-io/kubemq-targets/config"
"github.com/kubemq-io/kubemq-targets/pkg/logger"
"github.com/kubemq-io/kubemq-targets/types"
)
const (
defaultConnectTimeout = 5 * time.Second
)
type Client struct {
log *logger.Logger
opts options
client mqtt.Client
}
func New() *Client {
return &Client{}
}
func (c *Client) Connector() *common.Connector {
return Connector()
}
func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error {
c.log = log
if c.log == nil {
c.log = logger.NewLogger(cfg.Kind)
}
var err error
c.opts, err = parseOptions(cfg)
if err != nil {
return err
}
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s", c.opts.host))
opts.SetUsername(c.opts.username)
opts.SetPassword(c.opts.password)
opts.SetClientID(c.opts.clientId)
opts.SetConnectTimeout(defaultConnectTimeout)
c.client = mqtt.NewClient(opts)
if token := c.client.Connect(); token.Wait() && token.Error() != nil {
return fmt.Errorf("error connecting to mqtt broker, %w", token.Error())
}
return nil
}
func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) {
meta, ok := c.opts.defaultMetadata()
if !ok {
var err error
meta, err = parseMetadata(req.Metadata)
if err != nil {
return nil, err
}
}
token := c.client.Publish(meta.topic, byte(meta.qos), false, req.Data)
token.Wait()
if token.Error() != nil {
return nil, token.Error()
}
return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil
}
func (c *Client) Stop() error {
if c.client != nil {
c.client.Disconnect(0)
}
return nil
}