MQTT: make Monitor first-read cancellable via context (#31116)
This commit is contained in:
parent
aa7b5103dd
commit
2294066b27
4 changed files with 44 additions and 3 deletions
|
|
@ -12,6 +12,7 @@ import (
|
|||
// Mqtt provider
|
||||
type Mqtt struct {
|
||||
*getter
|
||||
ctx context.Context
|
||||
log *util.Logger
|
||||
client *mqtt.Client
|
||||
topic string
|
||||
|
|
@ -49,7 +50,7 @@ func NewMqttPluginFromConfig(ctx context.Context, other map[string]any) (Plugin,
|
|||
return nil, err
|
||||
}
|
||||
|
||||
m := NewMqtt(log, client, cc.Topic, cc.Timeout).WithScale(cc.Scale).WithPayload(cc.Payload)
|
||||
m := NewMqtt(log, client, cc.Topic, cc.Timeout).WithContext(ctx).WithScale(cc.Scale).WithPayload(cc.Payload)
|
||||
if cc.Retained {
|
||||
m = m.WithRetained()
|
||||
}
|
||||
|
|
@ -65,6 +66,7 @@ func NewMqttPluginFromConfig(ctx context.Context, other map[string]any) (Plugin,
|
|||
// NewMqtt creates mqtt provider for given topic
|
||||
func NewMqtt(log *util.Logger, client *mqtt.Client, topic string, timeout time.Duration) *Mqtt {
|
||||
m := &Mqtt{
|
||||
ctx: context.Background(),
|
||||
log: log,
|
||||
client: client,
|
||||
topic: topic,
|
||||
|
|
@ -76,6 +78,12 @@ func NewMqtt(log *util.Logger, client *mqtt.Client, topic string, timeout time.D
|
|||
return m
|
||||
}
|
||||
|
||||
// WithContext sets a context that can cancel the blocking first-read wait
|
||||
func (m *Mqtt) WithContext(ctx context.Context) *Mqtt {
|
||||
m.ctx = ctx
|
||||
return m
|
||||
}
|
||||
|
||||
// WithPayload adds payload for setters
|
||||
func (m *Mqtt) WithPayload(payload string) *Mqtt {
|
||||
m.payload = payload
|
||||
|
|
@ -103,6 +111,7 @@ func (p *Mqtt) WithPipeline(pipeline *pipeline.Pipeline) *Mqtt {
|
|||
// newReceiver creates a msgHandler and subscribes it to the topic.
|
||||
func (m *Mqtt) newReceiver() (*msgHandler, error) {
|
||||
h := &msgHandler{
|
||||
ctx: m.ctx,
|
||||
topic: m.topic,
|
||||
pipeline: m.pipeline,
|
||||
val: util.NewMonitor[string](m.timeout),
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/evcc-io/evcc/plugin/pipeline"
|
||||
"github.com/evcc-io/evcc/util"
|
||||
)
|
||||
|
||||
type msgHandler struct {
|
||||
ctx context.Context
|
||||
topic string
|
||||
pipeline *pipeline.Pipeline
|
||||
val *util.Monitor[string]
|
||||
|
|
@ -17,7 +20,7 @@ func (h *msgHandler) receive(payload string) {
|
|||
|
||||
// hasValue returned the received and processed payload as string
|
||||
func (h *msgHandler) hasValue() (string, error) {
|
||||
payload, err := h.val.Get()
|
||||
payload, err := h.val.GetContext(h.ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue