coap

package module
v0.0.0-...-6b1797a Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2025 License: MIT Imports: 16 Imported by: 0

README

COAP Client/Server Library

Go Reference codecov

Purpose

Implementation of the Constrained Application Protocol (CoAP), designed to facilitate lightweight and efficient communication for resource-constrained devices in Internet of Things (IoT) and machine-to-machine (M2M) applications.

Its primary purpose is to provide developers with a performant and easy-to-use toolkit for building CoAP-based clients and servers in Go, adhering to the RFC 7252 specification.

The library supports UDP and DTLS protocols.

Structure

Encoding
  • Message type represents a complete CoAP message, encapsulating the protocol's header, options, and payload.
  • Request type models a CoAP request, adding fields and validations for response code and commonly used options.
  • Response type models a CoAP response, adding fields and validations for request method and commonly used options.

Documentation

Index

Constants

View Source
const (
	ACKTimeout      = 2 * time.Second
	ACKRandomFactor = 1.5
	MaxRetransmit   = 4
)
View Source
const (
	// ProtocolVersion is the expected version in message header.
	ProtocolVersion = 1

	// TokenLength is default length of a token in bytes
	TokenLength = 4

	// TokenMaxLength is aximum length of a token in bytes
	TokenMaxLength = 8

	// HeaderLength is the expected length of message header.
	HeaderLength = 4
)
View Source
const (
	// MaxMessageLength is the default maximum length of entire message.
	MaxMessageLength = 65535

	// MaxPayloadLength is default maximum length of a payload.
	MaxPayloadLength = 65535 - HeaderLength - 1

	// MaxOptions is the default maximum number of options.
	MaxOptions = 256

	// MaxOptionLength is the default maximum length of an individual option value.
	MaxOptionLength = 1024

	// PayloadMarker is the marker byte that indicates the presence of a payload in a CoAP message.
	PayloadMarker = 0xFF
)
View Source
const (
	// ExtendByte indicates that next header byte is an extended delta or length value.
	ExtendByte = uint8(0x0D) // 13

	// ExtendDword indicates that next two header bytes are an extended delta or length value.
	ExtendDword = uint8(0x0E) // 14

	// ExtendInvalid indicates that the extended value is invalid.
	ExtendInvalid = uint8(0x0F) // 15

	// ExtendByteOffset is the offset for extended byte values.
	ExtendByteOffset = uint16(ExtendByte) // 13

	// ExtendDwordOffset is the offset for extended dword values.
	ExtendDwordOffset = uint16(256) + uint16(ExtendByte) // 269
)

Variables

View Source
var (
	MediaTypeImageGIF  = MediaType{Code: 21, Name: `image/gif`}
	MediaTypeImagePNG  = MediaType{Code: 22, Name: `image/png`}
	MediaTypeImageJPEG = MediaType{Code: 23, Name: `image/jpeg`}
)

Image assets

View Source
var (
	MediaTypeApplicationCOSEEncrypt0 = MediaType{Code: 16, Name: `application/cose; cose-type="cose-encrypt0"`}
	MediaTypeApplicationCOSEMac0     = MediaType{Code: 17, Name: `application/cose; cose-type="cose-mac0"`}
	MediaTypeApplicationCBORSign1    = MediaType{Code: 18, Name: `application/cbor; cbor-type="cbor-sign1"`}
)

Authentication and security

View Source
var (
	MediaTypeTextPlain              = MediaType{Code: 0, Name: `text/plain; charset=utf-8`}
	MediaTypeApplicationLinkFormat  = MediaType{Code: 40, Name: `application/link-format`}
	MediaTypeApplicationXML         = MediaType{Code: 41, Name: `application/xml`}
	MediaTypeApplicationOctetStream = MediaType{Code: 42, Name: `application/octet-stream`}
	MediaTypeApplicationExi         = MediaType{Code: 47, Name: `application/exi`}
	MediaTypeApplicationJSON        = MediaType{Code: 50, Name: `application/json`}
	MediaTypeApplicationCBOR        = MediaType{Code: 60, Name: `application/cbor`}
	MediaTypeApplicationCBORSeq     = MediaType{Code: 63, Name: `application/cbor-seq`}
)
View Source
var (
	IfMatch       = OptionDef{Code: 1, Name: "IfMatch", ValueFormat: ValueFormatOpaque, Repeatable: true, MaxLen: 8}
	URIHost       = OptionDef{Code: 3, Name: "URIHost", ValueFormat: ValueFormatString, MinLen: 1, MaxLen: 255}
	ETag          = OptionDef{Code: 4, Name: "ETag", ValueFormat: ValueFormatOpaque, Repeatable: true, MinLen: 1, MaxLen: 8}
	IfNoneMatch   = OptionDef{Code: 5, Name: "IfNoneMatch", ValueFormat: ValueFormatEmpty}
	Observe       = OptionDef{Code: 6, Name: "Observe", ValueFormat: ValueFormatUint, MaxLen: 3}
	URIPort       = OptionDef{Code: 7, Name: "URIPort", ValueFormat: ValueFormatUint, MaxLen: 2}
	LocationPath  = OptionDef{Code: 8, Name: "LocationPath", ValueFormat: ValueFormatString, Repeatable: true, MaxLen: 255}
	URIPath       = OptionDef{Code: 11, Name: "URIPath", ValueFormat: ValueFormatString, Repeatable: true, MaxLen: 255}
	ContentFormat = OptionDef{Code: 12, Name: "ContentFormat", ValueFormat: ValueFormatUint, MaxLen: 2}
	MaxAge        = OptionDef{Code: 14, Name: "MaxAge", ValueFormat: ValueFormatUint, MaxLen: 4}
	URIQuery      = OptionDef{Code: 15, Name: "URIQuery", ValueFormat: ValueFormatString, Repeatable: true, MaxLen: 255}
	Accept        = OptionDef{Code: 17, Name: "Accept", ValueFormat: ValueFormatUint, MaxLen: 2}
	LocationQuery = OptionDef{Code: 20, Name: "LocationQuery", ValueFormat: ValueFormatString, Repeatable: true, MaxLen: 255}
	Block1        = OptionDef{Code: 27, Name: "Block1", ValueFormat: ValueFormatUint, MaxLen: 3}
	Block2        = OptionDef{Code: 23, Name: "Block2", ValueFormat: ValueFormatUint, MaxLen: 3}
	ProxyURI      = OptionDef{Code: 35, Name: "ProxyURI", ValueFormat: ValueFormatString, MinLen: 1, MaxLen: 1034}
	ProxyScheme   = OptionDef{Code: 39, Name: "ProxyScheme", ValueFormat: ValueFormatString, MinLen: 1, MaxLen: 255}
	Size1         = OptionDef{Code: 60, Name: "Size1", ValueFormat: ValueFormatUint, MaxLen: 4}
	Size2         = OptionDef{Code: 28, Name: "Size2", ValueFormat: ValueFormatUint, MaxLen: 4}
	NoResponse    = OptionDef{Code: 258, Name: "NoResponse", ValueFormat: ValueFormatUint, MaxLen: 1}
)

DefaultSchema defines well-known CoAP options and media types.

https://www.iana.org/assignments/core-parameters/core-parameters.xhtml#content-formats

Functions

func Decode32

func Decode32(data []byte) uint32

Decode32 decodes a uint32 value from big-endian format using the minimum number of bytes.

Panics if the length of data is not between 1 and 4 bytes.

func DecodeExtend

func DecodeExtend(data []byte, v uint8) (uint16, []byte, error)

DecodeExtend decodes an extended delta or length value from the CoAP header format.

Returns the decoded value and the remaining data slice, and an error if any.

Returns TruncatedError if the data is too short for the expected extend type,

Returns UnsupportedExtendError if the extend type is 15.

func DecodePath

func DecodePath(segments iter.Seq[string]) string

DecodePath decodes a sequence of path segments into a single path string.

func Encode32

func Encode32(v uint32, data []byte) []byte

Encode32 encodes a uint32 value in big-endian format using the minimum number of bytes

func EncodeExtend

func EncodeExtend(data []byte, v uint16) (uint8, []byte)

EncodeExtend encodes a uint16 value as an extended delta or length value in the CoAP header format.

Returns the encoded header byte and the updated data slice.

func EncodePath

func EncodePath(path string) iter.Seq[string]

EncodePath encodes a path string into a sequence of path segments.

func Index

func Index(options []Option, def OptionDef) int

Index returns index of first option with matching code in the options slice returning -1 if not found.

func Len32

func Len32(v uint32) uint16

Len32 returns minimum number of bytes required to encode a uint32 value in big-endian format

func Must

func Must(err error)

Must panics if the provided error is not nil.

func MustValue

func MustValue[T any](value T, err error) T

MustValue returns the value if err is nil, otherwise it panics with the error.

Types

type Code

type Code uint8

Code represents request method or response code.

1-byte value where the first 3 bits represent the class and the last 5 bits represent the detail.

func (Code) Class

func (c Code) Class() uint8

Class indicates the class of the request method or response code represented by the first 3 bits of the code value.

func (Code) Detail

func (c Code) Detail() uint8

Detail indicates the detail of the request method or response code represented by the last 5 bits of the code value.

func (Code) String

func (c Code) String() string

String returns a string representation of the Code.

https://datatracker.ietf.org/doc/html/rfc7252#section-12.1

type Conn

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

Conn represents a CoAP connection over a net.PacketConn with retransmission of Confirmable messages.

func ListenPacket

func ListenPacket(ctx context.Context, network string, address string, opts ConnOptions) (*Conn, error)

ListenPacket instantiates a new Conn that listens for incoming packets on the specified network and address.

func NewConn

func NewConn(delegate net.PacketConn, opts ConnOptions) *Conn

NewConn instantiates a new Conn with the provided PacketConn and options.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection and stops the retransmission queue.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

func (*Conn) Read

func (c *Conn) Read(msg *Message) (addr net.Addr, err error)

Read reads a message from the connection and returns the address it was received from.

func (*Conn) Write

func (c *Conn) Write(msg *Message, addr net.Addr) error

Write sends a message to the specified address and handles retransmission for Confirmable messages.

type ConnOptions

type ConnOptions struct {
	RetransmitOptions
	MarshalOptions
}

ConnOptions holds options for creating a new CoAP connection.

type Header struct {
	Version uint8
	Type    Type
	Code    Code
	ID      MessageID
	Token   Token
}

Header represents the CoAP message header.

func (Header) AppendBinary

func (h Header) AppendBinary(data []byte) ([]byte, error)

AppendBinary encodes the CoAP message header to the provided data slice.

Returns the updated data slice with the header appended and any error encountered during encoding.

Returns an UnsupportedVersion error if the header version does not match the expected ProtocolVersion.

Returns an UnsupportedTokenLength error if the token length exceeds the TokenMaxLength.

func (*Header) Decode

func (h *Header) Decode(data []byte) ([]byte, error)

Decode decodes the CoAP message header from the provided data slice.

Returns the remaining data after the header and any error encountered during decoding.

type InvalidCode

type InvalidCode struct {
	Code Code
}

InvalidCode is returned when the code does not match the request/response type.

func (InvalidCode) Error

func (e InvalidCode) Error() string

type InvalidOptionValueFormat

type InvalidOptionValueFormat struct {
	OptionDef
	Requested ValueFormat
	Unknown   reflect.Type
}

InvalidOptionValueFormat is returned when the value format of an option does not match the requested format.

func (InvalidOptionValueFormat) Error

func (e InvalidOptionValueFormat) Error() string

type InvalidOptionValueLength

type InvalidOptionValueLength struct {
	OptionDef
	Length uint16
}

InvalidOptionValueLength is returned when the length of an option value does not match the expected length.

func (InvalidOptionValueLength) Error

func (e InvalidOptionValueLength) Error() string

type InvalidType

type InvalidType struct {
	Type Type
}

InvalidType is returned when the message type is outside the specified range of 0-4.

https://datatracker.ietf.org/doc/html/rfc7252#section-3

func (InvalidType) Error

func (e InvalidType) Error() string

type MarshalOptions

type MarshalOptions struct {
	// Schema
	Schema *Schema

	// MaxMessageLength is the maximum length of entire message.
	MaxMessageLength uint

	// MaxPayloadLength is the maximum length of payload.
	MaxPayloadLength uint

	// MaxOptions is the maximum number of options to encode.
	MaxOptions uint

	// MaxOptionLength is the maximum size of an individual option.
	MaxOptionLength uint16
}

MarshalOptions holds options for encoding and decoding a CoAP message.

type MediaType

type MediaType struct {
	Code uint16
	Name string
}

MediaType indicates payload media type.

func UnrecognizedMediaType

func UnrecognizedMediaType(code uint16) MediaType

UnrecognizedMediaType creates a MediaType instance for unrecognized media types.

func (MediaType) Recognized

func (m MediaType) Recognized() bool

Recognized indicates whether the media type is recognized by its name.

func (MediaType) String

func (m MediaType) String() string

String implements fmt.Stringer.

type Message

type Message struct {
	Header
	Options

	Payload []byte
}

Message represents a CoAP message, which includes a header, options, and an optional payload.

func (*Message) AppendBinary

func (m *Message) AppendBinary(data []byte) ([]byte, error)

AppendBinary implements encoding.BinaryAppender

func (*Message) Decode

func (m *Message) Decode(data []byte, opts MarshalOptions) ([]byte, error)

Decode decodes the CoAP message from the provided data slice using the given schema.

Returns the remaining data after the message.

Returns MessageTooLong if the message exceeds the maximum length.

Returns PayloadTooLong if the payload exceeds the maximum length.

Returns UnmarshalError if there is an error decoding the header or options.

