canopus

package module
v0.0.0-...-e374f5b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2018 License: Apache-2.0 Imports: 27 Imported by: 74

README

Canopus

GoDoc Build Status Coverage Status Go Report Card

Canopus is a client/server implementation of the Constrained Application Protocol (CoAP)

Updates

25.11.2016

I've added basic dTLS Support based on [Julien Vermillard's][JVERMILLARD] [implementation][NATIVEDTLS]. Thanks Julien! It should now support PSK-based authentication. I've also gone ahead and refactored the APIs to make it that bit more Go idiomatic. [JVERMILLARD]: https://github.com/jvermillard [NATIVEDTLS]: https://github.com/jvermillard/nativedtls

Building and running

  1. git submodule update --init --recursive
  2. cd openssl
  3. ./config && make
  4. You should then be able to run the examples in the /examples folder
Simple Example
	// Server
	// See /examples/simple/server/main.go
	server := canopus.NewServer()

	server.Get("/hello", func(req canopus.Request) canopus.Response {
		msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
		msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())

		res := canopus.NewResponse(msg, nil)
		return res
	})

	server.ListenAndServe(":5683")

	// Client
	// See /examples/simple/client/main.go
	conn, err := canopus.Dial("localhost:5683")
	if err != nil {
		panic(err.Error())
	}

	req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID()).(*canopus.CoapRequest)
	req.SetStringPayload("Hello, canopus")
	req.SetRequestURI("/hello")

	resp, err := conn.Send(req)
	if err != nil {
		panic(err.Error())
	}

	fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
Observe / Notify
	// Server
	// See /examples/observe/server/main.go
	server := canopus.NewServer()
	server.Get("/watch/this", func(req canopus.Request) canopus.Response {
		msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), canopus.NewPlainTextPayload("Acknowledged"))
		res := canopus.NewResponse(msg, nil)

		return res
	})

	ticker := time.NewTicker(3 * time.Second)
	go func() {
		for {
			select {
			case <-ticker.C:
				changeVal := strconv.Itoa(rand.Int())
				fmt.Println("[SERVER << ] Change of value -->", changeVal)

				server.NotifyChange("/watch/this", changeVal, false)
			}
		}
	}()

	server.OnObserve(func(resource string, msg canopus.Message) {
		fmt.Println("[SERVER << ] Observe Requested for " + resource)
	})

	server.ListenAndServe(":5683")

	// Client
	// See /examples/observe/client/main.go
	conn, err := canopus.Dial("localhost:5683")

	tok, err := conn.ObserveResource("/watch/this")
	if err != nil {
		panic(err.Error())
	}

	obsChannel := make(chan canopus.ObserveMessage)
	done := make(chan bool)
	go conn.Observe(obsChannel)

	notifyCount := 0
	for {
		select {
		case obsMsg, _ := <-obsChannel:
			if notifyCount == 5 {
				fmt.Println("[CLIENT >> ] Canceling observe after 5 notifications..")
				go conn.CancelObserveResource("watch/this", tok)
				go conn.StopObserve(obsChannel)
				return
			} else {
				notifyCount++
				// msg := obsMsg.Msg\
				resource := obsMsg.GetResource()
				val := obsMsg.GetValue()

				fmt.Println("[CLIENT >> ] Got Change Notification for resource and value: ", notifyCount, resource, val)
			}
		}
	}
dTLS with PSK
	// Server
	// See /examples/dtls/simple-psk/server/main.go
	server := canopus.NewServer()

	server.Get("/hello", func(req canopus.Request) canopus.Response {
		msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
		msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
		res := canopus.NewResponse(msg, nil)

		return res
	})

	server.HandlePSK(func(id string) []byte {
		return []byte("secretPSK")
	})

	server.ListenAndServeDTLS(":5684")

	// Client
	// See /examples/dtls/simple-psk/client/main.go
	conn, err := canopus.DialDTLS("localhost:5684", "canopus", "secretPSK")
	if err != nil {
		panic(err.Error())
	}

	req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
	req.SetStringPayload("Hello, canopus")
	req.SetRequestURI("/hello")

	resp, err := conn.Send(req)
	if err != nil {
		panic(err.Error())
	}

	fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
CoAP-CoAP Proxy
	// Server
	// See /examples/proxy/coap/server/main.go
	server := canopus.NewServer()

	server.Get("/proxycall", func(req canopus.Request) canopus.Response {
		msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
		msg.SetStringPayload("Data from :5685 -- " + req.GetMessage().GetPayload().String())
		res := canopus.NewResponse(msg, nil)

		return res
	})
	server.ListenAndServe(":5685")

	// Proxy Server
	// See /examples/proxy/coap/proxy/main.go
	server := canopus.NewServer()
	server.ProxyOverCoap(true)

	server.Get("/proxycall", func(req canopus.Request) canopus.Response {
		canopus.PrintMessage(req.GetMessage())
		msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
		msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
		res := canopus.NewResponse(msg, nil)

		return res
	})
	server.ListenAndServe(":5683")

	// Client
	// See /examples/proxy/coap/client/main.go
	conn, err := canopus.Dial("localhost:5683")
	if err != nil {
		panic(err.Error())
	}

	req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
	req.SetProxyURI("coap://localhost:5685/proxycall")

	resp, err := conn.Send(req)
	if err != nil {
		println("err", err)
	}
	canopus.PrintMessage(resp.GetMessage())
CoAP-HTTP Proxy
	// Server
	// See /examples/proxy/http/server/main.go
	server := canopus.NewServer()
	server.ProxyOverHttp(true)

	server.ListenAndServe(":5683")

	// Client
	// See /examples/proxy/http/client/main.go
	conn, err := canopus.Dial("localhost:5683")
	if err != nil {
		panic(err.Error())
	}

	req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
	req.SetProxyURI("https://httpbin.org/get")

	resp, err := conn.Send(req)
	if err != nil {
		println("err", err)
	}
	canopus.PrintMessage(resp.GetMessage())

Documentation

Index

Constants

View Source
const (
	MessageConfirmable    = 0
	MessageNonConfirmable = 1
	MessageAcknowledgment = 2
	MessageReset          = 3
)

Types of Messages

View Source
const (
	DataHeader     = 0
	DataCode       = 1
	DataMsgIDStart = 2
	DataMsgIDEnd   = 4
	DataTokenStart = 4
)

Fragments/parts of a CoAP Message packet

View Source
const (
	MethodGet     = "GET"
	MethodPut     = "PUT"
	MethodPost    = "POST"
	MethodDelete  = "DELETE"
	MethodOptions = "OPTIONS"
	MethodPatch   = "PATCH"
)
View Source
const (
	SecNoSec        = "NoSec"
	SecPreSharedKey = "PreSharedKey"
	SecRawPublicKey = "RawPublicKey"
	SecCertificate  = "Certificate"
)

Security Options

