coap

package module
v0.0.0-...-614f652 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2019 License: Apache-2.0 Imports: 22 Imported by: 0

README

Yggdrasil-Go-CoAP

builds.sr.ht status

This project is a fork of github.com/go-ocf/go-coap, adding Yggdrasil support to the library.

This project lives at git.sr.ht/~fnux/yggdrasil-go-coap, a bug tracker being available at todo.sr.ht/~fnux/yggdrasil-go-coap.

Contributions

You can send me patches by email. Feel free to contact me directly if you have issues with this workflow.

Yggdrasil support

In order to support Yggdrasil, the following structure and methods are provided:

type YggdrasilNode struct {
	Core   *yggdrasil.Core
	Config *config.NodeConfig
}


func DialYggdrasil(node coapNet.YggdrasilNode, address string) (*ClientConn, error)
func ListenAndServeYggdrasil(node coapNet.YggdrasilNode, handler Handler) error

A complete example can be found on git.sr.ht/~fnux/yggdrasil-coap-nodes.

Custom CoAP Options

This fork also allow to use custom CoAP options:

func SetOptionDef(oid OptionID, format string, minLen int, maxLen int)

// Example
var MyCustomCoAPOptionID coap.OptionID = 65000
coap.SetOptionDef(MyCustomCoAPOptionID, "string", 0, 255)

params := coap.MessageParams{ ... }
msg := c.NewMessage(params)

msg.SetOption(MyCustomCoAPOption, "spouik")

Documentation

Overview

Package coap provides a CoAP client and server.

Package coap provides a CoAP client and server.

Index

Constants

View Source
const (
	TCP_MESSAGE_LEN13_BASE = 13
	TCP_MESSAGE_LEN14_BASE = 269
	TCP_MESSAGE_LEN15_BASE = 65805
	TCP_MESSAGE_MAX_LEN    = 0x7fff0000 // Large number that works in 32-bit builds.
)
View Source
const DefaultPort = 5683

DefaultPort default unsecure port for COAP server

View Source
const DefaultSecurePort = 5684

DefaultSecurePort default secure port for COAP server

View Source
const ErrBlockInvalidSize = Error("block has invalid size")

ErrBlockInvalidSize block has invalid size

View Source
const ErrBlockNumberExceedLimit = Error("block number exceed limit 1,048,576")

ErrBlockNumberExceedLimit block number exceed limit 1,048,576

View Source
const ErrConnectionClosed = Error("connection closed")

ErrConnectionClosed Connection closed

View Source
const ErrContentFormatNotSet = Error("content format is not set")

ErrContentFormatNotSet content format is not set

View Source
const ErrInvalidBlockWiseSzx = Error("invalid block-wise transfer szx")

ErrInvalidBlockWiseSzx invalid block-wise transfer szx

View Source
const ErrInvalidMaxMesssageSizeParameter = Error("invalid .MaxMessageSize parameter")

ErrInvalidMaxMesssageSizeParameter invalid .MaxMessageSize parameter

View Source
const ErrInvalidNetParameter = Error("invalid .Net parameter")

ErrInvalidNetParameter invalid .Net parameter

View Source
const ErrInvalidOptionBlock1 = Error("message has invalid value of Block1")

ErrInvalidOptionBlock1 message has invalid value of Block1

View Source
const ErrInvalidOptionBlock2 = Error("message has invalid value of Block2")

ErrInvalidOptionBlock2 message has invalid value of Block2

View Source
const ErrInvalidPayload = Error("invalid payload")

ErrInvalidPayload invalid payload

View Source
const ErrInvalidPayloadSize = Error("invalid payload size")

ErrInvalidPayloadSize invalid payload size

View Source
const ErrInvalidReponseCode = Error("response code has invalid value")

ErrInvalidReponseCode response code has invalid value

View Source
const ErrInvalidRequest = Error("invalid request")

ErrInvalidRequest invalid requests

View Source
const ErrInvalidResponse = Error("invalid response")

ErrInvalidResponse invalid response received for certain token

View Source
const ErrInvalidServerConnParameter = Error("invalid Server.Conn parameter")

ErrInvalidServerConnParameter invalid Server.Conn parameter

View Source
const ErrInvalidServerListenerParameter = Error("invalid Server.Listener parameter")

ErrInvalidServerListenerParameter invalid Server.Listener parameter

View Source
const ErrInvalidTokenLen = Error("invalid token length")

ErrInvalidTokenLen invalid token length in Message

View Source
const ErrMaxMessageSizeLimitExceeded = Error("maximum message size limit exceeded")

ErrMaxMessageSizeLimitExceeded message size bigger thab maximum message size limit

View Source
const ErrMessageInvalidVersion = Error("invalid version of Message")

ErrMessageInvalidVersion invalid version of Message

View Source
const ErrMessageNotInterested = Error("message not to be sent due to disinterest")

ErrMessageNotInterested message is not of interest to the client

View Source
const ErrMessageTruncated = Error("message is truncated")

ErrMessageTruncated message is truncated

View Source
const ErrMsgTooLarge = Error("message it too large, for processing")

ErrMsgTooLarge message it too large, for processing

View Source
const ErrNotSupported = Error("not supported")

ErrNotSupported invalid response received for certain token

View Source
const ErrOptionGapTooLarge = Error("option gap too large")

ErrOptionGapTooLarge option gap too large in Message

View Source
const ErrOptionTooLong = Error("option is too long")

ErrOptionTooLong option is too long in Message

View Source
const ErrOptionTruncated = Error("option is truncated")

ErrOptionTruncated option is truncated

View Source
const ErrOptionUnexpectedExtendMarker = Error("unexpected extended option marker")

ErrOptionUnexpectedExtendMarker unexpected extended option marker

View Source
const ErrRequestEntityIncomplete = Error("payload comes in bad order")

ErrRequestEntityIncomplete payload comes in bad order

View Source
const ErrServerAlreadyStarted = Error("server already started")

ErrServerAlreadyStarted server already started

View Source
const ErrServerNotStarted = Error("server not started")

ErrServerNotStarted server not started

View Source
const ErrShortRead = Error("short read")

ErrShortRead To construct Message we need to read more data from connection

View Source
const ErrTimeout = Error("timeout")

ErrTimeout Timeout occurs during waiting for response Message

View Source
const ErrTokenAlreadyExist = Error("token is not unique for session")

ErrTokenAlreadyExist Token in request is not unique for session

View Source
const ErrTokenNotExist = Error("token is not exist")

ErrTokenNotExist Token in request is not exist

View Source
const ErrUnexpectedReponseCode = Error("unexpected response code")

ErrUnexpectedReponseCode unexpected response code occurs

View Source
const MaxTokenSize = 8

MaxTokenSize maximum of token size that can be used in message

Variables

View Source
var DefaultServeMux = NewServeMux()

DefaultServeMux is the default ServeMux used by Serve.

Functions

func ActivateAndServe

func ActivateAndServe(l Listener, p net.Conn, handler Handler) error

ActivateAndServe activates a server with a listener from systemd, l and p should not both be non-nil. If both l and p are not nil only p will be used. Invoke handler for incoming queries.

func CalcETag

func CalcETag(payload []byte) []byte

Calculate ETag from payload via CRC64

func DefaultHandle

func DefaultHandle(handler Handler)

DefaultHandle set the default handler in the DefaultServeMux.

func DefaultHandleFunc

func DefaultHandleFunc(handler func(w ResponseWriter, r *Request))

DefaultHandleFunc set the default handler in the DefaultServeMux.

func GenerateMessageID

func GenerateMessageID() uint16

GenerateMessageID generates a message id for UDP-coap

func GenerateToken

func GenerateToken() ([]byte, error)

GenerateToken generates a random token by a given length

func Handle

func Handle(pattern string, handler Handler)

Handle registers the handler with the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFailed

func HandleFailed(w ResponseWriter, req *Request)

HandleFailed returns a HandlerFunc that returns NotFound for every request it gets.

func HandleFunc

func HandleFunc(pattern string, handler func(w ResponseWriter, r *Request))

HandleFunc registers the handler function with the given pattern in the DefaultServeMux.

func HandleRemove

func HandleRemove(pattern string)

HandleRemove deregisters the handle with the given pattern in the DefaultServeMux.

func ListenAndServe

func ListenAndServe(network string, addr string, handler Handler) error

ListenAndServe Starts a server on address and network specified Invoke handler for incoming queries.

func ListenAndServeDTLS

func ListenAndServeDTLS(network string, addr string, config *dtls.Config, handler Handler) error

ListenAndServeDTLS acts like ListenAndServeTLS, more information in http://golang.org/pkg/net/http/#ListenAndServeTLS

func ListenAndServeTLS

func ListenAndServeTLS(network, addr string, config *tls.Config, handler Handler) error

ListenAndServeTLS acts like http.ListenAndServeTLS, more information in http://golang.org/pkg/net/http/#ListenAndServeTLS

func ListenAndServeYggdrasil

func ListenAndServeYggdrasil(node coapNet.YggdrasilNode, handler Handler) error

Yggdrasil support.

func MarshalBlockOption

func MarshalBlockOption(szx BlockWiseSzx, blockNumber uint, moreBlocksFollowing bool) (uint32, error)

func SetOptionDef

func SetOptionDef(oid OptionID, format string, minLen int, maxLen int)

Types

type BlockWiseSzx

type BlockWiseSzx uint8

BlockWiseSzx enum representation for szx

const (
	//BlockWiseSzx16 block of size 16bytes
	BlockWiseSzx16 BlockWiseSzx = 0
	//BlockWiseSzx32 block of size 32bytes
	BlockWiseSzx32 BlockWiseSzx = 1
	//BlockWiseSzx64 block of size 64bytes
	BlockWiseSzx64 BlockWiseSzx = 2
	//BlockWiseSzx128 block of size 128bytes
	BlockWiseSzx128 BlockWiseSzx = 3
	//BlockWiseSzx256 block of size 256bytes
	BlockWiseSzx256 BlockWiseSzx = 4
	//BlockWiseSzx512 block of size 512bytes
	BlockWiseSzx512 BlockWiseSzx = 5
	//BlockWiseSzx1024 block of size 1024bytes
	BlockWiseSzx1024 BlockWiseSzx = 6
	//BlockWiseSzxBERT block of size n*1024bytes
	BlockWiseSzxBERT BlockWiseSzx = 7

	//BlockWiseSzxCount count of block enums
	BlockWiseSzxCount BlockWiseSzx = 8
)

func UnmarshalBlockOption

func UnmarshalBlockOption(blockVal uint32) (szx BlockWiseSzx, blockNumber uint, moreBlocksFollowing bool, err error)

type COAPCode

type COAPCode uint8

COAPCode is the type used for both request and response codes.

const (
	GET    COAPCode = 1
	POST   COAPCode = 2
	PUT    COAPCode = 3
	DELETE COAPCode = 4
)

Request Codes

const (
	Empty                   COAPCode = 0
	Created                 COAPCode = 65
	Deleted                 COAPCode = 66
	Valid                   COAPCode = 67
	Changed                 COAPCode = 68
	Content                 COAPCode = 69
	Continue                COAPCode = 95
	BadRequest              COAPCode = 128
	Unauthorized            COAPCode = 129
	BadOption               COAPCode = 130
	Forbidden               COAPCode = 131
	NotFound                COAPCode = 132
	MethodNotAllowed        COAPCode = 133
	NotAcceptable           COAPCode = 134
	RequestEntityIncomplete COAPCode = 136
	PreconditionFailed      COAPCode = 140
	RequestEntityTooLarge   COAPCode = 141
	UnsupportedMediaType    COAPCode = 143
	InternalServerError     COAPCode = 160
	NotImplemented          COAPCode = 161
	BadGateway              COAPCode = 162
	ServiceUnavailable      COAPCode = 163
	GatewayTimeout          COAPCode = 164
	ProxyingNotSupported    COAPCode = 165
)

