1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-04-27 13:48:49 +08:00
b1ackd0t a008440dcc
NOISSUE - MQTT To Publish Payload Only (#1903)
* Publish only message payload

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Use concatenation instead of sprintf as documented

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix tests

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

---------

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>
2023-09-05 15:01:24 +02:00

60 lines
1.2 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt
import (
"context"
"errors"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/mainflux/mainflux/pkg/messaging"
)
var errPublishTimeout = errors.New("failed to publish due to timeout reached")
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(ctx context.Context, topic string, msg *messaging.Message) error {
if topic == "" {
return ErrEmptyTopic
}
// Publish only the payload and not the whole message.
token := pub.client.Publish(topic, qos, false, msg.GetPayload())
if token.Error() != nil {
return token.Error()
}
if ok := token.WaitTimeout(pub.timeout); !ok {
return errPublishTimeout
}
return nil
}
func (pub publisher) Close() error {
pub.client.Disconnect(uint(pub.timeout))
return nil
}