View Source
const CoapDefaultHost = ""
View Source
const CoapDefaultPort = 5683
View Source
const CoapsDefaultPort = 5684
View Source
const DefaultAckRandomFactor = 1.5
View Source
const DefaultAckTimeout = 2
View Source
const DefaultLeisure = 5
View Source
const DefaultMaxRetransmit = 4
View Source
const DefaultNStart = 1
View Source
const DefaultProbingRate = 1
View Source
const MaxPacketSize = 1500
View Source
const MessageIDPurgeDuration = 60

MessageIDPurgeDuration defines the number of seconds before a MessageID Purge is initiated

View Source
const PayloadMarker = 0xff
View Source
const UDP = "udp"

Variables

View Source
var CurrentMessageID = 0

CurrentMessageID stores the current message id used/generated for messages

View Source
var DTLS_CLIENT_CONNECTIONS = make(map[int32]*DTLSConnection)
View Source
var DTLS_SERVER_SESSIONS = make(map[int32]*DTLSServerSession)
View Source
var ErrInvalidCoapVersion = errors.New("Invalid CoAP version. Should be 1.")
View Source
var ErrInvalidTokenLength = errors.New("Invalid Token Length ( > 8)")
View Source
var ErrMessageSizeTooLongBlockOptionValNotSet = errors.New("Message is too long, block option or value not set")
View Source
var ErrNilAddr = errors.New("Address cannot be nil")
View Source
var ErrNilConn = errors.New("Connection object is nil")
View Source
var ErrNilMessage = errors.New("Message is nil")
View Source
var ErrNoMatchingMethod = errors.New("No matching method")
View Source
var ErrNoMatchingRoute = errors.New("No matching route found")
View Source
var ErrOptionDeltaUsesValue15 = errors.New(("Message format error. Option delta has reserved value of 15"))
View Source
var ErrOptionLengthUsesValue15 = errors.New(("Message format error. Option length has reserved value of 15"))
View Source
var ErrPacketLengthLessThan4 = errors.New("Packet length less than 4 bytes")

Errors

View Source
var ErrUnknownCriticalOption = errors.New("Unknown critical option encountered")
View Source
var ErrUnknownMessageType = errors.New("Unknown message type")
View Source
var ErrUnsupportedContentFormat = errors.New("Unsupported Content-Format")
View Source
var ErrUnsupportedMethod = errors.New("Unsupported Method")
View Source
var GENERATE_ID uint16 = 0
View Source
var MESSAGEID_MUTEX *sync.Mutex
View Source
var NEXT_SESSION_ID int32 = 0

Functions

func AddResponseChannel

func AddResponseChannel(c CoapServer, msgId uint16, ch chan *CoapResponseChannel)

func COAPProxyHandler

func COAPProxyHandler(c CoapServer, msg Message, session Session)

func CoapCodeToString

func CoapCodeToString(code CoapCode) string

CoapCodeToString returns the string representation of a CoapCode

func DeleteResponseChannel

func DeleteResponseChannel(c CoapServer, msgId uint16)

func GenerateMessageID

func GenerateMessageID() uint16

GenerateMessageId generate a uint16 Message ID

func GenerateToken

func GenerateToken(l int) string

GenerateToken generates a random token by a given length

func GetResponseChannel

func GetResponseChannel(c CoapServer, msgId uint16) (ch chan *CoapResponseChannel)

func HTTPCOAPProxyHandler

func HTTPCOAPProxyHandler(msg *Message, conn *net.UDPConn, addr net.Addr)

Handles requests for proxying from HTTP to CoAP

func HTTPProxyHandler

func HTTPProxyHandler(c CoapServer, msg Message, session Session)

Handles requests for proxying from CoAP to HTTP

func IsCoapURI

func IsCoapURI(uri string) bool

Determines if a message contains URI targeting a CoAP resource

func IsCriticalOption

func IsCriticalOption(opt Option) bool

Determines if an option is critical

func IsElectiveOption

func IsElectiveOption(opt Option) bool

Determines if an option is elective

func IsHTTPURI

func IsHTTPURI(uri string) bool

Determines if a message contains URI targeting an HTTP resource

func IsProxyRequest

func IsProxyRequest(msg Message) bool

Determines if a message contains options for proxying (i.e. Proxy-Scheme or Proxy-Uri)

func IsRepeatableOption

func IsRepeatableOption(opt Option) bool

Checks if an option is repeatable

func IsValidOption

func IsValidOption(opt Option) bool

Checks if an option/option code is recognizable/valid

func MessageSizeAllowed

func MessageSizeAllowed(req Request) bool

func MessageToBytes

func MessageToBytes(msg Message) ([]byte, error)

Converts a message object to a byte array. Typically done prior to transmission

func MethodString

func MethodString(c CoapCode) string

Gets the string representation of a CoAP Method code (e.g. GET, PUT, DELETE etc)

func NewResponseChannel

func NewResponseChannel() (ch chan *CoapResponseChannel)

func NullProxyFilter

func NullProxyFilter(Message, net.Addr) bool

func NullProxyHandler

func NullProxyHandler(c CoapServer, msg Message, session Session)

The default handler when proxying is disabled

func OptionNumberToString

func OptionNumberToString(o OptionCode) string

OptionNumberToString returns the string representation of a given Option Code

func PayloadAsString

func PayloadAsString(p MessagePayload) string

Returns the string value for a Message Payload

func PrintMessage

func PrintMessage(msg Message)

PrintMessage pretty prints out a given Message

func PrintOptions

func PrintOptions(msg Message)

PrintOptions pretty prints out a given Message's options

func ValidCoapMediaTypeCode

func ValidCoapMediaTypeCode(mt MediaType) bool

ValidCoapMediaTypeCode Checks if a MediaType is of a valid code

func ValidateMessage

func ValidateMessage(msg Message) error

Validates a message object and returns any error upon validation failure

Types

type Block1Option

type Block1Option struct {
	CoapOption
}

func Block1OptionFromOption

func Block1OptionFromOption(opt Option) *Block1Option

func NewBlock1Option

func NewBlock1Option(bs BlockSizeType, more bool, seq uint32) *Block1Option

func (*Block1Option) BlockSizeLength

func (o *Block1Option) BlockSizeLength() uint32

func (*Block1Option) Exponent

func (o *Block1Option) Exponent() uint32

func (*Block1Option) HasMore

func (o *Block1Option) HasMore() bool

func (*Block1Option) Sequence

func (o *Block1Option) Sequence() uint32

func (*Block1Option) Size

func (o *Block1Option) Size() BlockSizeType

type BlockMessage

type BlockMessage interface {
}

func NewBlockMessage

func NewBlockMessage() BlockMessage

type BlockSizeType

