Documentation
¶
Index ¶
- Constants
- Variables
- func Decode32(data []byte) uint32
- func DecodeExtend(data []byte, v uint8) (uint16, []byte, error)
- func DecodePath(segments iter.Seq[string]) string
- func Encode32(v uint32, data []byte) []byte
- func EncodeExtend(data []byte, v uint16) (uint8, []byte)
- func EncodePath(path string) iter.Seq[string]
- func Index(options []Option, def OptionDef) int
- func Len32(v uint32) uint16
- func Must(err error)
- func MustValue[T any](value T, err error) T
- type Code
- type Conn
- type ConnOptions
- type Header
- type InvalidCode
- type InvalidOptionValueFormat
- type InvalidOptionValueLength
- type InvalidType
- type MarshalOptions
- type MediaType
- type Message
- type MessageID
- type MessageIDSource
- type MessageTooLong
- type Method
- type Option
- func (o *Option) Decode(data []byte, prev uint16, opts MarshalOptions) ([]byte, error)
- func (o Option) Encode(data []byte, prev uint16) []byte
- func (o Option) GetOpaque() ([]byte, error)
- func (o Option) GetString() (string, error)
- func (o Option) GetUint() (uint32, error)
- func (o Option) GetValue() any
- func (o Option) Length() uint16
- func (o *Option) SetOpaque(value []byte) error
- func (o *Option) SetString(value string) error
- func (o *Option) SetUint(value uint32) error
- func (o *Option) SetValue(value any) error
- func (o Option) String() string
- type OptionDef
- type OptionNotFound
- type OptionNotRepeateable
- type Options
- func (o *Options) Clear(def OptionDef) int
- func (o Options) Contains(def OptionDef) bool
- func (o *Options) Decode(data []byte, opts MarshalOptions) ([]byte, error)
- func (o Options) Encode(data []byte) []byte
- func (o Options) Get(def OptionDef) (Option, bool)
- func (o Options) GetAll(def OptionDef) iter.Seq[Option]
- func (o Options) GetAllOpaque(def OptionDef) (iter.Seq[[]byte], error)
- func (o Options) GetAllString(def OptionDef) (iter.Seq[string], error)
- func (o Options) GetAllUint(def OptionDef) (iter.Seq[uint32], error)
- func (o Options) GetOpaque(def OptionDef) ([]byte, error)
- func (o Options) GetString(def OptionDef) (string, error)
- func (o Options) GetUint(def OptionDef) (uint32, error)
- func (o Options) GetValue(def OptionDef) (any, bool)
- func (o *Options) Set(opt Option)
- func (o *Options) SetAllOpaque(def OptionDef, values iter.Seq[[]byte]) error
- func (o *Options) SetAllString(def OptionDef, values iter.Seq[string]) error
- func (o *Options) SetAllUint(def OptionDef, values iter.Seq[uint32]) error
- func (o *Options) SetOpaque(def OptionDef, value []byte) error
- func (o *Options) SetString(def OptionDef, value string) error
- func (o *Options) SetUint(def OptionDef, value uint32) error
- func (o *Options) SetValue(def OptionDef, value any) error
- type PayloadTooLong
- type Reader
- type Request
- type Response
- type ResponseCode
- type RetransmitErrorHandler
- type RetransmitOptions
- type RetransmitQueue
- type RetransmitRetryLimit
- type RetransmitWaitLimit
- type Schema
- type Token
- type TokenSource
- type TooManyOptions
- type TruncatedError
- type Type
- type UnmarshalError
- type UnsupportedExtendError
- type UnsupportedTokenLength
- type UnsupportedVersion
- type ValueFormat
- type WriteOp
- type Writer
Constants ¶
const ( ACKTimeout = 2 * time.Second ACKRandomFactor = 1.5 MaxRetransmit = 4 )
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 )
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 )
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 ¶
var ( MediaTypeImageGIF = MediaType{Code: 21, Name: `image/gif`} MediaTypeImagePNG = MediaType{Code: 22, Name: `image/png`} MediaTypeImageJPEG = MediaType{Code: 23, Name: `image/jpeg`} )
Image assets
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
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`} )
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} )
var DefaultSchema = NewSchema(). AddOptions( IfMatch, URIHost, URIPort, URIPath, URIQuery, ETag, IfNoneMatch, Observe, LocationPath, LocationQuery, ContentFormat, MaxAge, Accept, Block1, Block2, ProxyURI, ProxyScheme, Size1, Size2, NoResponse, ). AddMediaTypes( MediaTypeTextPlain, MediaTypeImageGIF, MediaTypeImagePNG, MediaTypeImageJPEG, MediaTypeApplicationCOSEEncrypt0, MediaTypeApplicationCOSEMac0, MediaTypeApplicationCBORSign1, MediaTypeApplicationLinkFormat, MediaTypeApplicationXML, MediaTypeApplicationOctetStream, MediaTypeApplicationExi, MediaTypeApplicationJSON, MediaTypeApplicationCBOR, MediaTypeApplicationCBORSeq, )
DefaultSchema defines well-known CoAP options and media types.
https://www.iana.org/assignments/core-parameters/core-parameters.xhtml#content-formats
Functions ¶
func Decode32 ¶
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 ¶
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 ¶
DecodePath decodes a sequence of path segments into a single path string.
func Encode32 ¶
Encode32 encodes a uint32 value in big-endian format using the minimum number of bytes
func EncodeExtend ¶
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 ¶
EncodePath encodes a path string into a sequence of path segments.
func Index ¶
Index returns index of first option with matching code in the options slice returning -1 if not found.
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 ¶
Class indicates the class of the request method or response code represented by the first 3 bits of the code value.
func (Code) Detail ¶
Detail indicates the detail of the request method or response code represented by the last 5 bits of the code value.
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.
type ConnOptions ¶
type ConnOptions struct {
RetransmitOptions
MarshalOptions
}
ConnOptions holds options for creating a new CoAP connection.
type Header ¶
Header represents the CoAP message header.
func (Header) AppendBinary ¶
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.
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 ¶
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 ¶
MediaType indicates payload media type.
func UnrecognizedMediaType ¶
UnrecognizedMediaType creates a MediaType instance for unrecognized media types.
func (MediaType) Recognized ¶
Recognized indicates whether the media type is recognized by its name.
type Message ¶
Message represents a CoAP message, which includes a header, options, and an optional payload.
func (*Message) AppendBinary ¶
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 ¶
MarshalBinary implements encoding.BinaryMarshaler
func (*Message) UnmarshalBinary ¶
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 ¶
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.
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 ¶
MustOptionValue creates an Option from the provided definition and value, panicking if an error occurs.
func OptionValue ¶
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 ¶
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) GetOpaque ¶
GetOpaque returns the opaque byte slice value of the option.
Returns InvalidOptionValueFormat if the value format is not ValueFormatOpaque.
func (Option) GetString ¶
GetString returns the string value of the option.
Returns InvalidOptionValueFormat if the value format is not ValueFormatString.
func (Option) GetUint ¶
GetUint returns the uint32 value of the option.
Returns InvalidOptionValueFormat if the value format is not ValueFormatUint.
func (Option) GetValue ¶
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) SetOpaque ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
UnrecognizedOptionDef creates an OptionDef for an unrecognized option code.
func (OptionDef) NoCacheKey ¶
NoCacheKey returns true if option should not be used as cache key.
func (OptionDef) Recognized ¶
Recognized indicates whether the option is recognized by schema.
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 ¶
SortOptions sorts the options by their code in ascending order.
Returns a new slice of options sorted by code.
func (*Options) Clear ¶
Clear removes all occurrences of the option with matching code.
Returns number of options removed.
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 ¶
Encode encodes options into the data slice.
If there are no options to encode, it returns the data slice unchanged.
func (Options) GetAllOpaque ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) SetAllOpaque ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetString creates or updates an option with the given value as string.
Returns InvalidOptionValueFormat if the value format is not ValueFormatString.
type PayloadTooLong ¶
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.
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 ¶
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 ¶
MarshalBinary implements encoding.BinaryMarshaler
func (*Request) UnmarshalBinary ¶
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 ¶
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.
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
const ( BadRequest ResponseCode = 0x80 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
const ( InternalServerError ResponseCode = 0xa0 NotImplemented ResponseCode = 0xa1 BadGateway ResponseCode = 0xa2 GatewayTimeout ResponseCode = 0xa4 ProxyingNotSupported ResponseCode = 0xa5 HopLimitReached ResponseCode = 0xa8 )
Server Error 5.xx Response Codes
type RetransmitErrorHandler ¶
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.
type RetransmitRetryLimit ¶
func (RetransmitRetryLimit) Error ¶
func (e RetransmitRetryLimit) Error() string
type RetransmitWaitLimit ¶
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 ¶
AddMediaTypes adds media types.
func (*Schema) AddOptions ¶
AddOptions adds options.
type Token ¶
type Token []byte
Token represents the unique random token for matching requests and responses with maximum length of 8 bytes.
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 ¶
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 )
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.