Response Codes

const (
	CSM     COAPCode = 225
	Ping    COAPCode = 226
	Pong    COAPCode = 227
	Release COAPCode = 228
	Abort   COAPCode = 229
)

Signaling Codes for TCP

func (COAPCode) String

func (c COAPCode) String() string

type COAPType

type COAPType uint8

COAPType represents the message type.

const (
	// Confirmable messages require acknowledgements.
	Confirmable COAPType = 0
	// NonConfirmable messages do not require acknowledgements.
	NonConfirmable COAPType = 1
	// Acknowledgement is a message indicating a response to confirmable message.
	Acknowledgement COAPType = 2
	// Reset indicates a permanent negative acknowledgement.
	Reset COAPType = 3
)

func (COAPType) String

func (t COAPType) String() string

type Client

type Client struct {
	Net            string        // if "tcp" or "tcp-tls" (COAP over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP) or "udp-mcast" for multicast
	MaxMessageSize uint32        // Max message size that could be received from peer. If not set it defaults to 1152 B.
	TLSConfig      *tls.Config   // TLS connection configuration
	DTLSConfig     *dtls.Config  // TLS connection configuration
	DialTimeout    time.Duration // set Timeout for dialer
	ReadTimeout    time.Duration // net.ClientConn.SetReadTimeout value for connections, defaults to 1 hour - overridden by Timeout when that value is non-zero
	WriteTimeout   time.Duration // net.ClientConn.SetWriteTimeout value for connections, defaults to 1 hour - overridden by Timeout when that value is non-zero
	HeartBeat      time.Duration // Defines wake up interval from operations Read, Write over connection. defaults is 100ms.

	Handler              HandlerFunc     // default handler for handling messages from server
	NotifySessionEndFunc func(err error) // if NotifySessionEndFunc is set it is called when TCP/UDP session was ended.

	BlockWiseTransfer    *bool         // Use blockWise transfer for transfer payload (default for UDP it's enabled, for TCP it's disable)
	BlockWiseTransferSzx *BlockWiseSzx // Set maximal block size of payload that will be send in fragment

	DisableTCPSignalMessages        bool // Disable tcp signal messages
	DisablePeerTCPSignalMessageCSMs bool // Disable processes Capabilities and Settings Messages from client - iotivity sends max message size without blockwise.
	MulticastHopLimit               int  //sets the hop limit field value for future outgoing multicast packets. default is 2.
}

A Client defines parameters for a COAP client.

func (*Client) Dial

func (c *Client) Dial(address string) (clientConn *ClientConn, err error)

func (*Client) DialWithContext

func (c *Client) DialWithContext(ctx context.Context, address string) (clientConn *ClientConn, err error)

DialContext connects to the address on the named network.

type ClientCommander

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

ClientCommander provides commands Get,Post,Put,Delete,Observe For compare use ClientCommander.Equal

func (*ClientCommander) Close

func (cc *ClientCommander) Close() error

Close close connection

func (*ClientCommander) Delete

func (cc *ClientCommander) Delete(path string) (Message, error)

Delete deletes the resource identified by the request path

func (*ClientCommander) DeleteWithContext

func (cc *ClientCommander) DeleteWithContext(ctx context.Context, path string) (Message, error)

DeleteContext deletes with context the resource identified by the request path

func (*ClientCommander) Equal

func (cc *ClientCommander) Equal(cc1 *ClientCommander) bool

Equal compare two ClientCommanders

func (*ClientCommander) Exchange

func (cc *ClientCommander) Exchange(m Message) (Message, error)

Exchange same as ExchangeContext without context

func (*ClientCommander) ExchangeWithContext

func (cc *ClientCommander) ExchangeWithContext(ctx context.Context, m Message) (Message, error)

ExchangeContext performs a synchronous query with context. It sends the message m to the address contained in a and waits for a reply.

ExchangeContext does not retry a failed query, nor will it fall back to TCP in case of truncation.

func (*ClientCommander) Get

func (cc *ClientCommander) Get(path string) (Message, error)

Get retrieves the resource identified by the request path

func (*ClientCommander) GetWithContext

func (cc *ClientCommander) GetWithContext(ctx context.Context, path string) (Message, error)

GetContext retrieves with context the resource identified by the request path

func (*ClientCommander) LocalAddr

func (cc *ClientCommander) LocalAddr() net.Addr

LocalAddr implements the networkSession.LocalAddr method.

func (*ClientCommander) NewDeleteRequest

func (cc *ClientCommander) NewDeleteRequest(path string) (Message, error)

NewDeleteRequest creates delete request

func (*ClientCommander) NewGetRequest

func (cc *ClientCommander) NewGetRequest(path string) (Message, error)

NewGetRequest creates get request

func (*ClientCommander) NewMessage

func (cc *ClientCommander) NewMessage(p MessageParams) Message

NewMessage creates message for request

func (*ClientCommander) NewPostRequest

func (cc *ClientCommander) NewPostRequest(path string, contentFormat MediaType, body io.Reader) (Message, error)

NewPostRequest creates post request

func (*ClientCommander) NewPutRequest

func (cc *ClientCommander) NewPutRequest(path string, contentFormat MediaType, body io.Reader) (Message, error)

NewPutRequest creates put request

func (*ClientCommander) Observe

func (cc *ClientCommander) Observe(path string, observeFunc func(req *Request)) (*Observation, error)

