go-coap: github.com/go-ocf/go-coap Index | Files

package coap

import "github.com/go-ocf/go-coap"

Package coap provides a CoAP client and server.

Package coap provides a CoAP client and server.

Index

Package Files

blockwise.go client.go clientcommander.go error.go getresponsewriter.go message.go messagedgram.go messagetcp.go multicastClient.go networksession.go noresponsewriter.go request.go responsewriter.go server.go servermux.go shutdownContext.go tokenhandler.go utils.go

Constants

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.
)
const DefaultPort = 5683

DefaultPort default unsecure port for COAP server

const DefaultSecurePort = 5684

DefaultSecurePort default secure port for COAP server

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

ErrBlockInvalidSize block has invalid size

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

ErrBlockNumberExceedLimit block number exceed limit 1,048,576

const ErrConnectionClosed = Error("connection closed")

ErrConnectionClosed Connection closed

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

ErrContentFormatNotSet content format is not set

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

ErrInvalidBlockWiseSzx invalid block-wise transfer szx

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

ErrInvalidMaxMesssageSizeParameter invalid .MaxMessageSize parameter

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

ErrInvalidNetParameter invalid .Net parameter

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

ErrInvalidOptionBlock1 message has invalid value of Block1

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

ErrInvalidOptionBlock2 message has invalid value of Block2

const ErrInvalidPayload = Error("invalid payload")

ErrInvalidPayload invalid payload

const ErrInvalidPayloadSize = Error("invalid payload size")

ErrInvalidPayloadSize invalid payload size

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

ErrInvalidReponseCode response code has invalid value

const ErrInvalidRequest = Error("invalid request")

ErrInvalidRequest invalid requests

const ErrInvalidResponse = Error("invalid response")

ErrInvalidResponse invalid response received for certain token

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

ErrInvalidServerConnParameter invalid Server.Conn parameter

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

ErrInvalidServerListenerParameter invalid Server.Listener parameter

const ErrInvalidTokenLen = Error("invalid token length")

ErrInvalidTokenLen invalid token length in Message

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

ErrMessageInvalidVersion invalid version of Message

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

ErrMessageNotInterested message is not of interest to the client

const ErrMessageTruncated = Error("message is truncated")

ErrMessageTruncated message is truncated

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

ErrMsgTooLarge message it too large, for processing

const ErrNotSupported = Error("not supported")

ErrNotSupported invalid response received for certain token

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

ErrOptionGapTooLarge option gap too large in Message

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

ErrOptionTooLong option is too long in Message

const ErrOptionTruncated = Error("option is truncated")

ErrOptionTruncated option is truncated

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

ErrOptionUnexpectedExtendMarker unexpected extended option marker

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

ErrRequestEntityIncomplete payload comes in bad order

const ErrServerAlreadyStarted = Error("server already started")

ErrServerAlreadyStarted server already started

const ErrServerNotStarted = Error("server not started")

ErrServerNotStarted server not started

const ErrShortRead = Error("short read")

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

const ErrTimeout = Error("timeout")

ErrTimeout Timeout occurs during waiting for response Message

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

ErrTokenAlreadyExist Token in request is not unique for session

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

ErrTokenNotExist Token in request is not exist

const ErrUnexpectedReponseCode = Error("unexpected response code")

ErrUnexpectedReponseCode unexpected response code occurs

const MaxTokenSize = 8

MaxTokenSize maximum of token size that can be used in message

Variables

var DefaultServeMux = NewServeMux()

DefaultServeMux is the default ServeMux used by Serve.

func ActivateAndServe Uses

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 Uses

func CalcETag(payload []byte) []byte

Calculate ETag from payload via CRC64

func DefaultHandle Uses

func DefaultHandle(handler Handler)

DefaultHandle set the default handler in the DefaultServeMux.

func DefaultHandleFunc Uses

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

DefaultHandleFunc set the default handler in the DefaultServeMux.

func GenerateMessageID Uses

func GenerateMessageID() uint16

GenerateMessageID generates a message id for UDP-coap

func GenerateToken Uses

func GenerateToken() ([]byte, error)

GenerateToken generates a random token by a given length

func Handle Uses

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 Uses

func HandleFailed(w ResponseWriter, req *Request)

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

func HandleFunc Uses

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

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

func HandleRemove Uses

func HandleRemove(pattern string)

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

func ListenAndServe Uses

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

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

func ListenAndServeTLS Uses

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

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

func MarshalBlockOption Uses

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

type BlockWiseSzx Uses

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 Uses

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

type COAPCode Uses

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 Uses

func (c COAPCode) String() string

type COAPType Uses

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 Uses

func (t COAPType) String() string

type Client Uses

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
    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
}

A Client defines parameters for a COAP client.

func (*Client) Dial Uses

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

func (*Client) DialWithContext Uses

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

DialContext connects to the address on the named network.

type ClientCommander Uses

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

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

func (*ClientCommander) Close Uses

func (cc *ClientCommander) Close() error

Close close connection

func (*ClientCommander) Delete Uses

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

Delete deletes the resource identified by the request path

func (*ClientCommander) DeleteWithContext Uses

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 Uses

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

Equal compare two ClientCommanders

func (*ClientCommander) Exchange Uses

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

Exchange same as ExchangeContext without context

func (*ClientCommander) ExchangeWithContext Uses

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 Uses

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

Get retrieves the resource identified by the request path

func (*ClientCommander) GetWithContext Uses

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 Uses

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

LocalAddr implements the networkSession.LocalAddr method.

func (*ClientCommander) NewDeleteRequest Uses

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

NewDeleteRequest creates delete request

func (*ClientCommander) NewGetRequest Uses

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

NewGetRequest creates get request

func (*ClientCommander) NewMessage Uses

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

NewMessage creates message for request

func (*ClientCommander) NewPostRequest Uses

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

NewPostRequest creates post request

func (*ClientCommander) NewPutRequest Uses

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

NewPutRequest creates put request

func (*ClientCommander) Observe Uses

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

func (*ClientCommander) ObserveWithContext Uses

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

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

func (*ClientCommander) Ping Uses

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

Ping send a ping message and wait for a pong response

func (*ClientCommander) PingWithContext Uses

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

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

func (*ClientCommander) Post Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

RemoteAddr implements the networkSession.RemoteAddr method.

func (*ClientCommander) Sequence Uses

func (cc *ClientCommander) Sequence() uint64

Sequence discontinuously unique growing number for connection.

func (*ClientCommander) WriteMsg Uses

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

WriteMsg sends direct a message through the connection

func (*ClientCommander) WriteMsgWithContext Uses

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

WriteContextMsg sends with context direct a message through the connection

type ClientConn Uses

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

A ClientConn represents a connection to a COAP server.

func Dial Uses

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

Dial connects to the address on the named network.

func DialTimeout Uses

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

DialTimeout acts like Dial but takes a timeout.

func DialTimeoutWithTLS Uses

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

DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.

func DialWithTLS Uses

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

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

func (*ClientConn) Close Uses

func (co *ClientConn) Close() error

Close close connection

func (*ClientConn) Delete Uses

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

func (*ClientConn) DeleteWithContext Uses

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

Delete delete the resource identified by the request path

func (*ClientConn) Exchange Uses

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

func (*ClientConn) ExchangeWithContext Uses

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 Uses

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

GetContext retrieve the resource identified by the request path

func (*ClientConn) GetWithContext Uses

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

func (*ClientConn) LocalAddr Uses

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

LocalAddr implements the networkSession.LocalAddr method.

func (*ClientConn) NewDeleteRequest Uses

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

NewDeleteRequest creates delete request

func (*ClientConn) NewGetRequest Uses

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

NewGetRequest creates get request

func (*ClientConn) NewMessage Uses

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

NewMessage Create message for request

func (*ClientConn) NewPostRequest Uses

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

NewPostRequest creates post request

func (*ClientConn) NewPutRequest Uses

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

NewPutRequest creates put request

func (*ClientConn) Observe Uses

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

func (*ClientConn) ObserveWithContext Uses

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

func (*ClientConn) Ping Uses

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

Ping send a ping message and wait for a pong response

func (*ClientConn) PingWithContext Uses

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

Ping send a ping message and wait for a pong response

func (*ClientConn) Post Uses

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

func (*ClientConn) PostWithContext Uses

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 Uses

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

func (*ClientConn) PutWithContext Uses

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 Uses

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

RemoteAddr implements the networkSession.RemoteAddr method.

func (*ClientConn) Sequence Uses

func (co *ClientConn) Sequence() uint64

Sequence discontinuously unique growing number for connection.

func (*ClientConn) WriteMsg Uses

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

func (*ClientConn) WriteMsgWithContext Uses

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

WriteContextMsg sends direct a message through the connection

type DgramMessage Uses

type DgramMessage struct {
    MessageBase
}

DgramMessage implements Message interface.

func NewDgramMessage Uses

func NewDgramMessage(p MessageParams) *DgramMessage

func ParseDgramMessage Uses

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

ParseDgramMessage extracts the Message from the given input.

func (*DgramMessage) MarshalBinary Uses

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

MarshalBinary produces the binary form of this DgramMessage.

func (*DgramMessage) SetMessageID Uses

func (m *DgramMessage) SetMessageID(messageID uint16)

SetMessageID

func (*DgramMessage) UnmarshalBinary Uses

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

UnmarshalBinary parses the given binary slice as a DgramMessage.

type Error Uses

type Error string

Error errors type of coap

func (Error) Error Uses

func (e Error) Error() string

type Handler Uses

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

Handler is implemented by any value that implements ServeCOAP.

type HandlerFunc Uses

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 Uses

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

ServeCOAP calls f(w, r).

type Listener Uses

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

Listener defined used by coap

type MediaType Uses

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 Uses

func (c MediaType) String() string

type Message Uses

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)
    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)
    // contains filtered or unexported methods
}

Message represents the COAP message

type MessageBase Uses

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

MessageBase is a CoAP message.

func (*MessageBase) AddOption Uses

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

AddOption adds an option.

func (*MessageBase) AllOptions Uses

func (m *MessageBase) AllOptions() options

func (*MessageBase) Code Uses

func (m *MessageBase) Code() COAPCode

func (*MessageBase) IsConfirmable Uses

func (m *MessageBase) IsConfirmable() bool

IsConfirmable returns true if this message is confirmable.

func (*MessageBase) MessageID Uses

func (m *MessageBase) MessageID() uint16

func (*MessageBase) Option Uses

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

Option gets the first value for the given option ID.

func (*MessageBase) Options Uses

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

Options gets all the values for the given option.

func (*MessageBase) Path Uses

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

Path gets the Path set on this message if any.

func (*MessageBase) PathString Uses

func (m *MessageBase) PathString() string

PathString gets a path as a / separated string.

func (*MessageBase) Payload Uses

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

func (*MessageBase) Query Uses

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

Query gets the Query set on this message if any.

func (*MessageBase) QueryString Uses

func (m *MessageBase) QueryString() string

QueryString gets a path as an ampersand separated string.

func (*MessageBase) RemoveOption Uses

func (m *MessageBase) RemoveOption(opID OptionID)

RemoveOption removes all references to an option

func (*MessageBase) SetObserve Uses

func (m *MessageBase) SetObserve(b uint32)

Set Observer attribute to the message

func (*MessageBase) SetOption Uses

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

SetOption sets an option, discarding any previous value

func (*MessageBase) SetPath Uses

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

SetPath updates or adds a URIPath attribute on this message.

func (*MessageBase) SetPathString Uses

func (m *MessageBase) SetPathString(s string)

SetPathString sets a path by a / separated string.

func (*MessageBase) SetPayload Uses

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

SetPayload

func (*MessageBase) SetQuery Uses

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

SetQuery updates or adds a URIQuery attribute on this message.

func (*MessageBase) SetQueryString Uses

func (m *MessageBase) SetQueryString(s string)

SetQueryString sets a query by an ampersand separated string.

func (*MessageBase) SetToken Uses

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

SetToken

func (*MessageBase) SetURIQuery Uses

func (m *MessageBase) SetURIQuery(s string)

Set URIQuery attibute to the message

func (*MessageBase) Token Uses

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

func (*MessageBase) Type Uses

func (m *MessageBase) Type() COAPType

type MessageParams Uses

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

MessageParams params to create COAP message

type MulticastClient Uses

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
    // contains filtered or unexported fields
}

A MulticastClient defines parameters for a COAP client.

func (*MulticastClient) Dial Uses

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

func (*MulticastClient) DialWithContext Uses

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

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

type MulticastClientConn Uses

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

A ClientConn represents a connection to a COAP server.

func (*MulticastClientConn) Close Uses

func (mconn *MulticastClientConn) Close()

Close close connection

func (*MulticastClientConn) LocalAddr Uses

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

LocalAddr implements the networkSession.LocalAddr method.

func (*MulticastClientConn) NewGetRequest Uses

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

NewGetRequest creates get request

func (*MulticastClientConn) NewMessage Uses

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

NewMessage Create message for request

func (*MulticastClientConn) Publish Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

RemoteAddr implements the networkSession.RemoteAddr method.

func (*MulticastClientConn) WriteMsg Uses

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

WriteMsg sends a message through the connection co.

func (*MulticastClientConn) WriteMsgWithContext Uses

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

WriteContextMsg sends a message with context through the connection co.

type Observation Uses

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

Observation represents subscription to resource on the server

func (*Observation) Cancel Uses

func (o *Observation) Cancel() error

func (*Observation) CancelWithContext Uses

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

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

type OptionID Uses

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 Uses

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 Uses

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

ResponseWaiter represents subscription to resource on the server

func (*ResponseWaiter) Cancel Uses

func (r *ResponseWaiter) Cancel() error

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

type ResponseWriter Uses

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 Uses

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 Uses

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) DefaultHandle Uses

func (mux *ServeMux) DefaultHandle(handler Handler)

DefaultHandle set default handler to the ServeMux

func (*ServeMux) DefaultHandleFunc Uses

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

DefaultHandleFunc set a default handler function to the ServeMux.

func (*ServeMux) Handle Uses

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

Handle adds a handler to the ServeMux for pattern.

func (*ServeMux) HandleFunc Uses

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 Uses

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

HandleRemove deregistrars the handler specific for pattern from the ServeMux.

func (*ServeMux) ServeCOAP Uses

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 Uses

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
    // TCP Listener to use, this is to aid in systemd's socket activation.
    Listener Listener
    // TLS connection configuration
    TLSConfig *tls.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 to 1152 B.
    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 tcp signal messages
    DisableTCPSignalMessages bool
    // contains filtered or unexported fields
}

A Server defines parameters for running an COAP server.

func (*Server) ActivateAndServe Uses

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 Uses

func (srv *Server) ListenAndServe() error

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

func (*Server) Shutdown Uses

func (srv *Server) Shutdown() error

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

type TcpMessage Uses

type TcpMessage struct {
    MessageBase
}

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

func Decode Uses

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

Decode reads a single message from its input.

func NewTcpMessage Uses

func NewTcpMessage(p MessageParams) *TcpMessage

func PullTcp Uses

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 Uses

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

func (*TcpMessage) SetMessageID Uses

func (m *TcpMessage) SetMessageID(messageID uint16)

SetMessageID

func (*TcpMessage) UnmarshalBinary Uses

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

type TokenHandler Uses

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

TokenHandler container for regirstration handlers by token

func (*TokenHandler) Add Uses

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

Add register handler for token

func (*TokenHandler) Handle Uses

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

Handle call handler for request if exist otherwise use next

func (*TokenHandler) Remove Uses

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

Remove unregister handler for token

Package coap imports 20 packages (graph). Updated 2019-03-19. Refresh now. Tools for package owners.