transport

package
v0.0.0-...-02ded7e Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 10 Imported by: 0

README

transport

Package transport implements the network transport layer for Matter.

It abstracts the underlying network protocols (UDP, TCP) and provides a unified interface for sending and receiving Matter messages.

Supported Transports

  • UDP (Default/Mandatory): Connectionless, used for discovery, group casting, and most operational messaging.
  • TCP (Optional): Connection-oriented, used for large data transfers (e.g., OTA).

Architecture

The Manager owns the sockets and dispatches incoming messages to a registered handler.

      Application / Exchange Manager
                   ▲
                   │ OnMessageReceived ()
                   │
           ┌───────┴───────┐
           │    Manager    │
           └───────┬───────┘
                   │
       ┌───────────┴───────────┐
       ▼                       ▼
    ┌─────┐                 ┌─────┐
    │ UDP │                 │ TCP │
    └─────┘                 └─────┘

Usage

Initialize and Start
import "github.com/backkem/matter/pkg/transport"

// Define the handler for incoming messages
handler := func(msg *transport.ReceivedMessage) {
    fmt.Printf("Received %d bytes from %s\n", len(msg.Data), msg.PeerAddr)
}

// Create manager (binds to port 5540 by default)
mgr, err := transport.NewManager(transport.ManagerConfig{
    MessageHandler: handler,
})

// Start listening
mgr.Start()
Send a Message

The Send method automatically selects UDP or TCP based on the PeerAddress.

// Send via UDP
addr := transport.NewUDPPeerAddress(remoteNetAddr)
err := mgr.Send(data, addr)

Virtual Pipe for Testing

In-memory transport for deterministic, flaky-free tests without real network I/O. Supports both UDP and TCP transports.

    Device                              Controller
    ──────                              ──────────
       │                                    │
       ▼                                    ▼
  PipeFactory ◄─────── Pipe ──────► PipeFactory
       │           (auto-process)           │
       ├───────────────────────────────────►├
       ▼                                    ▼
  PipePacketConn ◄── Queue 0→1 ──► PipePacketConn  (UDP)
                 ◄── Queue 1→0 ──►
       │                                    │
       ▼                                    ▼
  PipeTCPListener ◄── Stream ────► PipeTCPConn     (TCP)
Basic Usage (UDP)
// Create paired factories - messages flow automatically
deviceFactory, controllerFactory := transport.NewPipeFactoryPair()
defer deviceFactory.Pipe().Close()

// Use in NodeConfig
config := matter.NodeConfig{
    TransportFactory: deviceFactory,
}
TCP Usage
f0, f1 := transport.NewPipeFactoryPair()
defer f0.Pipe().Close()

// Server side: create listener
listener, _ := f0.CreateTCPListener(5540)
defer listener.Close()

// Client side: get connection
clientConn := f1.GetTCPClientConn(5540)

// Server accepts the connection
serverConn, _ := listener.Accept()
defer serverConn.Close()

// Now clientConn and serverConn are connected via the pipe
clientConn.Write([]byte("hello"))
buf := make([]byte, 100)
n, _ := serverConn.Read(buf)
// buf[:n] == "hello"
Network Simulation
deviceFactory.SetCondition(transport.NetworkCondition{
    DropRate:      0.1,                   // 10% packet loss
    DelayMin:      10 * time.Millisecond,
    DelayMax:      50 * time.Millisecond,
    DuplicateRate: 0.05,                  // 5% duplicates
})
Manual Processing (Deterministic Tests)
f0, f1 := transport.NewPipeFactoryPairWithConfig(transport.PipeConfig{
    AutoProcess: false,
})

conn0.WriteTo(data, addr)
f0.Pipe().Process() // manually deliver

For most testing scenarios, use NewPipeManagerPair() instead of manually wiring pipes. It creates two fully connected Manager instances with minimal boilerplate.

pair, _ := transport.NewPipeManagerPair(transport.PipeManagerConfig{
    UDP: true,
    TCP: true,
    Handlers: [2]transport.MessageHandler{handler0, handler1},
})
defer pair.Close()

// Send from manager 0 to manager 1
pair.Manager(0).Send(data, pair.PeerAddresses(1).UDP)

// Send from manager 1 to manager 0 over TCP
pair.Manager(1).Send(data, pair.PeerAddresses(0).TCP)
Protocol Isolation

When testing specific protocols, disable the other to ensure test correctness:

// UDP-only testing - TCP addresses will be invalid
pair, _ := transport.NewPipeManagerPair(transport.PipeManagerConfig{
    UDP:      true,
    TCP:      false,
    Handlers: [2]transport.MessageHandler{h0, h1},
})

peer := pair.PeerAddresses(1)
peer.UDP.IsValid() // true
peer.TCP.IsValid() // false - prevents accidental TCP usage
Network Simulation with Manager Pairs
pair, _ := transport.NewPipeManagerPair(transport.PipeManagerConfig{
    UDP:      true,
    Handlers: [2]transport.MessageHandler{h0, h1},
})

// Simulate 10% packet loss on UDP
pair.Pipe().SetCondition(transport.NetworkCondition{
    DropRate: 0.1,
})

Factory Interface

type Factory interface {
    CreateUDPConn(port int) (net.PacketConn, error)
    CreateTCPListener(port int) (net.Listener, error)
}

When NodeConfig.TransportFactory is nil, real OS sockets are used.

Documentation

Index

Constants

View Source
const DefaultPort = 5540

DefaultPort is the default Matter port (Spec Section 2.5.6.3).

Variables

View Source
var (
	// ErrClosed is returned when an operation is attempted on a closed transport.
	ErrClosed = errors.New("transport: closed")

	// ErrInvalidAddress is returned when an invalid peer address is provided.
	ErrInvalidAddress = errors.New("transport: invalid address")

	// ErrNoHandler is returned when no message handler is configured.
	ErrNoHandler = errors.New("transport: no message handler configured")

	// ErrNotStarted is returned when an operation requires a started transport.
	ErrNotStarted = errors.New("transport: not started")

	// ErrAlreadyStarted is returned when Start is called on an already running transport.
	ErrAlreadyStarted = errors.New("transport: already started")

	// ErrConnectionNotFound is returned when no connection exists for a peer address.
	ErrConnectionNotFound = errors.New("transport: connection not found for peer")

	// ErrSendFailed is returned when sending a message fails.
	ErrSendFailed = errors.New("transport: send failed")

	// ErrMessageTooLarge is returned when a message exceeds the maximum size.
	ErrMessageTooLarge = errors.New("transport: message too large")
)

Transport errors.

Functions

func NewPipeFactoryPair

func NewPipeFactoryPair() (*PipeFactory, *PipeFactory)

NewPipeFactoryPair creates a pair of PipeFactory instances connected to each other via a Pipe with auto-processing enabled.

Example:

f0, f1 := transport.NewPipeFactoryPair()
// Use f0 for device, f1 for controller
// Messages flow automatically - no manual pumping needed!

func NewPipeFactoryPairWithConfig

func NewPipeFactoryPairWithConfig(config PipeConfig) (*PipeFactory, *PipeFactory)

NewPipeFactoryPairWithConfig creates a pair of PipeFactory instances with the given configuration.

For manual message control (deterministic testing):

f0, f1 := transport.NewPipeFactoryPairWithConfig(transport.PipeConfig{
    AutoProcess: false,
})
// ... do work ...
f0.Pipe().Process() // manually deliver messages

Types

type Factory

type Factory interface {
	// CreateUDPConn creates a UDP-like packet connection.
	// The port parameter is used for address assignment.
	CreateUDPConn(port int) (net.PacketConn, error)

	// CreateTCPListener creates a TCP-like listener.
	// The port parameter is used for address assignment.
	// Returns nil if TCP is not supported.
	CreateTCPListener(port int) (net.Listener, error)
}

Factory creates transport connections. Implementations can provide real network connections or virtual pipes for testing.

type Manager

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

Manager coordinates UDP and TCP transports for Matter messaging. It provides a unified interface for sending and receiving messages over both transport types.

func NewManager

func NewManager(config ManagerConfig) (*Manager, error)

NewManager creates a new transport manager with the given configuration.

func (*Manager) LocalAddresses

func (m *Manager) LocalAddresses() []net.Addr

LocalAddresses returns all local addresses the manager is listening on.

func (*Manager) Send

func (m *Manager) Send(data []byte, peer PeerAddress) error

Send sends a message to the specified peer address. The transport type is determined by the PeerAddress.TransportType field.

func (*Manager) Start

func (m *Manager) Start() error

Start begins listening for messages on all enabled transports.

func (*Manager) Stop

func (m *Manager) Stop() error

Stop closes all transports.

func (*Manager) TCP

func (m *Manager) TCP() *TCP

TCP returns the TCP transport, or nil if not enabled.

func (*Manager) UDP

func (m *Manager) UDP() *UDP

UDP returns the UDP transport, or nil if not enabled.