func (*ClientCommander) ObserveWithContext

func (cc *ClientCommander) ObserveWithContext(
	ctx context.Context,
	path string,
	observeFunc func(req *Request),
	options ...func(Message),
) (*Observation, error)

ObserveContext subscribe to severon path. After subscription and every change on path, server sends immediately response

func (*ClientCommander) Ping

func (cc *ClientCommander) Ping(timeout time.Duration) error

Ping send a ping message and wait for a pong response

func (*ClientCommander) PingWithContext

func (cc *ClientCommander) PingWithContext(ctx context.Context) error

PingContext send with context a ping message and wait for a pong response

func (*ClientCommander) Post

func (cc *ClientCommander) Post(path string, contentFormat MediaType, body io.Reader) (Message, error)

Post updates the resource identified by the request path

func (*ClientCommander) PostWithContext

func (cc *ClientCommander) PostWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error)

PostContext updates with context the resource identified by the request path

func (*ClientCommander) Put

func (cc *ClientCommander) Put(path string, contentFormat MediaType, body io.Reader) (Message, error)

Put creates the resource identified by the request path

func (*ClientCommander) PutWithContext

func (cc *ClientCommander) PutWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error)

PutContext creates with context the resource identified by the request path

func (*ClientCommander) RemoteAddr

func (cc *ClientCommander) RemoteAddr() net.Addr

RemoteAddr implements the networkSession.RemoteAddr method.

func (*ClientCommander) Sequence

func (cc *ClientCommander) Sequence() uint64

Sequence discontinuously unique growing number for connection.

func (*ClientCommander) WriteMsg

func (cc *ClientCommander) WriteMsg(m Message) error

WriteMsg sends direct a message through the connection

func (*ClientCommander) WriteMsgWithContext

func (cc *ClientCommander) WriteMsgWithContext(ctx context.Context, m Message) error

WriteContextMsg sends with context direct a message through the connection

type ClientConn

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

A ClientConn represents a connection to a COAP server.

func Dial

func Dial(network, address string) (*ClientConn, error)

Dial connects to the address on the named network.

func DialDTLS

func DialDTLS(network, address string, config *dtls.Config) (conn *ClientConn, err error)

DialDTLS connects to the address on the named network with DTLS.

func DialDTLSWithTimeout

func DialDTLSWithTimeout(network, address string, config *dtls.Config, timeout time.Duration) (conn *ClientConn, err error)

DialDTLSWithTimeout acts like DialwriteDeadlineDTLS but takes a timeout.

func DialTLS

func DialTLS(network, address string, tlsConfig *tls.Config) (conn *ClientConn, err error)

DialTLS connects to the address on the named network with TLS.

func DialTLSWithTimeout

func DialTLSWithTimeout(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *ClientConn, err error)

DialTLSWithTimeout acts like DialTLS but takes a timeout.

func DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (*ClientConn, error)

DialTimeout acts like Dial but takes a timeout.

func DialYggdrasil

func DialYggdrasil(node coapNet.YggdrasilNode, address string) (*ClientConn, error)

func (*ClientConn) Close

func (co *ClientConn) Close() error

Close close connection

func (*ClientConn) Delete

func (co *ClientConn) Delete(path string) (Message, error)

func (*ClientConn) DeleteWithContext

func (co *ClientConn) DeleteWithContext(ctx context.Context, path string) (Message, error)

Delete delete the resource identified by the request path

func (*ClientConn) Exchange

func (co *ClientConn) Exchange(m Message) (Message, error)

func (*ClientConn) ExchangeWithContext

func (co *ClientConn) ExchangeWithContext(ctx context.Context, m Message) (Message, error)

ExchangeContext performs a synchronous query. It sends the message m to the address contained in a and waits for a reply.

ExchangeContext does not retry a failed query, nor will it fall back to TCP in case of truncation. To specify a local address or a timeout, the caller has to set the `Client.Dialer` attribute appropriately

func (*ClientConn) Get

func (co *ClientConn) Get(path string) (Message, error)

GetContext retrieve the resource identified by the request path

func (*ClientConn) GetWithContext

func (co *ClientConn) GetWithContext(ctx context.Context, path string) (Message, error)

func (*ClientConn) LocalAddr

func (co *ClientConn) LocalAddr() net.Addr

LocalAddr implements the networkSession.LocalAddr method.

func (*ClientConn) NewDeleteRequest

func (co *ClientConn) NewDeleteRequest(path string) (Message, error)

NewDeleteRequest creates delete request

func (*ClientConn) NewGetRequest

func (co *ClientConn) NewGetRequest(path string) (Message, error)

NewGetRequest creates get request

func (*ClientConn) NewMessage

func (co *ClientConn) NewMessage(p MessageParams) Message

NewMessage Create message for request

func (*ClientConn) NewPostRequest

func (co *ClientConn) NewPostRequest(path string, contentFormat MediaType, body io.Reader) (Message, error)

NewPostRequest creates post request

func (*ClientConn) NewPutRequest

func (co *ClientConn) NewPutRequest(path string, contentFormat MediaType, body io.Reader) (Message, error)

NewPutRequest creates put request

func (*ClientConn) Observe

func (co *ClientConn) Observe(path string, observeFunc func(req *Request)) (*Observation, error)

func (*ClientConn) ObserveWithContext

func (co *ClientConn) ObserveWithContext(
	ctx context.Context,
	path string,
	observeFunc func(req *Request),
	options ...func(Message),
) (*Observation, error)

func (*ClientConn) Ping

func (co *ClientConn) Ping(timeout time.Duration) error

Ping send a ping message and wait for a pong response

func (*ClientConn) PingWithContext

func (co *ClientConn) PingWithContext(ctx context.Context) error

Ping send a ping message and wait for a pong response

