coap

package
v0.0.0-...-46646b9 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	ID        string
	Address   *net.UDPAddr
	CreatedAt time.Time
	LastSeen  time.Time
	MessageID uint16
}

Client represents a CoAP client

func (*Client) Close

func (c *Client) Close()

Close closes the client connection

type CoAPContentFormat

type CoAPContentFormat uint16

CoAPContentFormat represents CoAP content formats

const (
	ContentFormatTextPlain              CoAPContentFormat = 0
	ContentFormatApplicationLinkFormat  CoAPContentFormat = 40
	ContentFormatApplicationXML         CoAPContentFormat = 41
	ContentFormatApplicationOctetStream CoAPContentFormat = 42
	ContentFormatApplicationEXI         CoAPContentFormat = 47
	ContentFormatApplicationJSON        CoAPContentFormat = 50
	ContentFormatApplicationCBOR        CoAPContentFormat = 60
)

type Message

type Message struct {
	Type      MessageType
	Code      byte
	MessageID uint16
	Token     []byte
	Options   []Option
	Payload   []byte
}

Message represents a CoAP message

func ParseMessage

func ParseMessage(data []byte) (*Message, error)

ParseMessage parses a CoAP message from bytes

func (*Message) AddOption

func (m *Message) AddOption(number OptionNumber, value interface{})

AddOption adds an option to the message

func (*Message) Encode

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

Encode encodes a CoAP message to bytes

func (*Message) GetOption

func (m *Message) GetOption(number OptionNumber) []byte

GetOption gets an option value by number

func (*Message) GetPath

func (m *Message) GetPath() string

GetPath gets the URI path from options

func (*Message) HasOption

func (m *Message) HasOption(number OptionNumber) bool

HasOption checks if the message has an option

type MessageType

type MessageType byte

MessageType represents the CoAP message type

const (
	Confirmable     MessageType = 0
	NonConfirmable  MessageType = 1
	Acknowledgement MessageType = 2
	Reset           MessageType = 3
)

type MethodCode

type MethodCode byte

MethodCode represents the CoAP method code

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

type Observer

type Observer struct {
	Client    *Client
	Token     []byte
	Resource  *Resource
	CreatedAt time.Time
}

Observer represents a CoAP observer

type ObserverManager

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

ObserverManager manages CoAP observers

func NewObserverManager

func NewObserverManager(logger *slog.Logger) *ObserverManager

NewObserverManager creates a new observer manager

func (*ObserverManager) AddObserver

func (om *ObserverManager) AddObserver(path string, observer *Observer)

AddObserver adds an observer to a resource

func (*ObserverManager) CleanupObservers

func (om *ObserverManager) CleanupObservers(timeout time.Duration)

CleanupObservers removes expired observers

func (*ObserverManager) GetObserverCount

func (om *ObserverManager) GetObserverCount(path string) int

GetObserverCount returns the number of observers for a resource

func (*ObserverManager) GetObservers

func (om *ObserverManager) GetObservers(path string) []*Observer

GetObservers returns all observers for a resource

func (*ObserverManager) GetTotalObserverCount

func (om *ObserverManager) GetTotalObserverCount() int

GetTotalObserverCount returns the total number of observers

func (*ObserverManager) RemoveObserver

func (om *ObserverManager) RemoveObserver(path string, clientID string)

RemoveObserver removes an observer from a resource

type Option

type Option struct {
	Number OptionNumber
	Value  []byte
}

Option represents a CoAP option

type OptionNumber

type OptionNumber uint16

OptionNumber represents CoAP option numbers

const (
	IfMatch       OptionNumber = 1
	UriHost       OptionNumber = 3
	ETag          OptionNumber = 4
	IfNoneMatch   OptionNumber = 5
	UriPort       OptionNumber = 7
	LocationPath  OptionNumber = 8
	UriPath       OptionNumber = 11
	ContentFormat OptionNumber = 12
	MaxAge        OptionNumber = 14
	UriQuery      OptionNumber = 15
	Accept        OptionNumber = 17
	LocationQuery OptionNumber = 20
	ProxyUri      OptionNumber = 35
	ProxyScheme   OptionNumber = 39
	Size1         OptionNumber = 60
	Observe       OptionNumber = 6
	Block1        OptionNumber = 27
	Block2        OptionNumber = 23
)

type RequestHandler

type RequestHandler func(*Message, *Client) (*Message, error)

RequestHandler is a function that handles CoAP requests

type Resource

type Resource struct {
	// Resource metadata
	Name          string
	Description   string
	Content       []byte
	ContentFormat *CoAPContentFormat

	// Request handlers
	GetHandler    RequestHandler
	PostHandler   RequestHandler
	PutHandler    RequestHandler
	DeleteHandler RequestHandler

	// Resource state
	Observable   bool
	MaxAge       int
	ETag         []byte
	LastModified time.Time
	// contains filtered or unexported fields
}

Resource represents a CoAP resource

func NewObservableResource

func NewObservableResource(name, description string, content []byte) *Resource

NewObservableResource creates a new observable CoAP resource

func NewResource

func NewResource(name, description string, content []byte) *Resource

NewResource creates a new CoAP resource

func (*Resource) GetContent

func (r *Resource) GetContent() []byte

GetContent gets the current content of the resource

func (*Resource) GetETag

func (r *Resource) GetETag() []byte