type BlockSizeType byte
const (
	BlockSize16   BlockSizeType = 0
	BlockSize32   BlockSizeType = 1
	BlockSize64   BlockSizeType = 2
	BlockSize128  BlockSizeType = 3
	BlockSize256  BlockSizeType = 4
	BlockSize512  BlockSizeType = 5
	BlockSize1024 BlockSizeType = 6
)

type BySequence

type BySequence []*CoapBlockMessage

func (BySequence) Len

func (o BySequence) Len() int

func (BySequence) Less

func (o BySequence) Less(i, j int) bool

func (BySequence) Swap

func (o BySequence) Swap(i, j int)

type BytesPayload

type BytesPayload struct {
	// contains filtered or unexported fields
}

func (*BytesPayload) GetBytes

func (p *BytesPayload) GetBytes() []byte

func (*BytesPayload) Length

func (p *BytesPayload) Length() int

func (*BytesPayload) String

func (p *BytesPayload) String() string

type CoapBlockMessage

type CoapBlockMessage struct {
	CoapMessage
	MessageBuf []byte
	Sequence   uint32
}

type CoapCode

type CoapCode uint8

CoapCode defines a valid CoAP Code Type

const (
	Get    CoapCode = 1
	Post   CoapCode = 2
	Put    CoapCode = 3
	Delete CoapCode = 4

	// 2.x
	CoapCodeEmpty    CoapCode = 0
	CoapCodeCreated  CoapCode = 65 // 2.01
	CoapCodeDeleted  CoapCode = 66 // 2.02
	CoapCodeValid    CoapCode = 67 // 2.03
	CoapCodeChanged  CoapCode = 68 // 2.04
	CoapCodeContent  CoapCode = 69 // 2.05
	CoapCodeContinue CoapCode = 95 // 2.31

	// 4.x
	CoapCodeBadRequest               CoapCode = 128 // 4.00
	CoapCodeUnauthorized             CoapCode = 129 // 4.01
	CoapCodeBadOption                CoapCode = 130 // 4.02
	CoapCodeForbidden                CoapCode = 131 // 4.03
	CoapCodeNotFound                 CoapCode = 132 // 4.04
	CoapCodeMethodNotAllowed         CoapCode = 133 // 4.05
	CoapCodeNotAcceptable            CoapCode = 134 // 4.06
	CoapCodeRequestEntityIncomplete  CoapCode = 136 // 4.08
	CoapCodeConflict                 CoapCode = 137 // 4.09
	CoapCodePreconditionFailed       CoapCode = 140 // 4.12
	CoapCodeRequestEntityTooLarge    CoapCode = 141 // 4.13
	CoapCodeUnsupportedContentFormat CoapCode = 143 // 4.15

	// 5.x
	CoapCodeInternalServerError  CoapCode = 160 // 5.00
	CoapCodeNotImplemented       CoapCode = 161 // 5.01
	CoapCodeBadGateway           CoapCode = 162 // 5.02
	CoapCodeServiceUnavailable   CoapCode = 163 // 5.03
	CoapCodeGatewayTimeout       CoapCode = 164 // 5.04
	CoapCodeProxyingNotSupported CoapCode = 165 // 5.05
)

type CoapMessage

type CoapMessage struct {
	MessageType uint8
	Code        CoapCode
	MessageID   uint16
	Payload     MessagePayload
	Token       []byte
	Options     []Option
}

A Message object represents a CoAP payload

func (*CoapMessage) AddOption

func (m *CoapMessage) AddOption(code OptionCode, value interface{})

Add an Option to the message. If an option is not repeatable, it will replace any existing defined Option of the same type

func (*CoapMessage) AddOptions

func (m *CoapMessage) AddOptions(opts []Option)

Add an array of Options to the message. If an option is not repeatable, it will replace any existing defined Option of the same type

func (*CoapMessage) CloneOptions

func (m *CoapMessage) CloneOptions(cm Message, opts ...OptionCode)

Copies the given list of options from another message to this one

func (*CoapMessage) GetAcceptedContent

func (m *CoapMessage) GetAcceptedContent() MediaType

func (*CoapMessage) GetAllOptions

func (m *CoapMessage) GetAllOptions() []Option

func (*CoapMessage) GetCode

func (m *CoapMessage) GetCode() CoapCode

func (*CoapMessage) GetCodeString

func (m *CoapMessage) GetCodeString() string

func (*CoapMessage) GetLocationPath

func (m *CoapMessage) GetLocationPath() string

Returns the string value of the Location Path Options by joining and defining a / separator

func (*CoapMessage) GetMessageId

func (m *CoapMessage) GetMessageId() uint16

func (*CoapMessage) GetMessageType

func (m *CoapMessage) GetMessageType() uint8

func (*CoapMessage) GetMethod

func (m *CoapMessage) GetMethod() uint8

func (CoapMessage) GetOption

func (m CoapMessage) GetOption(id OptionCode) Option

Returns the first option found for a given option code

func (CoapMessage) GetOptions

func (m CoapMessage) GetOptions(id OptionCode) []Option

Returns an array of options given an option code

func (CoapMessage) GetOptionsAsString

func (m CoapMessage) GetOptionsAsString(id OptionCode) []string

Attempts to return the string value of an Option

func (*CoapMessage) GetPayload

func (m *CoapMessage) GetPayload() MessagePayload

func (*CoapMessage) GetToken

func (m *CoapMessage) GetToken() []byte

func (*CoapMessage) GetTokenLength

func (m *CoapMessage) GetTokenLength() uint8

func (*CoapMessage) GetTokenString

func (m *CoapMessage) GetTokenString() string

func (CoapMessage) GetURIPath

func (m CoapMessage) GetURIPath() string

Returns the string value of the Uri Path Options by joining and defining a / separator

func (*CoapMessage) RemoveOptions

func (m *CoapMessage) RemoveOptions(id OptionCode)

Removes an Option

func (*CoapMessage) ReplaceOptions

func (m *CoapMessage) ReplaceOptions(code OptionCode, opts []Option)

Replace an Option

func (*CoapMessage) SetBlock1Option

func (c *CoapMessage) SetBlock1Option(opt Option)

func (*CoapMessage) SetMessageId

func (m *CoapMessage) SetMessageId(id uint16)

func (*CoapMessage) SetMessageType

func (m *CoapMessage) SetMessageType(t uint8)

func (*CoapMessage) SetPayload

func (m *CoapMessage) SetPayload(p MessagePayload)

func (*CoapMessage) SetStringPayload

func (m *CoapMessage) SetStringPayload(s string)

Adds a string payload

func (*CoapMessage) SetToken

func (m *CoapMessage) SetToken(t []byte)

type CoapObserveMessage

type CoapObserveMessage struct {
	CoapMessage
	Resource string
	Value    interface{}
	Msg      Message
}

func (*CoapObserveMessage) GetMessage

func (m *CoapObserveMessage) GetMessage() Message

func (*CoapObserveMessage) GetResource

func (m *CoapObserveMessage) GetResource() string

func (*CoapObserveMessage) GetValue

func (m *CoapObserveMessage) GetValue() interface{}

type CoapOption

type CoapOption struct {
	Code  OptionCode
	Value interface{}
}

Represents an Option for a CoAP Message

func NewOption

func NewOption(optionNumber OptionCode, optionValue interface{}) *CoapOption

Instantiates a New Option

func (*CoapOption) GetCode

func (o *CoapOption) GetCode() OptionCode

func (*CoapOption) GetValue

func (o *CoapOption) GetValue() interface{}

func (*CoapOption) IntValue

func (o *CoapOption) IntValue() int

func (*CoapOption) IsCritical

func (o *CoapOption) IsCritical() bool

Determines if an option is critical

func (*CoapOption) IsElective

func (o *CoapOption) IsElective() bool

Determines if an option is elective

func (*CoapOption) Name

func (o *CoapOption) Name() string

func (*CoapOption) StringValue

func (o *CoapOption) StringValue() string

Returns the string value of an option

type CoapRequest

type CoapRequest struct {
	// contains filtered or unexported fields
}

Wraps a CoAP Message as a Request Provides various methods which proxies the Message object methods

func (*CoapRequest) GetAttribute

func (c *CoapRequest) GetAttribute(o string) string

func (*CoapRequest) GetAttributeAsInt

func (c *CoapRequest) GetAttributeAsInt(o string) int

func (*CoapRequest) GetAttributes

func (c *CoapRequest) GetAttributes() map[string]string

func (*CoapRequest) GetMessage

func (c *CoapRequest) GetMessage() Message

func (*CoapRequest) GetSession

func (c *CoapRequest) GetSession() Session

func (*CoapRequest) GetURIQuery

func (c *CoapRequest) GetURIQuery(q string) string

func (*CoapRequest) SetConfirmable

func (c *CoapRequest) SetConfirmable(con bool)

func (*CoapRequest) SetMediaType

func (c *CoapRequest) SetMediaType(mt MediaType)

func (*CoapRequest) SetPayload

func (c *CoapRequest) SetPayload(b []byte)

func (*CoapRequest) SetProxyURI

func (c *CoapRequest) SetProxyURI(uri string)

func (*CoapRequest) SetRequestURI

func (c *CoapRequest) SetRequestURI(uri string)

func (*CoapRequest) SetStringPayload

func (c *CoapRequest) SetStringPayload(s string)

func (*CoapRequest) SetToken

func (c *CoapRequest) SetToken(t string)

func (*CoapRequest) SetURIQuery

func (c *CoapRequest) SetURIQuery(k string, v string)

type CoapResponseChannel

type CoapResponseChannel struct {
	Response Response
	Error    error
}

type CoapServer

type CoapServer interface {
	ListenAndServe(addr string)
	ListenAndServeDTLS(addr string)
	Stop()

	Get(path string, fn RouteHandler) Route
	Delete(path string, fn RouteHandler) Route
	Put(path string, fn RouteHandler) Route
	Post(path string, fn RouteHandler) Route
	Options(path string, fn RouteHandler) Route
	Patch(path string, fn RouteHandler) Route

	NewRoute(path string, method CoapCode, fn RouteHandler) Route
	NotifyChange(resource, value string, confirm bool)

	OnNotify(fn FnEventNotify)
	OnStart(fn FnEventStart)
	OnClose(fn FnEventClose)
	OnDiscover(fn FnEventDiscover)
	OnError(fn FnEventError)
	OnObserve(fn FnEventObserve)
	OnObserveCancel(fn FnEventObserveCancel)
	OnMessage(fn FnEventMessage)
	OnBlockMessage(fn FnEventBlockMessage)

	ProxyOverHttp(enabled bool)
	ProxyOverCoap(enabled bool)

	GetEvents() Events

	AllowProxyForwarding(Message, net.Addr) bool
	GetRoutes() []Route
	ForwardCoap(msg Message, session Session)
	ForwardHTTP(msg Message, session Session)

	AddObservation(resource, token string, session Session)
	HasObservation(resource string, addr net.Addr) bool
	RemoveObservation(resource string, addr net.Addr)

	HandlePSK(func(id string) []byte)

	GetSession(addr string) Session
	DeleteSession(ssn Session)

	GetCookieSecret() []byte
}

Interfaces

func NewServer

func NewServer() CoapServer

type Connection

type Connection interface {
	ObserveResource(resource string) (tok string, err error)
	CancelObserveResource(resource string, token string) (err error)
	StopObserve(ch chan ObserveMessage)
	Observe(ch chan ObserveMessage)
	Send(req Request) (resp Response, err error)

	Write(b []byte) (n int, err error)
	Read(b []byte) (n int, err error)
	Close() error
}

func Dial

func Dial(address string) (conn Connection, err error)

func DialDTLS

func DialDTLS(address, identity, psk string) (conn Connection, err error)

func NewDTLSConnection

func NewDTLSConnection(c net.Conn, identity, psk string) (conn Connection, err error)

Client DTLS

type CoreAttribute

type CoreAttribute struct {
	Key   string
	Value interface{}
}

func NewCoreAttribute

func NewCoreAttribute(key string, value interface{}) *CoreAttribute

Instantiates a new core-attribute with a given key/value

type CoreAttributes

type CoreAttributes []*CoreAttribute

type CoreLinkFormatPayload

type CoreLinkFormatPayload struct {
}

Represents a message payload containing core-link format values

func (*CoreLinkFormatPayload) GetBytes

func (p *CoreLinkFormatPayload) GetBytes() []byte

func (*CoreLinkFormatPayload) Length

func (p *CoreLinkFormatPayload) Length() int

func (*CoreLinkFormatPayload) String

func (p *CoreLinkFormatPayload) String() string

type CoreResource

type CoreResource struct {
	Target     string
	Attributes CoreAttributes
}

func CoreResourcesFromString

func CoreResourcesFromString(str string) []*CoreResource

CoreResourcesFromString Converts to CoRE Resources Object from a CoRE String

func NewCoreResource

func NewCoreResource() *CoreResource

Instantiates a new Core Resource Object

func (*CoreResource) AddAttribute

func (c *CoreResource) AddAttribute(key string, value interface{})

Adds an attribute (key/value) for a given core resource

func (*CoreResource) GetAttribute

func (c *CoreResource) GetAttribute(key string) *CoreAttribute

Gets an attribute for a core resource

type DTLSConnection

type DTLSConnection struct {
	UDPConnection
	// contains filtered or unexported fields
}

func (*DTLSConnection) CancelObserveResource

func (c *DTLSConnection) CancelObserveResource(resource string, token string) (err error)

func (*DTLSConnection) Close

func (c *DTLSConnection) Close() error

func (*DTLSConnection) Observe

func (c *DTLSConnection) Observe(ch chan ObserveMessage)

func (*DTLSConnection) ObserveResource