func (*ClientConn) Post

func (co *ClientConn) Post(path string, contentFormat MediaType, body io.Reader) (Message, error)

func (*ClientConn) PostWithContext

func (co *ClientConn) PostWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error)

Post update the resource identified by the request path

func (*ClientConn) Put

func (co *ClientConn) Put(path string, contentFormat MediaType, body io.Reader) (Message, error)

func (*ClientConn) PutWithContext

func (co *ClientConn) PutWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error)

PutContext create the resource identified by the request path

func (*ClientConn) RemoteAddr

func (co *ClientConn) RemoteAddr() net.Addr

RemoteAddr implements the networkSession.RemoteAddr method.

func (*ClientConn) Sequence

func (co *ClientConn) Sequence() uint64

Sequence discontinuously unique growing number for connection.

func (*ClientConn) WriteMsg

func (co *ClientConn) WriteMsg(m Message) error

func (*ClientConn) WriteMsgWithContext

func (co *ClientConn) WriteMsgWithContext(ctx context.Context, m Message) error

WriteContextMsg sends direct a message through the connection

type DgramMessage

type DgramMessage struct {
	MessageBase
	// contains filtered or unexported fields
}

DgramMessage implements Message interface.

func NewDgramMessage

func NewDgramMessage(p MessageParams) *DgramMessage

func ParseDgramMessage

func ParseDgramMessage(data []byte) (*DgramMessage, error)

ParseDgramMessage extracts the Message from the given input.

func (*DgramMessage) MarshalBinary

func (m *DgramMessage) MarshalBinary(buf io.Writer) error

MarshalBinary produces the binary form of this DgramMessage.

func (*DgramMessage) MessageID

func (m *DgramMessage) MessageID() uint16

func (*DgramMessage) SetMessageID

func (m *DgramMessage) SetMessageID(messageID uint16)

SetMessageID

func (*DgramMessage) ToBytesLength

func (m *DgramMessage) ToBytesLength() (int, error)

ToBytesLength gets the length of the message

func (*DgramMessage) UnmarshalBinary

func (m *DgramMessage) UnmarshalBinary(data []byte) error

UnmarshalBinary parses the given binary slice as a DgramMessage.

type Error

type Error string

Error errors type of coap

func (Error) Error

func (e Error) Error() string

type Handler

type Handler interface {
	ServeCOAP(w ResponseWriter, r *Request)
}

Handler is implemented by any value that implements ServeCOAP.

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type is an adapter to allow the use of ordinary functions as COAP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

func (HandlerFunc) ServeCOAP

func (f HandlerFunc) ServeCOAP(w ResponseWriter, r *Request)

ServeCOAP calls f(w, r).

type Listener

type Listener interface {
	Close() error
	AcceptWithContext(ctx context.Context) (net.Conn, error)
}

Listener defined used by coap

type MediaType

type MediaType uint16

MediaType specifies the content format of a message.

const (
	TextPlain         MediaType = 0     // text/plain;charset=utf-8
	AppCoseEncrypt0   MediaType = 16    // application/cose; cose-type="cose-encrypt0" (RFC 8152)
	AppCoseMac0       MediaType = 17    // application/cose; cose-type="cose-mac0" (RFC 8152)
	AppCoseSign1      MediaType = 18    // application/cose; cose-type="cose-sign1" (RFC 8152)
	AppLinkFormat     MediaType = 40    // application/link-format
	AppXML            MediaType = 41    // application/xml
	AppOctets         MediaType = 42    // application/octet-stream
	AppExi            MediaType = 47    // application/exi
	AppJSON           MediaType = 50    // application/json
	AppJsonPatch      MediaType = 51    //application/json-patch+json (RFC6902)
	AppJsonMergePatch MediaType = 52    //application/merge-patch+json (RFC7396)
	AppCBOR           MediaType = 60    //application/cbor (RFC 7049)
	AppCWT            MediaType = 61    //application/cwt
	AppCoseEncrypt    MediaType = 96    //application/cose; cose-type="cose-encrypt" (RFC 8152)
	AppCoseMac        MediaType = 97    //application/cose; cose-type="cose-mac" (RFC 8152)
	AppCoseSign       MediaType = 98    //application/cose; cose-type="cose-sign" (RFC 8152)
	AppCoseKey        MediaType = 101   //application/cose-key (RFC 8152)
	AppCoseKeySet     MediaType = 102   //application/cose-key-set (RFC 8152)
	AppCoapGroup      MediaType = 256   //coap-group+json (RFC 7390)
	AppOcfCbor        MediaType = 10000 //application/vnd.ocf+cbor
	AppLwm2mTLV       MediaType = 11542 //application/vnd.oma.lwm2m+tlv
	AppLwm2mJSON      MediaType = 11543 //application/vnd.oma.lwm2m+json
)

Content formats.

func (MediaType) String

func (c MediaType) String() string

type Message

type Message interface {
	Type() COAPType
	Code() COAPCode
	MessageID() uint16
	Token() []byte
	Payload() []byte
	AllOptions() options

	IsConfirmable() bool
	Options(o OptionID) []interface{}
	Option(o OptionID) interface{}

	Path() []string
	PathString() string
	SetPathString(s string)
	SetPath(s []string)
	SetType(typ COAPType)
	Query() []string
	QueryString() string
	SetQueryString(string)
	SetQuery([]string)
	SetURIQuery(s string)
	SetObserve(b uint32)
	SetPayload(p []byte)
	RemoveOption(opID OptionID)
	AddOption(opID OptionID, val interface{})
	SetOption(opID OptionID, val interface{})
	MarshalBinary(buf io.Writer) error
	UnmarshalBinary(data []byte) error
	SetToken(t []byte)
	SetMessageID(messageID uint16)
	ToBytesLength() (int, error)
	SetCode(code COAPCode)
	// contains filtered or unexported methods
}

