76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
package mqttx
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
)
|
|
|
|
var (
|
|
ErrPublishWaitTimeout = errors.New("publish wait timeout")
|
|
ErrSubscribeWaitTimeout = errors.New("subscribe wait timeout")
|
|
)
|
|
|
|
func NewClient(o *ClientOptions) *Client {
|
|
opts := mqtt.NewClientOptions()
|
|
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", o.Host, o.Port))
|
|
opts.SetClientID(o.ClientID)
|
|
opts.SetUsername(o.Username)
|
|
opts.SetPassword(o.Password)
|
|
opts.OnConnect = o.OnConnect
|
|
opts.OnConnectionLost = o.OnConnectionLost
|
|
opts.OnReconnecting = o.OnReconnecting
|
|
|
|
return &Client{
|
|
id: o.ClientID,
|
|
Client: mqtt.NewClient(opts),
|
|
}
|
|
}
|
|
|
|
type Client struct {
|
|
id string
|
|
mqtt.Client
|
|
}
|
|
|
|
func (c *Client) GetId() string {
|
|
return c.id
|
|
}
|
|
|
|
func (c *Client) Connect() error {
|
|
t := c.Client.Connect()
|
|
t.Wait()
|
|
return t.Error()
|
|
}
|
|
|
|
func (c *Client) Publish(topic PublishTopic) error {
|
|
t := c.Client.Publish(topic.Name, topic.Qos, topic.Retained, topic.Payload)
|
|
if topic.WaitTimeout > 0 {
|
|
if !t.WaitTimeout(topic.WaitTimeout) {
|
|
return ErrPublishWaitTimeout
|
|
}
|
|
} else {
|
|
t.Wait()
|
|
}
|
|
return t.Error()
|
|
}
|
|
|
|
func (c *Client) Subscribe(topic SubscribeTopic) error {
|
|
t := c.Client.Subscribe(topic.Name, topic.Qos, topic.MessageHandler)
|
|
if topic.WaitTimeout > 0 {
|
|
if !t.WaitTimeout(topic.WaitTimeout) {
|
|
return ErrSubscribeWaitTimeout
|
|
}
|
|
} else {
|
|
t.Wait()
|
|
}
|
|
return t.Error()
|
|
}
|
|
|
|
type ClientOptions struct {
|
|
Host string
|
|
Port int
|
|
|
|
mqtt.ClientOptions
|
|
}
|