type ManagerConfig

type ManagerConfig struct {
	// Port is the port to listen on (default: 5540).
	Port int

	// UDPEnabled controls whether UDP transport is enabled (default: true).
	UDPEnabled bool

	// TCPEnabled controls whether TCP transport is enabled (default: true).
	TCPEnabled bool

	// MessageHandler is called for each received message.
	// Required.
	MessageHandler MessageHandler

	// UDPConn is an optional pre-existing UDP connection for testing.
	UDPConn net.PacketConn

	// TCPListener is an optional pre-existing TCP listener for testing.
	TCPListener net.Listener

	// LoggerFactory is the factory for creating loggers.
	// If nil, logging is disabled.
	LoggerFactory logging.LoggerFactory
}

ManagerConfig configures the transport manager.

type MessageHandler

type MessageHandler func(msg *ReceivedMessage)

MessageHandler is called for each received message. Implementations should process messages quickly or dispatch to a goroutine to avoid blocking the transport's read loop.

type NetworkCondition

type NetworkCondition struct {
	// DropRate is the probability of dropping a packet (0.0 - 1.0).
	DropRate float64

	// DelayMin is the minimum delay to add to each packet.
	DelayMin time.Duration

	// DelayMax is the maximum delay to add to each packet.
	// Actual delay is uniformly distributed between DelayMin and DelayMax.
	DelayMax time.Duration

	// DuplicateRate is the probability of duplicating a packet (0.0 - 1.0).
	DuplicateRate float64

	// ReorderRate is the probability of reordering packets (0.0 - 1.0).
	// When triggered, the packet is delayed by an additional ReorderDelay.
	ReorderRate float64

	// ReorderDelay is the additional delay for reordered packets.
	ReorderDelay time.Duration
}

NetworkCondition configures network behavior simulation. Use this to test protocol behavior under adverse network conditions.

type PeerAddress

type PeerAddress struct {
	// Addr is the network address of the peer.
	Addr net.Addr
	// TransportType identifies the transport protocol (UDP or TCP).
	TransportType TransportType
}

PeerAddress identifies a remote peer by network address and transport type.

func NewTCPPeerAddress

func NewTCPPeerAddress(addr net.Addr) PeerAddress

NewTCPPeerAddress creates a PeerAddress for a TCP peer.

func NewUDPPeerAddress

func NewUDPPeerAddress(addr net.Addr) PeerAddress

NewUDPPeerAddress creates a PeerAddress for a UDP peer.

func TCPAddrFromString

func TCPAddrFromString(addr string) (PeerAddress, error)

TCPAddrFromString parses an address string and creates a TCP PeerAddress.

func UDPAddrFromString

func UDPAddrFromString(addr string) (PeerAddress, error)

UDPAddrFromString parses an address string and creates a UDP PeerAddress.

func (PeerAddress) IsValid

func (p PeerAddress) IsValid() bool

IsValid returns true if the peer address has a valid transport type and address.

func (PeerAddress) String

func (p PeerAddress) String() string

String returns a human-readable representation of the peer address.

type Pipe

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

Pipe provides bidirectional in-memory packet communication between two endpoints. It wraps pion's test.Bridge and adds network condition simulation.

By default, Pipe automatically delivers messages in a background goroutine. Use SetAutoProcess(false) or NewPipeWithConfig for manual control.

This follows the "Virtual Network" testing pattern from docs/style.md. Use Pipe for deterministic, flaky-free tests without real network I/O.

func NewPipe

func NewPipe() *Pipe

NewPipe creates a new bidirectional pipe with auto-processing enabled. Messages are automatically delivered in a background goroutine.

func NewPipeWithConfig

func NewPipeWithConfig(config PipeConfig) *Pipe

NewPipeWithConfig creates a new pipe with the given configuration.

func (*Pipe) AutoProcess

func (p *Pipe) AutoProcess() bool

AutoProcess returns whether auto-processing is enabled.

func (*Pipe) Close

func (p *Pipe) Close() error

Close closes both endpoints of the pipe and stops auto-processing.

func (*Pipe) Condition

func (p *Pipe) Condition() NetworkCondition

Condition returns the current network condition configuration.

func (*Pipe) Conn0

func (p *Pipe) Conn0() net.Conn

Conn0 returns the connection for endpoint 0.

func (*Pipe) Conn1

func (p *Pipe) Conn1() net.Conn

Conn1 returns the connection for endpoint 1.

func (*Pipe) Process

func (p *Pipe) Process() int