func (*Message) MarshalBinary

func (m *Message) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*Message) UnmarshalBinary

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

UnmarshalBinary implements encoding.BinaryUnmarshaler

type MessageID

type MessageID uint16

MessageID represents the unique identifier for a CoAP message.

2-byte value that is used for message deduplication and retransmission. Usually it is sequential.

type MessageIDSource

type MessageIDSource func() MessageID

MessageIDSource is a source function that generates

func MessageIDSequence

func MessageIDSequence(start MessageID) MessageIDSource

MessageIDSequence returns a MessageIDSource that generates sequential message IDs starting from the specified value.

Uses an atomic counter. Values wrap around when they reach the maximum value of 65535 (0xffff).

type MessageTooLong

type MessageTooLong struct {
	Limit  uint
	Length uint
}

MessageTooLong is returned when the total message length exceeds the maximum allowed length.

func (MessageTooLong) Error

func (e MessageTooLong) Error() string

type Method

type Method Code

Method represents a CoAP request method code.

const (
	GET    Method = 0x01
	POST   Method = 0x02
	PUT    Method = 0x03
	DELETE Method = 0x04
	FETCH  Method = 0x05
	PATCH  Method = 0x06
	IPATCH Method = 0x07
)

Method 0.xx Codes https://datatracker.ietf.org/doc/html/rfc7252#section-12.1.1

func (Method) String

func (m Method) String() string

String implements fmt.Stringer for Method.

type Option

type Option struct {
	OptionDef
	// contains filtered or unexported fields
}

Option represents a CoAP option, which includes its definition and uint/opaque/string value.

func MustOptionValue

func MustOptionValue(def OptionDef, value any) Option

MustOptionValue creates an Option from the provided definition and value, panicking if an error occurs.

func OptionValue

func OptionValue(def OptionDef, value any) (Option, error)

OptionValue creates an Option from the provided definition and value.

Returns an error if the value does not match the expected format or length defined in OptionDef.

func (*Option) Decode

func (o *Option) Decode(data []byte, prev uint16, opts MarshalOptions) ([]byte, error)

Decode decodes the option from the provided data slice, using the previous option code and schema.

Returns the remaining data after decoding.

Returns TruncatedError if the data is too short to decode the option.

Returns InvalidOptionValueLength if the decoded length does not match the expected length.

func (Option) Encode

func (o Option) Encode(data []byte, prev uint16) []byte

Encode appends the encoded option to the provided data slice.

func (Option) GetOpaque

func (o Option) GetOpaque() ([]byte, error)

GetOpaque returns the opaque byte slice value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

func (Option) GetString

func (o Option) GetString() (string, error)

GetString returns the string value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

func (Option) GetUint

func (o Option) GetUint() (uint32, error)

GetUint returns the uint32 value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.

func (Option) GetValue

func (o Option) GetValue() any

GetValue returns the value of the option based on its ValueFormat.

Prefer using specific getter methods like GetUint, GetOpaque, or GetString to ensure type safety and avoid reflect overhead.

Returned value is of type `uint32`, `[]byte`, or `string` depending on the ValueFormat.

Returns nil if the value format is not recognized.

func (Option) Length

func (o Option) Length() uint16

Length returns the encoded length of the option value.

func (*Option) SetOpaque

func (o *Option) SetOpaque(value []byte) error

SetOpaque sets the opaque byte slice value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Option) SetString

func (o *Option) SetString(value string) error

SetString sets the string value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Option) SetUint

func (o *Option) SetUint(value uint32) error

SetUint sets the uint32 value of the option.

Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Option) SetValue

func (o *Option) SetValue(value any) error

SetValue sets the value of the option based on its ValueFormat.

Prefer using specific setter methods like SetUint, SetOpaque, or SetString to ensure type safety and avoid reflect overhead.

The value can be of type `uint32`, `[]byte`, or `string` depending on the ValueFormat.

Note that if value is of other integer type it will be rejected.

Returns InvalidOptionValueFormat if the value type does not match the expected value format.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (Option) String

func (o Option) String() string

String returns a string representation of the Option, including its name and value.

If the name is empty it uses the code as a string representation.

type OptionDef

type OptionDef struct {
	Name        string
	Code        uint16
	ValueFormat ValueFormat
	Repeatable  bool
	MinLen      uint16
	MaxLen      uint16
}

OptionDef defines a CoAP option with its properties.

Option values are validated agains ValueForman and MinLen/MaxLen.

func UnrecognizedOptionDef

func UnrecognizedOptionDef(code uint16, maxLen uint16) OptionDef

UnrecognizedOptionDef creates an OptionDef for an unrecognized option code.