func (c *DTLSConnection) ObserveResource(resource string) (tok string, err error)

func (*DTLSConnection) Read

func (c *DTLSConnection) Read(b []byte) (int, error)

func (*DTLSConnection) Send

func (c *DTLSConnection) Send(req Request) (resp Response, err error)

func (*DTLSConnection) StopObserve

func (c *DTLSConnection) StopObserve(ch chan ObserveMessage)

func (*DTLSConnection) Write

func (c *DTLSConnection) Write(b []byte) (int, error)

type DTLSServerSession

type DTLSServerSession struct {
	UDPServerSession
	// contains filtered or unexported fields
}

func (*DTLSServerSession) GetConnection

func (s *DTLSServerSession) GetConnection() ServerConnection

func (*DTLSServerSession) Read

func (s *DTLSServerSession) Read(b []byte) (n int, err error)

func (*DTLSServerSession) Write

func (s *DTLSServerSession) Write(b []byte) (int, error)

type DefaultCoapServer

type DefaultCoapServer struct {
	// contains filtered or unexported fields
}

func (*DefaultCoapServer) AddObservation

func (s *DefaultCoapServer) AddObservation(resource, token string, session Session)

func (*DefaultCoapServer) AllowProxyForwarding

func (s *DefaultCoapServer) AllowProxyForwarding(msg Message, addr net.Addr) bool

func (*DefaultCoapServer) Delete

func (s *DefaultCoapServer) Delete(path string, fn RouteHandler) Route

func (*DefaultCoapServer) DeleteSession

func (s *DefaultCoapServer) DeleteSession(ssn Session)

func (*DefaultCoapServer) ForwardCoap

func (s *DefaultCoapServer) ForwardCoap(msg Message, session Session)

func (*DefaultCoapServer) ForwardHTTP

func (s *DefaultCoapServer) ForwardHTTP(msg Message, session Session)

func (*DefaultCoapServer) Get

func (s *DefaultCoapServer) Get(path string, fn RouteHandler) Route

func (*DefaultCoapServer) GetCookieSecret

func (s *DefaultCoapServer) GetCookieSecret() []byte

func (*DefaultCoapServer) GetEvents

func (s *DefaultCoapServer) GetEvents() Events

func (*DefaultCoapServer) GetRoutes

func (s *DefaultCoapServer) GetRoutes() []Route

func (*DefaultCoapServer) GetSession

func (s *DefaultCoapServer) GetSession(addr string) Session

func (*DefaultCoapServer) HandlePSK

func (s *DefaultCoapServer) HandlePSK(fn func(id string) []byte)

func (*DefaultCoapServer) HasObservation

func (s *DefaultCoapServer) HasObservation(resource string, addr net.Addr) bool

func (*DefaultCoapServer) ListenAndServe

func (s *DefaultCoapServer) ListenAndServe(addr string)

func (*DefaultCoapServer) ListenAndServeDTLS

func (s *DefaultCoapServer) ListenAndServeDTLS(addr string)

func (*DefaultCoapServer) NewRoute

func (s *DefaultCoapServer) NewRoute(path string, method CoapCode, fn RouteHandler) Route

func (*DefaultCoapServer) NotifyChange

func (s *DefaultCoapServer) NotifyChange(resource, value string, confirm bool)

func (*DefaultCoapServer) OnBlockMessage

func (s *DefaultCoapServer) OnBlockMessage(fn FnEventBlockMessage)

func (*DefaultCoapServer) OnClose

func (s *DefaultCoapServer) OnClose(fn FnEventClose)

func (*DefaultCoapServer) OnDiscover

func (s *DefaultCoapServer) OnDiscover(fn FnEventDiscover)

func (*DefaultCoapServer) OnError

func (s *DefaultCoapServer) OnError(fn FnEventError)

func (*DefaultCoapServer) OnMessage

func (s *DefaultCoapServer) OnMessage(fn FnEventMessage)

func (*DefaultCoapServer) OnNotify

func (s *DefaultCoapServer) OnNotify(fn FnEventNotify)

func (*DefaultCoapServer) OnObserve

func (s *DefaultCoapServer) OnObserve(fn FnEventObserve)

func (*DefaultCoapServer) OnObserveCancel

func (s *DefaultCoapServer) OnObserveCancel(fn FnEventObserveCancel)

func (*DefaultCoapServer) OnStart

func (s *DefaultCoapServer) OnStart(fn FnEventStart)

func (*DefaultCoapServer) Options

func (s *DefaultCoapServer) Options(path string, fn RouteHandler) Route

func (*DefaultCoapServer) Patch

func (s *DefaultCoapServer) Patch(path string, fn RouteHandler) Route

func (*DefaultCoapServer) Post

func (s *DefaultCoapServer) Post(path string, fn RouteHandler) Route

func (*DefaultCoapServer) ProxyOverCoap

func (s *DefaultCoapServer) ProxyOverCoap(enabled bool)

func (*DefaultCoapServer) ProxyOverHttp

func (s *DefaultCoapServer) ProxyOverHttp(enabled bool)

func (*DefaultCoapServer) Put

func (s *DefaultCoapServer) Put(path string, fn RouteHandler) Route

func (*DefaultCoapServer) RemoveObservation

func (s *DefaultCoapServer) RemoveObservation(resource string, addr net.Addr)

func (*DefaultCoapServer) SetProxyFilter

func (s *DefaultCoapServer) SetProxyFilter(fn ProxyFilter)

func (*DefaultCoapServer) Stop

func (s *DefaultCoapServer) Stop()

type DefaultResponse

type DefaultResponse struct {
	// contains filtered or unexported fields
}

func (*DefaultResponse) GetError

func (c *DefaultResponse) GetError() error

func (*DefaultResponse) GetMessage

func (c *DefaultResponse) GetMessage() Message

func (*DefaultResponse) GetPayload

func (c *DefaultResponse) GetPayload() []byte

func (*DefaultResponse) GetURIQuery

func (c *DefaultResponse) GetURIQuery(q string) string

type EmptyPayload

type EmptyPayload struct {
}

Represents an empty message payload

func (*EmptyPayload) GetBytes

func (p *EmptyPayload) GetBytes() []byte

func (*EmptyPayload) Length

func (p *EmptyPayload) Length() int

func (*EmptyPayload) String

func (p *EmptyPayload) String() string

type EventCode

type EventCode int
const (
	EventStart         EventCode = 0
	EventClose         EventCode = 1
	EventDiscover      EventCode = 2
	EventMessage       EventCode = 3
	EventError         EventCode = 4
	EventObserve       EventCode = 5
	EventObserveCancel EventCode = 6
	EventNotify        EventCode = 7
)

type Events