Process delivers all queued packets. Returns the number of packets delivered.

Note: When AutoProcess is enabled (default), you typically don't need to call this manually. Use SetAutoProcess(false) for manual control.

func (*Pipe) SetAutoProcess

func (p *Pipe) SetAutoProcess(enabled bool)

SetAutoProcess enables or disables automatic message delivery. When disabled, you must call Tick() or Process() manually. This is useful for deterministic testing of specific packet orderings.

func (*Pipe) SetCondition

func (p *Pipe) SetCondition(cond NetworkCondition)

SetCondition configures network condition simulation. The conditions apply to packets in both directions.

func (*Pipe) Tick

func (p *Pipe) Tick() int

Tick delivers one packet in each direction (if available). Returns the number of packets delivered (0, 1, or 2).

Note: When AutoProcess is enabled (default), you typically don't need to call this manually. Use SetAutoProcess(false) for manual control.

type PipeAddr

type PipeAddr struct {
	ID   int // Endpoint ID (0 or 1)
	Port int // Logical port number
}

PipeAddr implements net.Addr for pipe endpoints.

func (PipeAddr) Network

func (a PipeAddr) Network() string

Network returns "pipe".

func (PipeAddr) String

func (a PipeAddr) String() string

String returns a string representation of the address.

type PipeAddresses

type PipeAddresses struct {
	// UDP is the UDP peer address, or invalid if UDP is not enabled.
	UDP PeerAddress

	// TCP is the TCP peer address, or invalid if TCP is not enabled.
	TCP PeerAddress
}

PipeAddresses contains the addresses needed to reach a manager over the pipe.

type PipeConfig

type PipeConfig struct {
	// AutoProcess enables automatic message delivery in a background goroutine.
	// Default: true
	AutoProcess bool

	// ProcessInterval is how often the auto-processor checks for messages.
	// Default: 1ms
	ProcessInterval time.Duration
}

PipeConfig configures a Pipe.

func DefaultPipeConfig

func DefaultPipeConfig() PipeConfig

DefaultPipeConfig returns the default pipe configuration.

type PipeFactory

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

PipeFactory creates transports that use a Pipe for communication. Use this for in-memory testing without real network I/O.

By default, messages are automatically delivered in a background goroutine. Use Pipe().SetAutoProcess(false) for manual control over message delivery.

func (*PipeFactory) CreateTCPListener

func (f *PipeFactory) CreateTCPListener(port int) (net.Listener, error)

