github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/mqtt/mqtt_client.go (about)

     1  package mqtt
     2  
     3  import (
     4  	"time"
     5  
     6  	mqtt "github.com/eclipse/paho.mqtt.golang"
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  type Client struct {
    11  	cid         string // cid client id
    12  	topic       string // topic registered topic
    13  	qos         QOS    // qos should be 0, 1 or 2
    14  	retain      bool
    15  	pubTimeout  time.Duration
    16  	subTimeout  time.Duration
    17  	connTimeout time.Duration
    18  	cli         mqtt.Client
    19  }
    20  
    21  func (c *Client) Cid() string { return c.cid }
    22  
    23  func (c *Client) WithTopic(topic string) *Client {
    24  	c2 := *c
    25  	c2.topic = topic
    26  	return &c2
    27  }
    28  
    29  func (c *Client) WithQoS(qos QOS) *Client {
    30  	c2 := *c
    31  	c2.qos = qos
    32  	return &c2
    33  }
    34  
    35  func (c *Client) WithSubTimeout(timeout time.Duration) *Client {
    36  	c2 := *c
    37  	c2.subTimeout = timeout
    38  	return &c2
    39  }
    40  
    41  func (c *Client) WithConnTimeout(timeout time.Duration) *Client {
    42  	c2 := *c
    43  	c2.connTimeout = timeout
    44  	return &c2
    45  }
    46  
    47  func (c *Client) WithRetain(retain bool) *Client {
    48  	c2 := *c
    49  	c2.retain = retain
    50  	return &c2
    51  }
    52  
    53  func (c *Client) connect() error {
    54  	return c.wait(c.cli.Connect(), "connect", c.connTimeout)
    55  }
    56  
    57  func (c *Client) wait(tok mqtt.Token, act string, timeout time.Duration) error {
    58  	waited := false
    59  	if timeout == 0 {
    60  		waited = tok.Wait()
    61  	} else {
    62  		waited = tok.WaitTimeout(timeout)
    63  	}
    64  	if !waited {
    65  		return errors.New(act + " timeout")
    66  	}
    67  	if err := tok.Error(); err != nil {
    68  		return errors.Wrap(err, act+" error")
    69  	}
    70  	return nil
    71  }
    72  
    73  func (c *Client) Publish(payload interface{}) error {
    74  	if c.topic == "" {
    75  		return errors.New("topic is empty")
    76  	}
    77  	return c.wait(
    78  		c.cli.Publish(c.topic, byte(c.qos), c.retain, payload),
    79  		"pub",
    80  		c.pubTimeout,
    81  	)
    82  }
    83  
    84  func (c *Client) Subscribe(handler mqtt.MessageHandler) error {
    85  	if c.topic == "" {
    86  		return errors.New("topic is empty")
    87  	}
    88  	return c.wait(
    89  		c.cli.Subscribe(c.topic, byte(c.qos), handler),
    90  		"sub",
    91  		c.subTimeout,
    92  	)
    93  }
    94  
    95  func (c *Client) Unsubscribe() error {
    96  	if c.topic == "" {
    97  		return errors.New("topic is empty")
    98  	}
    99  	return c.wait(
   100  		c.cli.Unsubscribe(c.topic),
   101  		"Unsub",
   102  		c.subTimeout,
   103  	)
   104  }