type Events interface {
	OnNotify(fn FnEventNotify)
	OnStart(fn FnEventStart)
	OnClose(fn FnEventClose)
	OnDiscover(fn FnEventDiscover)
	OnError(fn FnEventError)
	OnObserve(fn FnEventObserve)
	OnObserveCancel(fn FnEventObserveCancel)
	OnMessage(fn FnEventMessage)
	OnBlockMessage(fn FnEventBlockMessage)

	Notify(resource string, value interface{}, msg Message)
	Started(server CoapServer)
	Closed(server CoapServer)
	Discover()
	Error(err error)
	Observe(resource string, msg Message)
	ObserveCancelled(resource string, msg Message)
	Message(msg Message, inbound bool)
	BlockMessage(msg Message, inbound bool)
}

type FnEventBlockMessage

type FnEventBlockMessage func(Message, bool)

type FnEventClose

type FnEventClose func(CoapServer)

type FnEventDiscover

type FnEventDiscover func()

type FnEventError

type FnEventError func(error)

type FnEventMessage

type FnEventMessage func(Message, bool)

type FnEventNotify

type FnEventNotify func(string, interface{}, Message)

type FnEventObserve

type FnEventObserve func(string, Message)

type FnEventObserveCancel

type FnEventObserveCancel func(string, Message)

type FnEventStart

type FnEventStart func(CoapServer)

type JSONPayload

type JSONPayload struct {
	// contains filtered or unexported fields
}

Represents a message payload containing JSON String

func (*JSONPayload) GetBytes

func (p *JSONPayload) GetBytes() []byte

func (*JSONPayload) Length

func (p *JSONPayload) Length() int

func (*JSONPayload) String

func (p *JSONPayload) String() string

type MediaType

type MediaType int
const (
	MediaTypeTextPlain                  MediaType = 0
	MediaTypeTextXML                    MediaType = 1
	MediaTypeTextCsv                    MediaType = 2
	MediaTypeTextHTML                   MediaType = 3
	MediaTypeImageGif                   MediaType = 21
	MediaTypeImageJpeg                  MediaType = 22
	MediaTypeImagePng                   MediaType = 23
	MediaTypeImageTiff                  MediaType = 24
	MediaTypeAudioRaw                   MediaType = 25
	MediaTypeVideoRaw                   MediaType = 26
	MediaTypeApplicationLinkFormat      MediaType = 40
	MediaTypeApplicationXML             MediaType = 41
	MediaTypeApplicationOctetStream     MediaType = 42
	MediaTypeApplicationRdfXML          MediaType = 43
	MediaTypeApplicationSoapXML         MediaType = 44
	MediaTypeApplicationAtomXML         MediaType = 45
	MediaTypeApplicationXmppXML         MediaType = 46
	MediaTypeApplicationExi             MediaType = 47
	MediaTypeApplicationFastInfoSet     MediaType = 48
	MediaTypeApplicationSoapFastInfoSet MediaType = 49
	MediaTypeApplicationJSON            MediaType = 50
	MediaTypeApplicationXObitBinary     MediaType = 51
	MediaTypeTextPlainVndOmaLwm2m       MediaType = 1541
	MediaTypeTlvVndOmaLwm2m             MediaType = 1542
	MediaTypeJSONVndOmaLwm2m            MediaType = 1543
	MediaTypeOpaqueVndOmaLwm2m          MediaType = 1544
)

type Message

type Message interface {
	GetToken() []byte
	GetMessageId() uint16
	GetMessageType() uint8
	GetAcceptedContent() MediaType
	GetCodeString() string
	GetCode() CoapCode
	GetMethod() uint8
	GetTokenLength() uint8
	GetTokenString() string
	GetOptions(id OptionCode) []Option
	GetOption(id OptionCode) Option
	GetAllOptions() []Option
	GetOptionsAsString(id OptionCode) []string
	GetLocationPath() string
	GetURIPath() string
	GetPayload() MessagePayload

	SetToken([]byte)
	SetMessageId(uint16)
	SetMessageType(uint8)
	SetBlock1Option(opt Option)
	SetStringPayload(s string)
	SetPayload(MessagePayload)

	AddOption(code OptionCode, value interface{})
	AddOptions(opts []Option)
	CloneOptions(cm Message, opts ...OptionCode)
	ReplaceOptions(code OptionCode, opts []Option)
	RemoveOptions(id OptionCode)
}

func BadGatewayMessage

func BadGatewayMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 502 - Bad Gateway

func BadOptionMessage

func BadOptionMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 402 - Bad Option

func BadRequestMessage

func BadRequestMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 400 - Bad Request

func BytesToMessage

func BytesToMessage(data []byte) (Message, error)

Converts an array of bytes to a Mesasge object. An error is returned if a parsing error occurs

func ChangedMessage

func ChangedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 204 - Changed

func ConflictMessage

func ConflictMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 409 - Conflict

func ContentMessage

func ContentMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 205 - Content

func ContinueMessage

func ContinueMessage(messageID uint16, messageType uint8) Message

func CreatedMessage

func CreatedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 201 - Created

func DeletedMessage

func DeletedMessage(messageID uint16, messageType uint8) Message

// Creates a Non-Confirmable with CoAP Code 202 - Deleted

func EmptyMessage

func EmptyMessage(messageID uint16, messageType uint8) Message

Response Code Messages Creates a Non-Confirmable Empty Message

func ForbiddenMessage

func ForbiddenMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 403 - Forbidden

func GatewayTimeoutMessage

func GatewayTimeoutMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 504 - Gateway Timeout

func InternalServerErrorMessage

func InternalServerErrorMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 500 - Internal Server Error

func MethodNotAllowedMessage

func MethodNotAllowedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 405 - Method Not Allowed

func NewEmptyMessage

func NewEmptyMessage(id uint16) Message

Instantiates an empty message with a given message id

func NewMessage

func NewMessage(messageType uint8, code CoapCode, messageID uint16) Message

Instantiates a new message object messageType (e.g. Confirm/Non-Confirm) CoAP code 404 - Not found etc Message ID uint16 unique id

func NewMessageOfType

func NewMessageOfType(t uint8, id uint16, payload MessagePayload) Message

Instantiates an empty message of a specific type and message id

func NotAcceptableMessage

func NotAcceptableMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 406 - Not Acceptable

func NotFoundMessage

func NotFoundMessage(messageID uint16, messageType uint8, token []byte) (m Message)

Creates a Non-Confirmable with CoAP Code 404 - Not Found

func NotImplementedMessage

func NotImplementedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 501 - Not Implemented

func PreconditionFailedMessage

func PreconditionFailedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 412 - Precondition Failed

func ProxyingNotSupportedMessage

func ProxyingNotSupportedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 505 - Proxying Not Supported

func RequestEntityTooLargeMessage

func RequestEntityTooLargeMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 413 - Request Entity Too Large

func ServiceUnavailableMessage

func ServiceUnavailableMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 503 - Service Unavailable

func UnauthorizedMessage

func UnauthorizedMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 401 - Unauthorized