Message represents the COAP message

type MessageBase

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

MessageBase is a CoAP message.

func (*MessageBase) AddOption

func (m *MessageBase) AddOption(opID OptionID, val interface{})

AddOption adds an option.

func (*MessageBase) AllOptions

func (m *MessageBase) AllOptions() options

func (*MessageBase) Code

func (m *MessageBase) Code() COAPCode

func (*MessageBase) IsConfirmable

func (m *MessageBase) IsConfirmable() bool

IsConfirmable returns true if this message is confirmable.

func (*MessageBase) Option

func (m *MessageBase) Option(o OptionID) interface{}

Option gets the first value for the given option ID.

func (*MessageBase) Options

func (m *MessageBase) Options(o OptionID) []interface{}

Options gets all the values for the given option.

func (*MessageBase) Path

func (m *MessageBase) Path() []string

Path gets the Path set on this message if any.

func (*MessageBase) PathString

func (m *MessageBase) PathString() string

PathString gets a path as a / separated string.

func (*MessageBase) Payload

func (m *MessageBase) Payload() []byte

func (*MessageBase) Query

func (m *MessageBase) Query() []string

Query gets the Query set on this message if any.

func (*MessageBase) QueryString

func (m *MessageBase) QueryString() string

QueryString gets a path as an ampersand separated string.

func (*MessageBase) RemoveOption

func (m *MessageBase) RemoveOption(opID OptionID)

RemoveOption removes all references to an option

func (*MessageBase) SetCode

func (m *MessageBase) SetCode(code COAPCode)

SetCode sets the coap code on the message

func (*MessageBase) SetObserve

func (m *MessageBase) SetObserve(b uint32)

Set Observer attribute to the message

func (*MessageBase) SetOption

func (m *MessageBase) SetOption(opID OptionID, val interface{})

SetOption sets an option, discarding any previous value

func (*MessageBase) SetPath

func (m *MessageBase) SetPath(s []string)

SetPath updates or adds a URIPath attribute on this message.

func (*MessageBase) SetPathString

func (m *MessageBase) SetPathString(s string)

SetPathString sets a path by a / separated string.

func (*MessageBase) SetPayload

func (m *MessageBase) SetPayload(p []byte)

SetPayload

func (*MessageBase) SetQuery

func (m *MessageBase) SetQuery(s []string)

SetQuery updates or adds a URIQuery attribute on this message.

func (*MessageBase) SetQueryString

func (m *MessageBase) SetQueryString(s string)

SetQueryString sets a query by an ampersand separated string.

func (*MessageBase) SetToken

func (m *MessageBase) SetToken(p []byte)

SetToken

func (*MessageBase) SetType

func (m *MessageBase) SetType(typ COAPType)

func (*MessageBase) SetURIQuery

func (m *MessageBase) SetURIQuery(s string)

Set URIQuery attibute to the message

func (*MessageBase) Token

func (m *MessageBase) Token() []byte

func (*MessageBase) Type

func (m *MessageBase) Type() COAPType

type MessageParams

type MessageParams struct {
	Type      COAPType
	Code      COAPCode
	MessageID uint16
	Token     []byte
	Payload   []byte
}

MessageParams params to create COAP message

type MulticastClient

type MulticastClient struct {
	Net            string        // "udp" / "udp4" / "udp6"
	MaxMessageSize uint32        // Max message size that could be received from peer. If not set it defaults to 1152 B.
	DialTimeout    time.Duration // set Timeout for dialer
	ReadTimeout    time.Duration // net.ClientConn.SetReadTimeout value for connections, defaults to 1 hour - overridden by Timeout when that value is non-zero
	WriteTimeout   time.Duration // net.ClientConn.SetWriteTimeout value for connections, defaults to 1 hour - overridden by Timeout when that value is non-zero
	HeartBeat      time.Duration // The maximum of time for synchronization go-routines, defaults to 30 seconds - overridden by Timeout when that value is non-zero if it occurs, then it call log.Fatal

	Handler              HandlerFunc     // default handler for handling messages from server
	NotifySessionEndFunc func(err error) // if NotifySessionEndFunc is set it is called when TCP/UDP session was ended.

	BlockWiseTransfer    *bool         // Use blockWise transfer for transfer payload (default for UDP it's enabled, for TCP it's disable)
	BlockWiseTransferSzx *BlockWiseSzx // Set maximal block size of payload that will be send in fragment

	MulticastHopLimit int //sets the hop limit field value for future outgoing multicast packets. default is 2.
	// contains filtered or unexported fields
}

A MulticastClient defines parameters for a COAP client.

func (*MulticastClient) Dial

func (c *MulticastClient) Dial(address string) (*MulticastClientConn, error)

func (*MulticastClient) DialWithContext

func (c *MulticastClient) DialWithContext(ctx context.Context, address string) (*MulticastClientConn, error)

DialContext connects with context to the address on the named network.

type MulticastClientConn

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

A ClientConn represents a connection to a COAP server.

func (*MulticastClientConn) Close

func (mconn *MulticastClientConn) Close()

Close close connection

func (*MulticastClientConn) LocalAddr

func (mconn *MulticastClientConn) LocalAddr() net.Addr

LocalAddr implements the networkSession.LocalAddr method.

func (*MulticastClientConn) NewGetRequest

func (mconn *MulticastClientConn) NewGetRequest(path string) (Message, error)

NewGetRequest creates get request

func (*MulticastClientConn) NewMessage

func (mconn *MulticastClientConn) NewMessage(p MessageParams) Message

NewMessage Create message for request

func (*MulticastClientConn) Publish

func (mconn *MulticastClientConn) Publish(path string, responseHandler func(req *Request)) (*ResponseWaiter, error)

Publish subscribes to sever on path. After subscription and every change on path, server sends immediately response

