1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-05-08 19:29:17 +08:00
Mainflux.mainflux/coap/observer.go
Dušan Borovčanin c6f7c69798
NOISSUE - Fix CoAP adapter (#1572)
* Revert "NOISSUE - Add nats wrapper for COAP (#1569)"

This reverts commit cc5d5195ab27fa94270ada616487b7053fd9c7bd.

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix CoAP adapter

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Update CoAP observation cancel

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix observe

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix GET handling

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Revert authorization

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Use constants instead of magic numbers

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Remove an empty line

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Extract special observe value to constant

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>
2022-03-30 16:52:10 +02:00

48 lines
1.0 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package coap
import (
"github.com/gogo/protobuf/proto"
"github.com/mainflux/mainflux/pkg/messaging"
broker "github.com/nats-io/nats.go"
)
// Observer represents an internal observer used to handle CoAP observe messages.
type Observer interface {
Cancel() error
}
// NewObserver returns a new Observer instance.
func NewObserver(subject string, c Client, conn *broker.Conn) (Observer, error) {
sub, err := conn.Subscribe(subject, func(m *broker.Msg) {
var msg messaging.Message
if err := proto.Unmarshal(m.Data, &msg); err != nil {
return
}
// There is no error handling, but the client takes care to log the error.
c.SendMessage(msg)
})
if err != nil {
return nil, err
}
ret := &observer{
client: c,
sub: sub,
}
return ret, nil
}
type observer struct {
client Client
sub *broker.Subscription
}
func (o *observer) Cancel() error {
if err := o.sub.Unsubscribe(); err != nil && err != broker.ErrConnectionClosed {
return err
}
return o.client.Cancel()
}