func UnsupportedContentFormatMessage

func UnsupportedContentFormatMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 415 - Unsupported Content Format

func ValidMessage

func ValidMessage(messageID uint16, messageType uint8) Message

Creates a Non-Confirmable with CoAP Code 203 - Valid

type MessagePayload

type MessagePayload interface {
	GetBytes() []byte
	Length() int
	String() string
}

Represents the payload/content of a CoAP Message

func NewBytesPayload

func NewBytesPayload(v []byte) MessagePayload

Represents a message payload containing an array of bytes

func NewEmptyPayload

func NewEmptyPayload() MessagePayload

func NewJSONPayload

func NewJSONPayload(obj interface{}) MessagePayload

func NewPlainTextPayload

func NewPlainTextPayload(s string) MessagePayload

Instantiates a new message payload of type string

type NilResponse

type NilResponse struct {
}

func (NilResponse) GetError

func (c NilResponse) GetError() error

func (NilResponse) GetMessage

func (c NilResponse) GetMessage() Message

func (NilResponse) GetPayload

func (c NilResponse) GetPayload() []byte

func (NilResponse) GetURIQuery

func (c NilResponse) GetURIQuery(q string) string

type Observation

type Observation struct {
	Session     Session
	Token       string
	Resource    string
	NotifyCount int
}

func NewObservation

func NewObservation(session Session, token string, resource string) *Observation

type ObserveMessage

type ObserveMessage interface {
	GetResource() string
	GetValue() interface{}
	GetMessage() Message
}

func NewObserveMessage

func NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage

type Option

type Option interface {
	Name() string
	IsElective() bool
	IsCritical() bool
	StringValue() string
	IntValue() int
	GetCode() OptionCode
	GetValue() interface{}
}

func NewPathOptions

func NewPathOptions(path string) []Option

Creates an array of options decomposed from a given path

type OptionCode

type OptionCode int

OptionCode type represents a valid CoAP Option Code

const (
	// OptionIfMatch request-header field is used with a method to make it conditional.
	// A client that has one or more entities previously obtained from the resource can verify
	// that one of those entities is current by including a list of their associated entity tags
	// in the If-Match header field.
	OptionIfMatch OptionCode = 1

	OptionURIHost       OptionCode = 3
	OptionEtag          OptionCode = 4
	OptionIfNoneMatch   OptionCode = 5
	OptionObserve       OptionCode = 6
	OptionURIPort       OptionCode = 7
	OptionLocationPath  OptionCode = 8
	OptionURIPath       OptionCode = 11
	OptionContentFormat OptionCode = 12
	OptionMaxAge        OptionCode = 14
	OptionURIQuery      OptionCode = 15
	OptionAccept        OptionCode = 17
	OptionLocationQuery OptionCode = 20
	OptionBlock2        OptionCode = 23
	OptionBlock1        OptionCode = 27
	OptionSize2         OptionCode = 28
	OptionProxyURI      OptionCode = 35
	OptionProxyScheme   OptionCode = 39
	OptionSize1         OptionCode = 60
)

type PlainTextPayload

type PlainTextPayload struct {
	// contains filtered or unexported fields
}

Represents a message payload containing string value

func (*PlainTextPayload) GetBytes

func (p *PlainTextPayload) GetBytes() []byte

func (*PlainTextPayload) Length

func (p *PlainTextPayload) Length() int

func (*PlainTextPayload) String

func (p *PlainTextPayload) String() string

type ProxyFilter

type ProxyFilter func(Message, net.Addr) bool

Proxy Filter

type ProxyHandler

type ProxyHandler func(c CoapServer, msg Message, session Session)

type RegExRoute

type RegExRoute struct {
	Path       string
	Method     string
	Handler    RouteHandler
	RegEx      *regexp.Regexp
	AutoAck    bool
	MediaTypes []MediaType
}

Route represents a CoAP Route/Resource

func (*RegExRoute) AutoAcknowledge

func (r *RegExRoute) AutoAcknowledge() bool

func (*RegExRoute) GetConfiguredPath

func (r *RegExRoute) GetConfiguredPath() string

func (*RegExRoute) GetMediaTypes

func (r *RegExRoute) GetMediaTypes() []MediaType

func (*RegExRoute) GetMethod

func (r *RegExRoute) GetMethod() string

func (*RegExRoute) Handle

func (r *RegExRoute) Handle(req Request) Response

func (*RegExRoute) Matches

func (r *RegExRoute) Matches(path string) (bool, map[string]string)

type Request

type Request interface {
	GetAttributes() map[string]string
	GetAttribute(o string) string
	GetAttributeAsInt(o string) int
	GetMessage() Message
	GetURIQuery(q string) string

	SetProxyURI(uri string)
	SetMediaType(mt MediaType)
	SetPayload([]byte)
	SetStringPayload(s string)
	SetRequestURI(uri string)
	SetConfirmable(con bool)
	SetToken(t string)
	SetURIQuery(k string, v string)
}

func NewClientRequestFromMessage

func NewClientRequestFromMessage(msg Message, attrs map[string]string, session Session) Request

func NewConfirmableDeleteRequest

func NewConfirmableDeleteRequest() Request

func NewConfirmableGetRequest

func NewConfirmableGetRequest() Request

func NewConfirmablePostRequest

func NewConfirmablePostRequest() Request

func NewConfirmablePutRequest

func NewConfirmablePutRequest() Request

func NewRequest

func NewRequest(messageType uint8, messageMethod CoapCode) Request

Creates a New Request Instance

func NewRequestFromMessage

func NewRequestFromMessage(msg Message) Request

Creates a new request messages from a CoAP Message

func NewRequestWithMessageId

func NewRequestWithMessageId(messageType uint8, messageMethod CoapCode, messageID uint16) Request

type Response

type Response interface {
	GetMessage() Message
	GetError() error
	GetPayload() []byte
	GetURIQuery(q string) string
}

func NewResponse

func NewResponse(msg Message, err error) Response

Creates a new Response object with a Message object and any error messages

func NewResponseWithMessage

func NewResponseWithMessage(msg Message) Response

Creates a new response object with a Message object

func NoResponse

func NoResponse() Response

func SendMessage

func SendMessage(msg Message, session Session) (Response, error)

type Route

type Route interface {
	GetMethod() string
	GetMediaTypes() []MediaType
	GetConfiguredPath() string

	Matches(path string) (bool, map[string]string)
	AutoAcknowledge() bool
	Handle(req Request) Response
}

func CreateNewRegExRoute

func CreateNewRegExRoute(path string, method string, fn RouteHandler) Route

CreateNewRoute creates a new Route object

func MatchingRoute

func MatchingRoute(path string, method string, cf interface{}, routes []Route) (Route, map[string]string, error)

MatchingRoute checks if a given path matches any defined routes/resources

type RouteHandler

type RouteHandler func(Request) Response

type ServerConfiguration

