1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-05-02 22:17:10 +08:00
__touk__ f8ce94e9bb
NOISSUE - Refactor MQTT subscriber (#1561)
* correct suscriber interface validator + refactore token error handling

Signed-off-by: tzzed <zerouali.t@gmail.com>

* apply review suggestion

Signed-off-by: tzzed <zerouali.t@gmail.com>

Co-authored-by: Dušan Borovčanin <dusan.borovcanin@mainflux.com>
2022-02-09 10:19:09 +01:00

50 lines
997 B
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt
import (
"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, timeout)
if err != nil {
return nil, err
}
ret := publisher{
client: client,
timeout: timeout,
}
return ret, nil
}
func (pub publisher) Publish(topic string, msg messaging.Message) error {
token := pub.client.Publish(topic, qos, false, msg.Payload)
if token.Error() != nil {
return token.Error()
}
ok := token.WaitTimeout(pub.timeout)
if !ok {
return errPublishTimeout
}
return token.Error()
}