func (*MulticastClientConn) PublishMsg

func (mconn *MulticastClientConn) PublishMsg(req Message, responseHandler func(req *Request)) (*ResponseWaiter, error)

PublishMsg subscribes to sever with GET message. After subscription and every change on path, server sends immediately response

func (*MulticastClientConn) PublishMsgWithContext

func (mconn *MulticastClientConn) PublishMsgWithContext(ctx context.Context, req Message, responseHandler func(req *Request)) (*ResponseWaiter, error)

PublishMsgWithContext subscribes with context to sever with GET message. After subscription and every change on path, server sends immediately response

func (*MulticastClientConn) PublishWithContext

func (mconn *MulticastClientConn) PublishWithContext(ctx context.Context, path string, responseHandler func(req *Request)) (*ResponseWaiter, error)

PublishContext subscribes with context to sever on path. After subscription and every change on path, server sends immediately response

func (*MulticastClientConn) RemoteAddr

func (mconn *MulticastClientConn) RemoteAddr() net.Addr

RemoteAddr implements the networkSession.RemoteAddr method.

func (*MulticastClientConn) WriteMsg

func (mconn *MulticastClientConn) WriteMsg(m Message) error

WriteMsg sends a message through the connection co.

func (*MulticastClientConn) WriteMsgWithContext

func (mconn *MulticastClientConn) WriteMsgWithContext(ctx context.Context, m Message) error

WriteContextMsg sends a message with context through the connection co.

type Observation

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

Observation represents subscription to resource on the server

func (*Observation) Cancel

func (o *Observation) Cancel() error

func (*Observation) CancelWithContext

func (o *Observation) CancelWithContext(ctx context.Context) error

CancelContext remove observation from server. For recreate observation use Observe.

type OptionID

type OptionID uint16

OptionID identifies an option in a message.

const (
	IfMatch       OptionID = 1
	URIHost       OptionID = 3
	ETag          OptionID = 4
	IfNoneMatch   OptionID = 5
	Observe       OptionID = 6
	URIPort       OptionID = 7
	LocationPath  OptionID = 8
	URIPath       OptionID = 11
	ContentFormat OptionID = 12
	MaxAge        OptionID = 14
	URIQuery      OptionID = 15
	Accept        OptionID = 17
	LocationQuery OptionID = 20
	Block2        OptionID = 23
	Block1        OptionID = 27
	Size2         OptionID = 28
	ProxyURI      OptionID = 35
	ProxyScheme   OptionID = 39
	Size1         OptionID = 60
	NoResponse    OptionID = 258
)

Option IDs.

const (
	MaxMessageSize    OptionID = 2
	BlockWiseTransfer OptionID = 4
)
const (
	AlternativeAddress OptionID = 2
	HoldOff            OptionID = 4
)

Signal Release Option IDs

+-----+---+---+---------------------+--------+--------+---------+
| No. | C | R | Name                | Format | Length | Default |
+-----+---+---+---------------------+--------+--------+---------+
|   2 |   | x | Alternative-Address | string | 1-255  | (none)  |
|   4 |   |   | Hold-Off            | uint3  | 0-3    | (none)  |
+-----+---+---+---------------------+--------+--------+---------+
C=Critical, R=Repeatable
const (
	BadCSMOption OptionID = 2
)

Signal Abort Option IDs

+-----+---+---+---------------------+--------+--------+---------+
| No. | C | R | Name                | Format | Length | Default |
+-----+---+---+---------------------+--------+--------+---------+
|   2 |   |   | Bad-CSM-Option      | uint   | 0-2    | (none)  |
+-----+---+---+---------------------+--------+--------+---------+
C=Critical, R=Repeatable
const (
	Custody OptionID = 2
)

type Request

type Request struct {
	Msg      Message
	Client   *ClientConn
	Ctx      context.Context
	Sequence uint64 // discontinuously growing number for every request from connection starts from 0
}

type ResponseWaiter

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

ResponseWaiter represents subscription to resource on the server

func (*ResponseWaiter) Cancel

func (r *ResponseWaiter) Cancel() error

Cancel remove observation from server. For recreate observation use Observe.

type ResponseWriter

type ResponseWriter interface {
	Write(p []byte) (n int, err error)
	// WriteContext response with payload.
	// If p is nil it writes response without payload.
	// If p is non-nil then SetContentFormat must be called before Write otherwise Write fails.
	WriteWithContext(ctx context.Context, p []byte) (n int, err error)
	// SetCode for response that is send via Write call.
	//
	// If SetCode is not called explicitly, the first call to Write
	// will trigger an implicit SetCode(Content/Changed/Deleted/Created - depends on request).
	// Thus explicit calls to SetCode are mainly used to send error codes.
	SetCode(code COAPCode)
	// SetContentFormat of payload for response that is send via Write call.
	//
	// If SetContentFormat is not called and Write is called with non-nil argumet
	// If SetContentFormat is set but Write is called with nil argument it fails
	SetContentFormat(contentFormat MediaType)

	//NewResponse create response with code and token, messageid against request
	NewResponse(code COAPCode) Message

	WriteMsg(msg Message) error
	//WriteContextMsg to client.
	//If Option ContentFormat is set and Payload is not set then call will failed.
	//If Option ContentFormat is not set and Payload is set then call will failed.
	WriteMsgWithContext(ctx context.Context, msg Message) error
	// contains filtered or unexported methods
}

A ResponseWriter interface is used by an CAOP handler to construct an COAP response. For Obsevation (GET+option observe) it can be stored and used in another go-routine with using calls NewResponse, WriteContextMsg

type ServeMux

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

ServeMux is an COAP request multiplexer. It matches the path name of each incoming request against a list of registered patterns add calls the handler for the pattern with same name. ServeMux is also safe for concurrent access from multiple goroutines.

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) DefaultHandle

func (mux *ServeMux) DefaultHandle(handler Handler)

DefaultHandle set default handler to the ServeMux

func (*ServeMux) DefaultHandleFunc

func (mux *ServeMux) DefaultHandleFunc(handler func(w ResponseWriter, r *Request))

DefaultHandleFunc set a default handler function to the ServeMux.

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler) error

Handle adds a handler to the ServeMux for pattern.

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(w ResponseWriter, r *Request))

HandleFunc adds a handler function to the ServeMux for pattern.

func (*ServeMux) HandleRemove

func (mux *ServeMux) HandleRemove(pattern string) error

HandleRemove deregistrars the handler specific for pattern from the ServeMux.

func (*ServeMux) ServeCOAP

func (mux *ServeMux) ServeCOAP(w ResponseWriter, r *Request)

ServeCOAP dispatches the request to the handler whose pattern most closely matches the request message. If DefaultServeMux is used the correct thing for DS queries is done: a possible parent is sought. If no handler is found a standard NotFound message is returned

type Server

type Server struct {
	// Address to listen on, ":COAP" if empty.
	Addr string
	// if "tcp" or "tcp-tls" (COAP over TLS) it will invoke a TCP listener, otherwise an UDP one
	Net string
	// YggdrasilNode
	YggdrasilNode coapNet.YggdrasilNode
	// TCP Listener to use, this is to aid in systemd's socket activation.
	Listener Listener
	// TLS connection configuration
	TLSConfig *tls.Config
	// DTLSConfig connection configuration
	DTLSConfig *dtls.Config
	// UDP/TCP "Listener/Connection" to use, this is to aid in systemd's socket activation.
	Conn net.Conn
	// Handler to invoke, COAP.DefaultServeMux if nil.
	Handler Handler
	// Max message size that could be received from peer. Min 16bytes. If not set
	// it defaults is unlimited.
	MaxMessageSize uint32
	// The net.Conn.SetReadTimeout value for new connections, defaults to 1hour.
	ReadTimeout time.Duration
	// The net.Conn.SetWriteTimeout value for new connections, defaults to 1hour.
	WriteTimeout time.Duration
	// If NotifyStartedFunc is set it is called once the server has started listening.
	NotifyStartedFunc func()
	// Defines wake up interval from operations Read, Write over connection. defaults is 100ms.
	HeartBeat time.Duration

	// If NotifyNewSession is set it is called when new TCP/UDP session was created.
	NotifySessionNewFunc func(w *ClientConn)
	// If NotifyNewSession is set it is called when TCP/UDP session was ended.
	NotifySessionEndFunc func(w *ClientConn, err error)
	// The interfaces that will be used for udp-mcast (default uses the system assigned for multicast)
	UDPMcastInterfaces []net.Interface
	// Use blockWise transfer for transfer payload (default for UDP it's enabled, for TCP it's disable)
	BlockWiseTransfer *bool
	// Set maximal block size of payload that will be send in fragment
	BlockWiseTransferSzx *BlockWiseSzx
	// Disable send tcp signal messages
	DisableTCPSignalMessages bool
	// Disable processes Capabilities and Settings Messages from client - iotivity sends max message size without blockwise.
	DisablePeerTCPSignalMessageCSMs bool
	// contains filtered or unexported fields
}

A Server defines parameters for running an COAP server.

func (*Server) ActivateAndServe

func (srv *Server) ActivateAndServe() error

ActivateAndServe starts a coapserver with the PacketConn or Listener configured in *Server. Its main use is to start a server from systemd.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe starts a coapserver on the configured address in *Server.

func (*Server) Shutdown

func (srv *Server) Shutdown() error

Shutdown shuts down a server. After a call to Shutdown, ListenAndServe and ActivateAndServe will return.

type TcpMessage

type TcpMessage struct {
	MessageBase
}

TcpMessage is a CoAP MessageBase that can encode itself for TCP transport.

func Decode

func Decode(reader io.Reader) (*TcpMessage, error)

Decode reads a single message from its input.

func NewTcpMessage

func NewTcpMessage(p MessageParams) *TcpMessage

func PullTcp

func PullTcp(data []byte) (*TcpMessage, []byte, error)

PullTcp extracts a complete TCP CoAP message from the front of a byte queue.

Return values:

*TcpMessage: On success, points to the extracted message; nil if a complete
             message could not be extracted.
[]byte: The unread portion of of the supplied byte buffer.  If a message
        was not extracted, this is the unchanged buffer that was passed in.
error: Non-nil if the buffer contains an invalid CoAP message.

Note: It is not an error if the supplied buffer does not contain a complete message. In such a case, nil *TclMessage and error values are returned along with the original buffer.

func (*TcpMessage) MarshalBinary

func (m *TcpMessage) MarshalBinary(buf io.Writer) error

func (*TcpMessage) MessageID

func (m *TcpMessage) MessageID() uint16

func (*TcpMessage) SetMessageID

func (m *TcpMessage) SetMessageID(messageID uint16)

SetMessageID

func (*TcpMessage) ToBytesLength

func (m *TcpMessage) ToBytesLength() (int, error)

func (*TcpMessage) UnmarshalBinary

func (m *TcpMessage) UnmarshalBinary(data []byte) error

type TokenHandler

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

TokenHandler container for regirstration handlers by token

func (*TokenHandler) Add

func (s *TokenHandler) Add(token []byte, handler func(w ResponseWriter, r *Request)) error

Add register handler for token

func (*TokenHandler) Handle

func (s *TokenHandler) Handle(w ResponseWriter, r *Request, next HandlerFunc)

Handle call handler for request if exist otherwise use next

func (*TokenHandler) Remove

func (s *TokenHandler) Remove(token []byte) error

Remove unregister handler for token

Jump to

Keyboard shortcuts

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