coap

package module
v0.0.0-...-2b2386e Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2019 License: MIT Imports: 25 Imported by: 1

README

Build Status codecov Go Report

CoAP Client and Server for go

Features supported:

Not yet implemented:

  • CoAP over DTLS

Samples

Simple
Server UDP/TCP
	// Server
	// See /examples/simple/server/main.go
	func handleA(w coap.ResponseWriter, req *coap.Request) {
		log.Printf("Got message in handleA: path=%q: %#v from %v", req.Msg.Path(), req.Msg, req.Client.RemoteAddr())
		w.SetContentFormat(coap.TextPlain)
		log.Printf("Transmitting from A")
		if _, err := w.Write([]byte("hello world")); err != nil {
			log.Printf("Cannot send response: %v", err)
		}
	}

	func main() {
		mux := coap.NewServeMux()
		mux.Handle("/a", coap.HandlerFunc(handleA))

		log.Fatal(coap.ListenAndServe(":5688", "udp", mux))
		
		// for tcp
		// log.Fatal(coap.ListenAndServe(":5688", "tcp", mux))

		// fot tcp-tls
		// log.Fatal(coap.ListenAndServeTLS(":5688", CertPEMBlock, KeyPEMBlock, mux))
	}
Client
	// Client
	// See /examples/simpler/client/main.go
	func main() {
		co, err := coap.Dial("udp", "localhost:5688")
		
		// for tcp
		// co, err := coap.Dial("tcp", "localhost:5688")
		
		// for tcp-tls
		// co, err := coap.DialWithTLS("localhost:5688", &tls.Config{InsecureSkipVerify: true})

		if err != nil {
			log.Fatalf("Error dialing: %v", err)
		}

		resp, err := co.Get(path)

		if err != nil {
			log.Fatalf("Error sending request: %v", err)
		}

		log.Printf("Response payload: %v", resp.Payload())
	}
Observe / Notify
Server

Look to examples/observe/server/main.go

Client

Look to examples/observe/client/main.go

Multicast
Server

Look to examples/mcast/server/main.go

Client

Look to examples/mcast/client/main.go

License

MIT

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 ErrMessageInvalidVersion = Error("invalid version of Message")

ErrMessageInvalidVersion invalid version of Message

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.

View Source
var ErrIncoherentHandshakeMsg = errors.New("go-coap: incoherent handshake message")

Functions

func ActivateAndServe

func ActivateAndServe(l net.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(addr string, network string, handler Handler) error

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

func ListenAndServeTLS

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

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

func WriteToSessionUDP

func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDPData) (int, error)

WriteToSessionUDP acts just like net.UDPConn.WriteTo(), but uses a *SessionUDPData instead of a net.Addr.

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

	Encryption bool
	KeyStore   KeyStore
	Compressor Compressor
	Psk        []byte

	RetriesQueue *RetriesQueue // Queue used to schedule, operate and cancel retries of sent messages
}

A Client defines parameters for a COAP client.

func (*Client) Dial

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

Dial 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 delete 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 performs a synchronous query. It sends the message m to the address contained in a and waits for a reply.

Exchange 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 (*ClientCommander) Get

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

Get retrieve 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)

Observe 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) Post

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

Post update the resource identified by the request path

func (*ClientCommander) Put

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

Put create the resource identified by the request path

func (*ClientCommander) ReadDeadline

func (cc *ClientCommander) ReadDeadline() time.Duration

ReadDeadline get read deadline

func (*ClientCommander) RemoteAddr

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

RemoteAddr implements the networkSession.RemoteAddr method.

func (*ClientCommander) SetReadDeadline

func (cc *ClientCommander) SetReadDeadline(timeout time.Duration)

SetReadDeadline set read deadline for timeout for Exchange

func (*ClientCommander) SetWriteDeadline

func (cc *ClientCommander) SetWriteDeadline(timeout time.Duration)

SetWriteDeadline set write deadline for timeout for Exchange and Write

func (*ClientCommander) WriteDeadline

func (cc *ClientCommander) WriteDeadline() time.Duration

WriteDeadline get read writeline

func (*ClientCommander) WriteMsg

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

WriteMsg sends 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 DialTimeout

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

DialTimeout acts like Dial but takes a timeout.

func DialTimeoutWithTLS

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

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

func (co *ClientConn) Close() error

Close close connection

func (*ClientConn) Delete

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

Delete delete the resource identified by the request path

func (*ClientConn) Exchange

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

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

Exchange 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)

Get retrieve the resource identified by the request path

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) Ping

func (co *ClientConn) Ping(timeout time.Duration) 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)

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)

Put 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) SetReadDeadline

func (co *ClientConn) SetReadDeadline(timeout time.Duration)

SetReadDeadline set read deadline for timeout for Exchange

func (*ClientConn) SetWriteDeadline

func (co *ClientConn) SetWriteDeadline(timeout time.Duration)

SetWriteDeadline set write deadline for timeout for Exchange and Write

func (*ClientConn) WriteMsg

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

Write sends direct a message through the connection

type Compressor

type Compressor interface {
	CompressPayload(j []byte) ([]byte, error)
	DecompressPayload(j []byte) ([]byte, error)
}

type Conn

type Conn interface {
	// LocalAddr get local address of the connection
	LocalAddr() net.Addr
	// RemoteAddr get peer address of the connection
	RemoteAddr() net.Addr
	// Close close the connection
	Close() error
	// contains filtered or unexported methods
}

Conn represents the connection

type DgramMessage

type DgramMessage struct {
	MessageBase
}

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) SetMessageID

func (m *DgramMessage) SetMessageID(messageID uint16)

SetMessageID

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 HSQueueMsg

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

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 KeyStore

type KeyStore interface {
	GetLocalKey() (noise.DHKey, error)
	SetLocalKey(noise.DHKey) error

	GetRemoteKey(net.Addr) ([]byte, error)
	SetRemoteKey(net.Addr, []byte) error
}

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)
	SetURIQuery(s string)
	SetObserve(b int)
	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

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) MessageID

func (m *MessageBase) MessageID() uint16

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) RemoveOption

func (m *MessageBase) RemoveOption(opID OptionID)

RemoveOption removes all references to an option

func (*MessageBase) SetObserve

func (m *MessageBase) SetObserve(b int)

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) SetToken

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

SetToken

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

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

Dial connects 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 subscribe 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) SetReadDeadline

func (mconn *MulticastClientConn) SetReadDeadline(timeout time.Duration)

SetReadDeadline set read deadline for timeout for Exchange

func (*MulticastClientConn) SetWriteDeadline

func (mconn *MulticastClientConn) SetWriteDeadline(timeout time.Duration)

SetWriteDeadline set write deadline for timeout for Exchange and Write

func (*MulticastClientConn) WriteMsg

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

WriteMsg sends a message through the connection co.

type NoisePipeState

type NoisePipeState int
const (
	START NoisePipeState = iota // our starting point

	// if we have no static key for our peer:
	XX1 // -> e
	XX2 // <- e, ee, s, es + payload  (initiator stores s as peer). Payload is empty given the responder has nothing yet to say.
	XX3 // -> s, se        + payload  (responder stores for that peer). Payload is the CoAP req from the initiator.

	// and then we're established.
	READY // send & encrypt via respective CipherStates

	// else, if we have a static key for our peer:
	IK1 // -> e, es, s, ss + payload  (payload is CoAP req)

	IK2 // <- e, ee, se    + payload  (payload is CoAP ack)

	// If something goes wrong...
	ERROR
)

type NoiseState

type NoiseState struct {
	Hs        *noise.HandshakeState
	Cs        *noise.CipherSuite
	Rng       io.Reader
	PipeState NoisePipeState

	LocalStaticKey  noise.DHKey
	RemoteStaticKey []byte
	Cs0             *noise.CipherState // the cipher used by the initiator to send (and the responder to receive)
	Cs1             *noise.CipherState // the cipher used by the initiator to receive (and the responder to send)
	Initiator       bool
	// contains filtered or unexported fields
}

func NewNoiseState

func NewNoiseState(connection Conn, initiator bool, ks KeyStore) (*NoiseState, error)

func (*NoiseState) DecryptMessage

func (ns *NoiseState) DecryptMessage(msg, payload []byte, seqnum uint8, connUDP *connUDP, sessionUDPData *SessionUDPData) (b []byte, toSend []byte, decrypted bool, err error)

func (*NoiseState) EncryptMessage

func (ns *NoiseState) EncryptMessage(msg []byte, connUDP *connUDP, sessionUDPData *SessionUDPData) ([]byte, error)

func (*NoiseState) SetupIK

func (ns *NoiseState) SetupIK() error

func (*NoiseState) SetupXX

func (ns *NoiseState) SetupXX() error

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

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

type OptionID

type OptionID uint8

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
)

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

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 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.
	Write(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 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.
	WriteMsg(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, WriteMsg

type RetriesQueue

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

func NewRetriesQueue

func NewRetriesQueue(initDelay time.Duration, multiplier int) *RetriesQueue

func (*RetriesQueue) CancelRetrySchedule

func (rq *RetriesQueue) CancelRetrySchedule(mID uint16)

func (*RetriesQueue) PopHS

func (rq *RetriesQueue) PopHS(host string) *HSQueueMsg

func (*RetriesQueue) PopMID

func (rq *RetriesQueue) PopMID(dest string) *uint16

func (*RetriesQueue) PushHS

func (rq *RetriesQueue) PushHS(msg HSQueueMsg)

func (*RetriesQueue) ScheduleRetry

func (rq *RetriesQueue) ScheduleRetry(mID uint16, b []byte, session *SessionUDPData, conn *connUDP)

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)

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)

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
	// TCP Listener to use, this is to aid in systemd's socket activation.
	Listener net.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()
	// The maximum of time for synchronization go-routines, defaults to 30 seconds, if it occurs, then it call log.Fatal
	SyncTimeout time.Duration

	// If NotifyNewSession is set it is called when new TCP/UDP session was created.
	NotifySessionNewFunc func(w *ClientCommander)
	// If NotifyNewSession is set it is called when TCP/UDP session was ended.
	NotifySessionEndFunc func(w *ClientCommander, 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

	// Used to compress packets
	Compressor Compressor

	// is encryption on or off?
	Encryption bool

	// what keystore to use for tracking remote server keys
	KeyStore KeyStore

	// psk if any
	Psk []byte

	TCPReadBufferSize  int
	TCPWriteBufferSize int

	// Queue used to schedule, operate and cancel retries of sent messages
	RetriesQueue *RetriesQueue
	// 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 SessionUDPData

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

SessionUDPData holds the remote address and the associated out-of-band data.

func ReadFromSessionUDP

func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDPData, error)

ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a net.UDPAddr.

func (*SessionUDPData) Key

func (s *SessionUDPData) Key() string

Key returns the key session for the map using

func (*SessionUDPData) RemoteAddr

func (s *SessionUDPData) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

type TcpMessage

type TcpMessage struct {
	MessageBase
}

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

func Decode

func Decode(r 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) SetMessageID

func (m *TcpMessage) SetMessageID(messageID uint16)

SetMessageID

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

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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