func (OptionDef) Critical

func (o OptionDef) Critical() bool

Critical returns true if option critical bit is set.

func (OptionDef) NoCacheKey

func (o OptionDef) NoCacheKey() bool

NoCacheKey returns true if option should not be used as cache key.

func (OptionDef) Recognized

func (o OptionDef) Recognized() bool

Recognized indicates whether the option is recognized by schema.

func (OptionDef) String

func (o OptionDef) String() string

String implements fmt.Stringer.

func (OptionDef) Unsafe

func (o OptionDef) Unsafe() bool

Unsafe indicate if proxy should understand this option to forward the message.

type OptionNotFound

type OptionNotFound struct {
	OptionDef
}

OptionNotFound is returned when a requested option is not found in the message options.

func (OptionNotFound) Error

func (e OptionNotFound) Error() string

type OptionNotRepeateable

type OptionNotRepeateable struct {
	OptionDef
}

OptionNotRepeateable is returned when an option that is not allowed to be repeated is found more than once in the message options.

https://datatracker.ietf.org/doc/html/rfc7252#section-5.4.1

func (OptionNotRepeateable) Error

func (e OptionNotRepeateable) Error() string

type Options

type Options []Option

Options represents a collection of CoAP options.

func SortOptions

func SortOptions(options Options) Options

SortOptions sorts the options by their code in ascending order.

Returns a new slice of options sorted by code.

func (*Options) Clear

func (o *Options) Clear(def OptionDef) int

Clear removes all occurrences of the option with matching code.

Returns number of options removed.

func (Options) Contains

func (o Options) Contains(def OptionDef) bool

Contains checks if the given option is present.

func (*Options) Decode

func (o *Options) Decode(data []byte, opts MarshalOptions) ([]byte, error)

Decode decodes options from data using schema.

Returns the remaining data after options have been decoded.

Returns TruncatedError if the data is too short to decode the option.

Returns InvalidOptionValueLength if the decoded length does not match the expected length defined in OptionDef.

Multiple occurrences of non-repeatable options are treated as unrecognized options. Unrecognized options are silently ignored if they are elective.

func (Options) Encode

func (o Options) Encode(data []byte) []byte

Encode encodes options into the data slice.

If there are no options to encode, it returns the data slice unchanged.

func (Options) Get

func (o Options) Get(def OptionDef) (Option, bool)

Get retrieves the first option matching the definition.

func (Options) GetAll

func (o Options) GetAll(def OptionDef) iter.Seq[Option]

GetAll retrieves all options matching the definition.

func (Options) GetAllOpaque

func (o Options) GetAllOpaque(def OptionDef) (iter.Seq[[]byte], error)

GetAllOpaque retrieves all options matching the definition as a sequence of []byte values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

func (Options) GetAllString

func (o Options) GetAllString(def OptionDef) (iter.Seq[string], error)

GetAllString retrieves all options matching the definition as a sequence of string values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (Options) GetAllUint

func (o Options) GetAllUint(def OptionDef) (iter.Seq[uint32], error)

GetAllUint retrieves all options matching the definition as a sequence of uint32 values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.

func (Options) GetOpaque

func (o Options) GetOpaque(def OptionDef) ([]byte, error)

GetOpaque retrieves the value of the first option matching the definition as []byte.

Returns OptionNotFound if the option is not present.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

func (Options) GetString

func (o Options) GetString(def OptionDef) (string, error)

GetString retrieves the value of the first option matching the definition as string.

Returns OptionNotFound if the option is not present.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

func (Options) GetUint

func (o Options) GetUint(def OptionDef) (uint32, error)

GetUint retrieves the value of the first option matching the definition as uint32.

Returns OptionNotFound if the option is not present.

Returns InvalidOptionValueFormat if the option value format is not ValueFormatUint.

func (Options) GetValue

func (o Options) GetValue(def OptionDef) (any, bool)

GetValue retrieves the value of the first option matching the definition.

Prefer to use specific methods GetUint, GetOpaque or GetString to ensure type safety and avoid reflect overhead.

func (*Options) Set

func (o *Options) Set(opt Option)

Set creates or updates an option.

func (*Options) SetAllOpaque

func (o *Options) SetAllOpaque(def OptionDef, values iter.Seq[[]byte]) error

SetAllOpaque creates or updates all options matching the definition with the given sequence of []byte values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Options) SetAllString

func (o *Options) SetAllString(def OptionDef, values iter.Seq[string]) error

SetAllString creates or updates all options matching the definition with the given sequence of string values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

func (*Options) SetAllUint

func (o *Options) SetAllUint(def OptionDef, values iter.Seq[uint32]) error

SetAllUint creates or updates all options matching the definition with the given sequence of uint32 values.

Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Options) SetOpaque

func (o *Options) SetOpaque(def OptionDef, value []byte) error

SetOpaque creates or updates an option with the given value as []byte.

Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Options) SetString

func (o *Options) SetString(def OptionDef, value string) error

SetString creates or updates an option with the given value as string.

Returns InvalidOptionValueFormat if the value format is not ValueFormatString.

func (*Options) SetUint

func (o *Options) SetUint(def OptionDef, value uint32) error

SetUint creates or updates an option with the given value as uint32.

Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.

Returns InvalidOptionValueLength if the value length does not match the expected length.

func (*Options) SetValue

func (o *Options) SetValue(def OptionDef, value any) error

SetValue creates or updates an option with the given value.

Prefer to use specific methods SetUint, SetOpaque, SetString to ensure type safety and avoid reflect overhead.

type PayloadTooLong

type PayloadTooLong struct {
	Limit  uint
	Length uint
}

PayloadTooLong is returned when the payload length exceeds the maximum allowed length.

func (PayloadTooLong) Error

func (e PayloadTooLong) Error() string

type Reader

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

Reader reads messages from net.PacketConn using provided MarshalOptions.

func NewReader

func NewReader(conn net.PacketConn, opts MarshalOptions) *Reader

NewReader instantiates a new Reader that can read messages from the specified PacketConn.

func (*Reader) Read

func (r *Reader) Read(msg *Message) (addr net.Addr, err error)

Read reads a message from the PacketConn and decodes it into the provided Message.

type Request

type Request struct {
	// Type is the message type, either Confirmable or NonConfirmable.
	//
	// If not set, it defaults to Confirmable.
	Type Type

	// Method
	Method Method

	// MessageID
	MessageID MessageID

	// Token
	Token Token

	// Options
	Options Options

	// Host overrides URIHost option if not empty.
	Host string

	// Port overrides URIPort option if not zero.
	Port uint16

	// Path overrides URIPath options if not empty.
	Path string

	// Query overrides URIQuery options if not empty.
	Query []string

	// ContentFormat overrides ContentFormat option.
	ContentFormat *MediaType

	// Payload
	Payload []byte
}

Request represents a CoAP request message.

func (*Request) AppendBinary

func (r *Request) AppendBinary(data []byte) ([]byte, error)

AppendBinary implements encoding.BinaryAppender

Host, Port, Path, and Query are set in final message options.

func (*Request) Decode

func (r *Request) Decode(data []byte, opts MarshalOptions) ([]byte, error)

Decode decodes Request from the given data using the provided options.

Returns UnmarshalError if the message cannot be decoded.

Returns UnsupportedType error if the message type is not Confirmable or NonConfirmable.

Returns UnsupportedCode error if the message code is not a valid request method (0.xx).

func (*Request) MarshalBinary

func (r *Request) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*Request) String

func (r *Request) String() string

String implements fmt.Stringer.

func (*Request) UnmarshalBinary

func (r *Request) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

type Response

type Response struct {
	// Type, defaults to Confirmable.
	Type Type

	// Code
	Code ResponseCode

	// MessageID
	MessageID MessageID

	// Token
	Token Token

	// Options
	Options Options

	// ContentFormat overrides ContentFormat option if set.
	ContentFormat *MediaType

	// LocationPath overrides LocationPath option if not empty.
	LocationPath string

	// LocationQuery overrides LocationQuery options if not empty.
	LocationQuery []string

	// Payload
	Payload []byte
}

Response represents a CoAP response message.

func (*Response) AppendBinary

func (r *Response) AppendBinary(data []byte) ([]byte, error)

AppendBinary appends the binary representation of the Response to the provided data slice.

Returns InvalidType if type is out of range.

Returns InvalidCode if code is not a valid response code.

func (*Response) Decode

func (r *Response) Decode(data []byte, opts MarshalOptions) ([]byte, error)

Decode decodes the Response from the given data using the provided options.

Returns UnmarshalError if the message cannot be decoded.

Returns InvalidCode if the message code class is not in the range of 2.xx to 5.xx.

func (*Response) String

func (r *Response) String() string

type ResponseCode

type ResponseCode uint8

ResponseCode represents a CoAP response message code.

https://datatracker.ietf.org/doc/html/rfc7252#section-5.9

const (
	Created  ResponseCode = 0x41
	Deleted  ResponseCode = 0x42
	Valid    ResponseCode = 0x43
	Changed  ResponseCode = 0x44
	Content  ResponseCode = 0x45
	Continue ResponseCode = 0x46
)

Success 2.xx Response Codes