GetETag returns the ETag of the resource

func (*Resource) GetLastModified

func (r *Resource) GetLastModified() time.Time

GetLastModified returns the last modified time of the resource

func (*Resource) GetMaxAge

func (r *Resource) GetMaxAge() int

GetMaxAge returns the max age of the resource

func (*Resource) IsObservable

func (r *Resource) IsObservable() bool

IsObservable returns true if the resource is observable

func (*Resource) SetContent

func (r *Resource) SetContent(content []byte)

SetContent sets the content of the resource

func (*Resource) SetContentFormat

func (r *Resource) SetContentFormat(format CoAPContentFormat)

SetContentFormat sets the content format of the resource

func (*Resource) SetDeleteHandler

func (r *Resource) SetDeleteHandler(handler RequestHandler)

SetDeleteHandler sets the DELETE request handler

func (*Resource) SetGetHandler

func (r *Resource) SetGetHandler(handler RequestHandler)

SetGetHandler sets the GET request handler

func (*Resource) SetMaxAge

func (r *Resource) SetMaxAge(maxAge int)

SetMaxAge sets the max age of the resource

func (*Resource) SetObservable

func (r *Resource) SetObservable(observable bool)

SetObservable sets whether the resource is observable

func (*Resource) SetPostHandler

func (r *Resource) SetPostHandler(handler RequestHandler)

SetPostHandler sets the POST request handler

func (*Resource) SetPutHandler

func (r *Resource) SetPutHandler(handler RequestHandler)

SetPutHandler sets the PUT request handler

func (*Resource) UpdateContent

func (r *Resource) UpdateContent(content []byte, notifyObservers func([]byte))

UpdateContent updates the content and notifies observers

type ResourceManager

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

ResourceManager manages CoAP resources

func NewResourceManager

func NewResourceManager(logger *slog.Logger) *ResourceManager

NewResourceManager creates a new resource manager

func (*ResourceManager) GetResource

func (rm *ResourceManager) GetResource(path string) (*Resource, bool)

GetResource gets a resource by path

func (*ResourceManager) GetResourceCount

func (rm *ResourceManager) GetResourceCount() int

GetResourceCount returns the number of registered resources

func (*ResourceManager) ListResources

func (rm *ResourceManager) ListResources() map[string]*Resource

ListResources returns all registered resources

func (*ResourceManager) RegisterResource

func (rm *ResourceManager) RegisterResource(path string, resource *Resource)

RegisterResource registers a resource

func (*ResourceManager) UnregisterResource

func (rm *ResourceManager) UnregisterResource(path string)

UnregisterResource unregisters a resource

type ResponseCode

type ResponseCode byte

ResponseCode represents the CoAP response code

const (
	// Success responses
	Created ResponseCode = 65 // 2.01
	Deleted ResponseCode = 66 // 2.02
	Valid   ResponseCode = 67 // 2.03
	Changed ResponseCode = 68 // 2.04
	Content ResponseCode = 69 // 2.05

	// Client error responses
	BadRequest               ResponseCode = 128 // 4.00
	Unauthorized             ResponseCode = 129 // 4.01
	BadOption                ResponseCode = 130 // 4.02
	Forbidden                ResponseCode = 131 // 4.03
	NotFound                 ResponseCode = 132 // 4.04
	MethodNotAllowed         ResponseCode = 133 // 4.05
	NotAcceptable            ResponseCode = 134 // 4.06
	PreconditionFailed       ResponseCode = 140 // 4.12
	RequestEntityTooLarge    ResponseCode = 141 // 4.13
	UnsupportedContentFormat ResponseCode = 143 // 4.15

	// Server error responses
	InternalServerError  ResponseCode = 160 // 5.00
	NotImplemented       ResponseCode = 161 // 5.01
	BadGateway           ResponseCode = 162 // 5.02
	ServiceUnavailable   ResponseCode = 163 // 5.03
	GatewayTimeout       ResponseCode = 164 // 5.04
	ProxyingNotSupported ResponseCode = 165 // 5.05
)

type Server

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

Server represents the CoAP server

func NewServer

func NewServer(fileserver *fileserver.Server, config *ServerConfig, logger *slog.Logger) *Server

NewServer creates a new CoAP server

func (*Server) GetStats

func (s *Server) GetStats() *ServerStats

GetStats returns server statistics

func (*Server) ServeDTLS

func (s *Server) ServeDTLS(ctx context.Context, addr string) error

ServeDTLS starts the DTLS CoAP server

func (*Server) ServeUDP

func (s *Server) ServeUDP(ctx context.Context, conn *net.UDPConn) error

ServeUDP starts the UDP CoAP server

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown gracefully shuts down the server

type ServerConfig

type ServerConfig struct {
	Port           int
	Host           string
	EnableDTLS     bool
	DTLSPort       int
	MaxConnections int
	MaxMessageSize int
	BlockSize      int
	MaxAge         int
	EnableObserve  bool
	ObserveTimeout time.Duration
}

ServerConfig holds the configuration for the CoAP server

type ServerStats

type ServerStats struct {
	StartTime         time.Time
	TotalConnections  int
	ActiveConnections int
	TotalRequests     int
	TotalResponses    int
	TotalResources    int
	TotalObservers    int
	BytesReceived     int64
	BytesSent         int64
}

ServerStats holds server statistics

Jump to

Keyboard shortcuts

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