type ServerConfiguration struct {
	EnableResourceDiscovery bool
}

type ServerConnection

type ServerConnection interface {
	ReadFrom(b []byte) (n int, addr net.Addr, err error)
	WriteTo(b []byte, addr net.Addr) (n int, err error)
	Close() error
	LocalAddr() net.Addr
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

type ServerDtlsContext

type ServerDtlsContext struct {
	// contains filtered or unexported fields
}

func NewServerDtlsContext

func NewServerDtlsContext() (ctx *ServerDtlsContext, err error)

type ServerEvents

type ServerEvents struct {
	// contains filtered or unexported fields
}

This holds the various events which are triggered throughout an application's lifetime

func NewEvents

func NewEvents() *ServerEvents

func (*ServerEvents) BlockMessage

func (ce *ServerEvents) BlockMessage(msg Message, inbound bool)

Fires the "OnBlockMessage" event. The 'inbound' variables determines if the message is inbound or outgoing

func (*ServerEvents) Closed

func (ce *ServerEvents) Closed(server CoapServer)

Fires the "OnClosed" event

func (*ServerEvents) Discover

func (ce *ServerEvents) Discover()

Fires the "OnDiscover" event

func (*ServerEvents) Error

func (ce *ServerEvents) Error(err error)

Fires the "OnError" event given an error object

func (*ServerEvents) Message

func (ce *ServerEvents) Message(msg Message, inbound bool)

Fires the "OnMessage" event. The 'inbound' variables determines if the message is inbound or outgoing

func (*ServerEvents) Notify

func (ce *ServerEvents) Notify(resource string, value interface{}, msg Message)

Fires the "OnNotify" event

func (*ServerEvents) Observe

func (ce *ServerEvents) Observe(resource string, msg Message)

Fires the "OnObserve" event for a given resource

func (*ServerEvents) ObserveCancelled

func (ce *ServerEvents) ObserveCancelled(resource string, msg Message)

Fires the "OnObserveCancelled" event for a given resource

func (*ServerEvents) OnBlockMessage

func (ce *ServerEvents) OnBlockMessage(fn FnEventBlockMessage)

Fired when a block messageis received

func (*ServerEvents) OnClose

func (ce *ServerEvents) OnClose(fn FnEventClose)

Fired when the server/client closes

func (*ServerEvents) OnDiscover

func (ce *ServerEvents) OnDiscover(fn FnEventDiscover)

Fired when a discovery request is triggered

func (*ServerEvents) OnError

func (ce *ServerEvents) OnError(fn FnEventError)

Catch-all event which is fired when an error occurs

func (*ServerEvents) OnMessage

func (ce *ServerEvents) OnMessage(fn FnEventMessage)

Fired when a message is received

func (*ServerEvents) OnNotify

func (ce *ServerEvents) OnNotify(fn FnEventNotify)

OnNotify is Fired when an observeed resource is notified

func (*ServerEvents) OnObserve

func (ce *ServerEvents) OnObserve(fn FnEventObserve)

Fired when an observe request is triggered for a resource

func (*ServerEvents) OnObserveCancel

func (ce *ServerEvents) OnObserveCancel(fn FnEventObserveCancel)

Fired when an observe-cancel request is triggered foa r esource

func (*ServerEvents) OnStart

func (ce *ServerEvents) OnStart(fn FnEventStart)

Fired when the server/client starts up

func (*ServerEvents) Started

func (ce *ServerEvents) Started(server CoapServer)

Fires the "OnStarted" event

type Session

type Session interface {
	GetConnection() ServerConnection
	GetAddress() net.Addr
	Write([]byte) (int, error)
	Read([]byte) (n int, err error)
	GetServer() CoapServer
	WriteBuffer([]byte) int
}

type SortOptions

type SortOptions []Option

type to sort the coap options list (which is mandatory) prior to transmission

func (SortOptions) Len

func (opts SortOptions) Len() int

func (SortOptions) Less

func (opts SortOptions) Less(i, j int) bool

func (SortOptions) Swap

func (opts SortOptions) Swap(i, j int)

type UDPConnection

type UDPConnection struct {
	// contains filtered or unexported fields
}

func (*UDPConnection) CancelObserveResource

func (c *UDPConnection) CancelObserveResource(resource string, token string) (err error)

func (*UDPConnection) Close

func (c *UDPConnection) Close() error

func (*UDPConnection) Observe

func (c *UDPConnection) Observe(ch chan ObserveMessage)

func (*UDPConnection) ObserveResource

func (c *UDPConnection) ObserveResource(resource string) (tok string, err error)

func (*UDPConnection) Read

func (c *UDPConnection) Read(b []byte) (int, error)

func (*UDPConnection) Send

func (c *UDPConnection) Send(req Request) (resp Response, err error)

func (*UDPConnection) SendMessage

func (c *UDPConnection) SendMessage(msg Message) (resp Response, err error)

func (*UDPConnection) StopObserve

func (c *UDPConnection) StopObserve(ch chan ObserveMessage)

func (*UDPConnection) Write

func (c *UDPConnection) Write(b []byte) (int, error)

type UDPServerConnection

type UDPServerConnection struct {
	// contains filtered or unexported fields
}

func (*UDPServerConnection) Close

func (uc *UDPServerConnection) Close() error

func (*UDPServerConnection) LocalAddr

func (uc *UDPServerConnection) LocalAddr() net.Addr

func (*UDPServerConnection) ReadFrom

func (uc *UDPServerConnection) ReadFrom(b []byte) (n int, addr net.Addr, err error)

func (*UDPServerConnection) SetDeadline

func (uc *UDPServerConnection) SetDeadline(t time.Time) error

func (*UDPServerConnection) SetReadDeadline

func (uc *UDPServerConnection) SetReadDeadline(t time.Time) error

func (*UDPServerConnection) SetWriteDeadline

func (uc *UDPServerConnection) SetWriteDeadline(t time.Time) error

func (*UDPServerConnection) WriteTo

func (uc *UDPServerConnection) WriteTo(b []byte, addr net.Addr) (n int, err error)

type UDPServerSession

type UDPServerSession struct {
	// contains filtered or unexported fields
}

func (*UDPServerSession) GetAddress

func (s *UDPServerSession) GetAddress() net.Addr

func (*UDPServerSession) GetConnection

func (s *UDPServerSession) GetConnection() ServerConnection

func (*UDPServerSession) GetServer

func (s *UDPServerSession) GetServer() CoapServer

func (*UDPServerSession) Read

func (s *UDPServerSession) Read(b []byte) (n int, err error)

func (*UDPServerSession) Write

func (s *UDPServerSession) Write(b []byte) (n int, err error)

func (*UDPServerSession) WriteBuffer

func (s *UDPServerSession) WriteBuffer(b []byte) (n int)

type XMLPayload

type XMLPayload struct {
}

Represents a message payload containing XML String

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL