|
|
@@ -47,7 +47,9 @@ func NewMqttHandlerhl(server, user, password string, timeout uint) *MqttHandlerh
|
|
|
return nil
|
|
|
}
|
|
|
o.mqtt = client
|
|
|
- err = client.Connect(o.Ctx())
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ err = client.Connect(ctx)
|
|
|
return &o
|
|
|
}
|
|
|
|
|
|
@@ -69,7 +71,9 @@ func (o *MqttHandlerhl) GetWill() (string, string) {
|
|
|
|
|
|
func (o *MqttHandlerhl) Connect() error {
|
|
|
if !o.mqtt.IsConnected() {
|
|
|
- return o.mqtt.Connect(o.Ctx())
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.Connect(ctx)
|
|
|
}
|
|
|
return nil
|
|
|
}
|
|
|
@@ -79,15 +83,21 @@ func (o *MqttHandlerhl) IsConnected() bool {
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) Publish(topic string, payload []byte, qos mqtt.QOS) error {
|
|
|
- return o.mqtt.Publish(o.Ctx(), topic, payload, qos)
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.Publish(ctx, topic, payload, qos)
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) PublishString(topic string, payload string, qos mqtt.QOS) error {
|
|
|
- return o.mqtt.PublishString(o.Ctx(), topic, payload, qos)
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.PublishString(ctx, topic, payload, qos)
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) PublishJSON(topic string, payload interface{}, qos mqtt.QOS) error {
|
|
|
- return o.mqtt.PublishJSON(o.Ctx(), topic, payload, qos)
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.PublishJSON(ctx, topic, payload, qos)
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) Subscribe(topic string, qos mqtt.QOS) error {
|
|
|
@@ -96,7 +106,9 @@ func (o *MqttHandlerhl) Subscribe(topic string, qos mqtt.QOS) error {
|
|
|
if _, ok := o.mapTopics[topic]; !ok {
|
|
|
o.mapTopics[topic] = qos
|
|
|
}
|
|
|
- return o.mqtt.Subscribe(o.Ctx(), topic, qos)
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.Subscribe(ctx, topic, qos)
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) Unsubscribe(ctx context.Context, topic string) error {
|
|
|
@@ -105,14 +117,15 @@ func (o *MqttHandlerhl) Unsubscribe(ctx context.Context, topic string) error {
|
|
|
if _, ok := o.mapTopics[topic]; ok {
|
|
|
delete(o.mapTopics, topic)
|
|
|
}
|
|
|
- return o.mqtt.Unsubscribe(o.Ctx(), topic)
|
|
|
+ ctx, cancel := o.Ctx()
|
|
|
+ defer cancel()
|
|
|
+ return o.mqtt.Unsubscribe(ctx, topic)
|
|
|
}
|
|
|
|
|
|
func (o *MqttHandlerhl) Handle(topic string, handler mqtt.MessageHandler) mqtt.Route {
|
|
|
return o.mqtt.Handle(topic, handler)
|
|
|
}
|
|
|
|
|
|
-func (o *MqttHandlerhl) Ctx() context.Context {
|
|
|
- ctx, _ := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(o.Timeout))
|
|
|
- return ctx
|
|
|
+func (o *MqttHandlerhl) Ctx() (context.Context, context.CancelFunc) {
|
|
|
+ return context.WithTimeout(context.Background(), time.Millisecond*time.Duration(o.Timeout))
|
|
|
}
|