CreateTCPListener creates a TCP listener using a pipe. The listener will accept exactly one connection (the pipe's endpoint). This is suitable for point-to-point testing scenarios.

func (*PipeFactory) CreateUDPConn

func (f *PipeFactory) CreateUDPConn(port int) (net.PacketConn, error)

CreateUDPConn creates a UDP-like connection using the pipe.

func (*PipeFactory) GetTCPClientConn

func (f *PipeFactory) GetTCPClientConn(port int) net.Conn

GetTCPClientConn returns a TCP client connection for connecting to the peer's listener. This is the counterpart to CreateTCPListener - use it on the "client" side of the pipe.

Example:

f0, f1 := NewPipeFactoryPair()
listener, _ := f0.CreateTCPListener(5540)  // Server side
clientConn := f1.GetTCPClientConn(5540)    // Client side
serverConn, _ := listener.Accept()
// Now clientConn and serverConn are connected via the pipe

func (*PipeFactory) LocalAddr

func (f *PipeFactory) LocalAddr() net.Addr

LocalAddr returns the local address for this side of the pipe.

func (*PipeFactory) PeerAddr

func (f *PipeFactory) PeerAddr() net.Addr

PeerAddr returns the peer address for this side of the pipe.

func (*PipeFactory) Pipe

func (f *PipeFactory) Pipe() *Pipe

Pipe returns the underlying pipe for configuration and manual message control.

To disable auto-processing for deterministic tests:

f.Pipe().SetAutoProcess(false)

To configure network conditions:

f.Pipe().SetCondition(transport.NetworkCondition{
    DropRate: 0.1, // 10% packet loss
})

func (*PipeFactory) SetCondition

func (f *PipeFactory) SetCondition(cond NetworkCondition)

SetCondition configures network condition simulation for this factory's pipe.

type PipeManagerConfig

type PipeManagerConfig struct {
	// UDP enables UDP transport (default: true if both UDP and TCP are false).
	UDP bool

	// TCP enables TCP transport (default: true if both UDP and TCP are false).
	TCP bool

	// Handlers are the message handlers for each manager.
	// Handlers[0] is for Manager(0), Handlers[1] is for Manager(1).
	Handlers [2]MessageHandler

	// PipeConfig configures the underlying pipe (optional).
	PipeConfig PipeConfig
}

PipeManagerConfig configures a PipeManagerPair.

type PipeManagerPair

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

PipeManagerPair provides two connected Manager instances for testing. Messages sent from one manager arrive at the other via in-memory pipes.

Example:

pair := transport.NewPipeManagerPair(transport.PipeManagerConfig{
    UDP: true,
    TCP: true,
    Handlers: [2]transport.MessageHandler{handler0, handler1},
})
defer pair.Close()

// Send from manager 0 to manager 1
pair.Manager(0).Send(data, pair.PeerAddresses(1).UDP)

// Send from manager 1 to manager 0 over TCP
pair.Manager(1).Send(data, pair.PeerAddresses(0).TCP)

func NewPipeManagerPair

func NewPipeManagerPair(config PipeManagerConfig) (*PipeManagerPair, error)

NewPipeManagerPair creates a pair of connected Manager instances for testing. Both managers are started automatically and ready to use.

func (*PipeManagerPair) Close

func (p *PipeManagerPair) Close() error

Close stops both managers and closes all pipes.

func (*PipeManagerPair) Manager

func (p *PipeManagerPair) Manager(id int) *Manager

Manager returns the manager at the given index (0 or 1).

func (*PipeManagerPair) PeerAddresses

func (p *PipeManagerPair) PeerAddresses(id int) PipeAddresses

PeerAddresses returns the addresses needed to send messages TO the manager at the given index. Use these addresses when sending from the other manager.

Example:

// Send from manager 0 to manager 1
pair.Manager(0).Send(data, pair.PeerAddresses(1).UDP)

func (*PipeManagerPair) Pipe

func (p *PipeManagerPair) Pipe() *Pipe

Pipe returns the underlying UDP pipe for configuration (e.g., network conditions). Returns nil if UDP is not enabled.

func (*PipeManagerPair) TCPPipe

func (p *PipeManagerPair) TCPPipe() *Pipe

TCPPipe returns the underlying TCP pipe for configuration. Returns nil if TCP is not enabled.

type PipePacketConn

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

PipePacketConn wraps a Pipe endpoint to implement net.PacketConn. This allows pipes to be used with Matter's UDP transport layer.

func (*PipePacketConn) Close

func (c *PipePacketConn) Close() error

Close closes the pipe connection.

func (*PipePacketConn) LocalAddr

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

LocalAddr returns the local address.

func (*PipePacketConn) ReadFrom

func (c *PipePacketConn) ReadFrom(b []byte) (n int, addr net.Addr, err error)

ReadFrom reads a packet from the pipe. The returned address is the peer's address.

func (*PipePacketConn) SetDeadline

func (c *PipePacketConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines.

func (*PipePacketConn) SetReadDeadline

func (c *PipePacketConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline.

func (*PipePacketConn) SetWriteDeadline

func (c *PipePacketConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline.

func (*PipePacketConn) WriteTo

func (c *PipePacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error)

WriteTo writes a packet to the pipe. The addr parameter is ignored since the pipe has only one peer.

type PipeTCPConn

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

PipeTCPConn wraps a net.Conn with pipe-specific addresses. This provides proper LocalAddr and RemoteAddr for pipe-based TCP connections.

func (*PipeTCPConn) Close

func (c *PipeTCPConn) Close() error

Close closes the connection.

func (*PipeTCPConn) LocalAddr

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

LocalAddr returns the local network address.

func (*PipeTCPConn) Read

func (c *PipeTCPConn) Read(b []byte) (n int, err error)

Read reads data from the connection.

func (*PipeTCPConn) RemoteAddr

func (c *PipeTCPConn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*PipeTCPConn) SetDeadline

func (c *PipeTCPConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines.

func (*PipeTCPConn) SetReadDeadline

func (c *PipeTCPConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline.

func (*PipeTCPConn) SetWriteDeadline

func (c *PipeTCPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline.

func (*PipeTCPConn) Write

func (c *PipeTCPConn) Write(b []byte) (n int, err error)

Write writes data to the connection.

type PipeTCPListener

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

PipeTCPListener implements net.Listener for pipe-based TCP testing. It accepts exactly one connection (the pipe's endpoint), making it suitable for point-to-point testing scenarios.

func (*PipeTCPListener) Accept

func (l *PipeTCPListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection to the listener. Since a pipe only has two endpoints, Accept will return exactly one connection (the peer's endpoint). Subsequent calls block until Close.

func (*PipeTCPListener) Addr

func (l *PipeTCPListener) Addr() net.Addr

Addr returns the listener's network address.

func (*PipeTCPListener) Close

func (l *PipeTCPListener) Close() error

Close closes the listener.

type ReceivedMessage

type ReceivedMessage struct {
	// Data contains the raw message bytes.
	Data []byte
	// PeerAddr identifies the source of the message.
	PeerAddr PeerAddress
}

ReceivedMessage represents an incoming message from the network. The Data field contains the raw message bytes as received from the wire, including the Matter message header, payload, and MIC (if encrypted). Higher layers are responsible for parsing and processing the message.

type TCP

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

TCP provides TCP transport for Matter messages. It wraps a net.Listener and manages persistent connections with peers. Messages are framed with a 4-byte length prefix per Spec Section 4.5.

func NewTCP

func NewTCP(config TCPConfig) (*TCP, error)

NewTCP creates a new TCP transport with the given configuration.

func (*TCP) AddConnection

func (t *TCP) AddConnection(conn net.Conn)

AddConnection adds an existing connection to the transport. This is useful for testing with net.Pipe().

func (*TCP) LocalAddr

func (t *TCP) LocalAddr() net.Addr

LocalAddr returns the local address the transport is listening on.

func (*TCP) Send

func (t *TCP) Send(data []byte, addr net.Addr) error

Send sends a message to the specified address over TCP. If no connection exists, one will be established.

func (*TCP) SendRaw

func (t *TCP) SendRaw(data []byte, addr net.Addr) error

SendRaw sends raw data with length prefix to the specified address.

func (*TCP) Start

func (t *TCP) Start() error

Start begins accepting connections and receiving messages.

func (*TCP) Stop

func (t *TCP) Stop() error

Stop closes all connections and the listener.

type TCPConfig

type TCPConfig struct {
	// Listener is an optional pre-existing Listener to use.
	// If nil, a new listener will be created using ListenAddr.
	Listener net.Listener

	// ListenAddr is the address to listen on (e.g., ":5540").
	// Ignored if Listener is provided.
	ListenAddr string

	// MessageHandler is called for each received message.
	// Required.
	MessageHandler MessageHandler

	// LoggerFactory is the factory for creating loggers.
	// If nil, logging is disabled.
	LoggerFactory logging.LoggerFactory
}

TCPConfig configures the TCP transport.

type TransportType

type TransportType int

TransportType identifies the transport protocol used for a message.

const (
	// TransportTypeUnknown is the zero value for unknown transport.
	TransportTypeUnknown TransportType = iota
	// TransportTypeUDP indicates UDP transport.
	TransportTypeUDP
	// TransportTypeTCP indicates TCP transport.
	TransportTypeTCP
)

func (TransportType) IsValid

func (t TransportType) IsValid() bool

IsValid returns true if the transport type is a known valid type.

func (TransportType) String

func (t TransportType) String() string

String returns the string representation of the transport type.

type UDP

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

UDP provides UDP transport for Matter messages. It wraps a net.PacketConn and provides a read loop that calls the configured MessageHandler for each received message.

func NewUDP

func NewUDP(config UDPConfig) (*UDP, error)

NewUDP creates a new UDP transport with the given configuration.

func (*UDP) LocalAddr

func (u *UDP) LocalAddr() net.Addr

LocalAddr returns the local address the transport is listening on.

func (*UDP) Send

func (u *UDP) Send(data []byte, addr net.Addr) error

Send sends a message to the specified address.

func (*UDP) Start

func (u *UDP) Start() error

Start begins the read loop for receiving messages. Messages are delivered to the configured MessageHandler.

func (*UDP) Stop

func (u *UDP) Stop() error

Stop closes the transport and waits for the read loop to exit.

type UDPConfig

type UDPConfig struct {
	// Conn is an optional pre-existing PacketConn to use.
	// If nil, a new connection will be created using ListenAddr.
	Conn net.PacketConn

	// ListenAddr is the address to listen on (e.g., ":5540").
	// Ignored if Conn is provided.
	ListenAddr string

	// MessageHandler is called for each received message.
	// Required.
	MessageHandler MessageHandler

	// LoggerFactory is the factory for creating loggers.
	// If nil, logging is disabled.
	LoggerFactory logging.LoggerFactory
}

UDPConfig configures the UDP transport.

Jump to

Keyboard shortcuts

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