https://datatracker.ietf.org/doc/html/rfc7252#section-5.9.1

const (
	BadRequest               ResponseCode = 0x80
	Unauthorized             ResponseCode = 0x81
	BadOption                ResponseCode = 0x82
	Forbidden                ResponseCode = 0x83
	NotFound                 ResponseCode = 0x84
	MethodNotAllowed         ResponseCode = 0x85
	NotAcceptable            ResponseCode = 0x86
	Conflict                 ResponseCode = 0x89
	PreconditionFailed       ResponseCode = 0x8c
	RequestEntityTooLarge    ResponseCode = 0x8d
	UnsupportedContentFormat ResponseCode = 0x8f
	RequestEntityIncomplete  ResponseCode = 0x88
	UnprocessableEntity      ResponseCode = 0x96
	TooManyRequests          ResponseCode = 0x9d
)

Client Error 4.xx Response Codes

https://datatracker.ietf.org/doc/html/rfc7252#section-5.9.2

const (
	InternalServerError  ResponseCode = 0xa0
	NotImplemented       ResponseCode = 0xa1
	BadGateway           ResponseCode = 0xa2
	ServiceUnavailable   ResponseCode = 0xa3
	GatewayTimeout       ResponseCode = 0xa4
	ProxyingNotSupported ResponseCode = 0xa5
	HopLimitReached      ResponseCode = 0xa8
)

Server Error 5.xx Response Codes

https://datatracker.ietf.org/doc/html/rfc7252#section-5.9.3

func (ResponseCode) String

func (c ResponseCode) String() string

String implements fmt.Stringer.

type RetransmitErrorHandler

type RetransmitErrorHandler func(msg *Message, err error)
var NoopRetransmitErrorHandler RetransmitErrorHandler = func(_ *Message, _ error) {}

type RetransmitOptions

type RetransmitOptions struct {
	ACKTimeout      time.Duration
	ACKRandomFactor float64
	MaxRetransmit   uint
	MaxTransmitWait time.Duration
	MaxTransmitSpan time.Duration
	ErrorHandler    RetransmitErrorHandler
}

RetransmitOptions holds options for reliable message transmission.

type RetransmitQueue

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

RetransmitQueue manages retransmission of Confirmable messages until they are acknowledged or the maximum retransmission limit/time is reached.

func NewRetransmitQueue

func NewRetransmitQueue(opts RetransmitOptions) *RetransmitQueue

NewRetransmitQueue instantiate a new retransmit queue with the given writer and options.

If ErrorHandler is not set, it defaults to NoopRetransmitErrorHandler.

func (*RetransmitQueue) Add

func (q *RetransmitQueue) Add(op WriteOp)

Add adds op to the retransmit queue.

func (*RetransmitQueue) Close

func (q *RetransmitQueue) Close()

Close clears the retransmit queue and calls the error handler for each message with net.ErrClosed.

func (*RetransmitQueue) Next

func (q *RetransmitQueue) Next(now time.Time) time.Duration

Next returns the next retransmit time.

func (*RetransmitQueue) Process

func (q *RetransmitQueue) Process(now time.Time) []WriteOp

Process returns messages that need to be retransmitted and removes expired messages.

ErrorHandler is called when message retransmission exceeds limits.

https://datatracker.ietf.org/doc/html/rfc7252#section-4.8.2

func (*RetransmitQueue) Remove

func (q *RetransmitQueue) Remove(id MessageID) (WriteOp, bool)

Remove removes op from the retransmit queue by its message ID.

type RetransmitRetryLimit

type RetransmitRetryLimit struct {
	Retransmit    uint
	MaxRetransmit uint
}

func (RetransmitRetryLimit) Error

func (e RetransmitRetryLimit) Error() string

type RetransmitWaitLimit

type RetransmitWaitLimit struct {
	MaxTransmitWait time.Duration
}

func (RetransmitWaitLimit) Error

func (e RetransmitWaitLimit) Error() string

type Schema

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

Schema contains definitions of CoAP options and media types.

func NewSchema

func NewSchema() *Schema

NewSchema creates a new Schema instance with empty options and media types.

func (*Schema) AddMediaTypes

func (s *Schema) AddMediaTypes(mediaTypes ...MediaType) *Schema

AddMediaTypes adds media types.

func (*Schema) AddOptions

func (s *Schema) AddOptions(options ...OptionDef) *Schema

AddOptions adds options.

func (*Schema) MediaType

func (s *Schema) MediaType(code uint16) MediaType

MediaType retrieves a media type by code.

If the media type is not recognized, it returns an UnrecognizedMediaType with given code.

func (*Schema) Option

func (s *Schema) Option(code uint16, maxLen uint16) OptionDef

Option retrieves an option by code.

If the option is not recognized, it returns an UnrecognizedOptionDef with given code.

type Token

type Token []byte

Token represents the unique random token for matching requests and responses with maximum length of 8 bytes.

func (Token) Hash

func (t Token) Hash() uint64

Hash generates FNV-1a hash of the token.

type TokenSource

type TokenSource func() Token

TokenSource is a function that generates a random token of a specified length.

func RandTokenSource

func RandTokenSource(length uint) TokenSource

RandTokenSource returns a TokenSource that generates cryptographically random tokens of the length between 1-8 bytes.

If the length is 0, it defaults to 4 bytes. If the length is greater than 8, it defaults to 8 bytes.

type TooManyOptions

type TooManyOptions struct {
	Limit  uint
	Length uint
}

TooManyOptions is returned when the number of options exceeds the maximum allowed number.

func (TooManyOptions) Error

func (e TooManyOptions) Error() string

type TruncatedError

type TruncatedError struct {
	Expected uint
}

TruncatedError is returned when the input data does not contain enough bytes.

func (TruncatedError) Error

func (e TruncatedError) Error() string

type Type

type Type uint8

Type represents the message type in CoAP.

Requests can be Confirmable or NonConfirmable. Responses can be of any type.

const (
	// Confirmable is a message type that requires an acknowledgment.
	Confirmable Type = 0x00

	// NonConfirmable is a message type that does not require an acknowledgment.
	NonConfirmable Type = 0x01

	// Acknowledgement is a message type used to acknowledge a Confirmable message.
	Acknowledgement Type = 0x02

	// Reset is a message type used to indicate that a message could not be processed.
	Reset Type = 0x03
)

func (Type) String

func (t Type) String() string

String implements fmt.Stringer.

type UnmarshalError

type UnmarshalError struct {
	// Offset indicates where the error occurred in the input data.
	Offset uint

	// Cause is the underlying error that caused the unmarshaling to fail.
	Cause error
}

UnmarshalError is returned when an error occurs during unmarshaling a message.

func (UnmarshalError) Error

func (e UnmarshalError) Error() string

func (UnmarshalError) Unwrap

func (e UnmarshalError) Unwrap() error

type UnsupportedExtendError

type UnsupportedExtendError struct{}

UnsupportedExtendError is returned when an unsupported extend value 15 is encountered.

https://datatracker.ietf.org/doc/html/rfc7252#section-3.1

func (UnsupportedExtendError) Error

func (e UnsupportedExtendError) Error() string

type UnsupportedTokenLength

type UnsupportedTokenLength struct {
	Length uint
}

UnsupportedTokenLength is returned when the token length exceeds the maximum allowed length of 8 bytes.

https://datatracker.ietf.org/doc/html/rfc7252#section-3

func (UnsupportedTokenLength) Error

func (e UnsupportedTokenLength) Error() string

type UnsupportedVersion

type UnsupportedVersion struct {
	Version uint8
}

UnsupportedVersion is returned when the version does not match the expected protocol version 1.

https://datatracker.ietf.org/doc/html/rfc7252#section-3

func (UnsupportedVersion) Error

func (e UnsupportedVersion) Error() string

type ValueFormat

type ValueFormat uint8

ValueFormat indicates the format of the option value.

const (
	// ValueFormatEmpty indicates an option with no value.
	ValueFormatEmpty ValueFormat = 0x00

	// ValueFormatUint indicates an option with a value that is an unsigned integer.
	ValueFormatUint ValueFormat = 0x01

	// ValueFormatOpaque indicates an option with a value that is an opaque byte sequence.
	ValueFormatOpaque ValueFormat = 0x02

	// ValueFormatString indicates an option with a value that is a UTF-8 string.
	ValueFormatString ValueFormat = 0x03
)

func (ValueFormat) String

func (f ValueFormat) String() string

String implements fmt.Stringer for ValueFormat.

type WriteOp

type WriteOp struct {
	Message    *Message
	Addr       net.Addr
	Start      time.Time
	Retransmit uint
	Timeout    time.Duration
	Next       time.Time
}

WriteOp represents a write operation for a Confirmable message that needs retransmission.

type Writer

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

Writer writes messages to net.PacketConn using provided MarshalOptions.

func NewWriter

func NewWriter(conn net.PacketConn, opts MarshalOptions) *Writer

NewWriter instantiates a new Writer that can send messages over the specified PacketConn.

func (*Writer) Write

func (w *Writer) Write(msg *Message, addr net.Addr) error

Write sends a message to the specified address.

Jump to

Keyboard shortcuts

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