nt4

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 19 Imported by: 0

README

go-nt4

CI Go Reference Go Report Card

Go implementation of the WPILib NT4 protocol.

Installation

go get github.com/levifitzpatrick1/go-nt4

Usage

package main

import (
	"fmt"
	"log"
	"time"

	nt4 "github.com/levifitzpatrick1/go-nt4"
)

func main() {
	// Connect to NT4 server at 10.20.64.2
	opts := nt4.DefaultClientOptions(nt4.TeamNumberToAddress(2064))
	opts.OnConnect = func() {
		fmt.Println("NT4 Client Connected")
	}
	opts.OnDisconnect = func() {
		fmt.Println("NT4 Client Disconnected")
	}

	client, err := nt4.NewClient(opts)
	if err != nil {
		log.Fatal(err)
	}

	if err := client.Connect(); err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect()

	// Publish a topic and send data
	pub, err := client.PublishDouble("/SmartDashboard/Speed", 42.5)
	if err != nil {
		log.Fatal(err)
	}
	_ = pub.Set(43.0)

	// Subscribe to a topic prefix with a callback
	sub, err := client.SubscribeWithPrefix("/SmartDashboard/", func(topic *nt4.Topic, timestamp int64, value any) {
		fmt.Printf("Callback received: %s = %v\n", topic.Name, value)
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sub.Close()

	// Receive data from channel
	go func() {
		for update := range sub.Updates() {
			fmt.Printf("Channel update: %s = %v\n", update.Topic.Name, update.Value)
		}
	}()

	// Retrieve a single value with timeout
	speed, ok := client.GetDouble("/SmartDashboard/Speed", 2*time.Second)
	if ok {
		fmt.Printf("Speed retrieved: %v\n", speed)
	}

	// Read from cache
	if sample, ok := client.Latest("/SmartDashboard/Speed"); ok {
		fmt.Printf("Cached Speed: %v (timestamp: %d)\n", sample.Value, sample.Timestamp)
	}
}

Features

Client Builder
client, err := nt4.NewClientBuilder().
	Team(2064).
	Name("Dashboard").
	Build()
Typed Publish Methods
client.PublishDouble("/SmartDashboard/Speed", 42.5)
client.PublishString("/SmartDashboard/Mode", "teleop")
client.PublishBoolean("/SmartDashboard/Enabled", true)
client.PublishInt("/SmartDashboard/ShooterRPM", 3500)
client.PublishDoubleArray("/SmartDashboard/Position", []float64{1.0, 2.0, 3.0})
client.PublishStringArray("/SmartDashboard/Cameras", []string{"front", "back"})
client.PublishRaw("/Vision/TargetBytes", []byte{0xDE, 0xAD, 0xBE, 0xEF})
Typed Getters
speed, ok := client.GetDouble("/SmartDashboard/Speed", 2*time.Second)
mode, ok := client.GetString("/SmartDashboard/Mode", 2*time.Second)
enabled, ok := client.GetBoolean("/SmartDashboard/Enabled", 2*time.Second)
rpm, ok := client.GetInt("/SmartDashboard/ShooterRPM", 2*time.Second)
pos, ok := client.GetDoubleArray("/SmartDashboard/Position", 2*time.Second)
Prefix Subscriptions
// Subscribe to all topics starting with /SmartDashboard
sub, err := client.SubscribeWithPrefix("/SmartDashboard/", func(topic *nt4.Topic, timestamp int64, value any) {
	fmt.Printf("%s: %v\n", topic.Name, value)
})
defer sub.Close()

for update := range sub.Updates() {
	fmt.Printf("%s: %v\n", update.Topic.Name, update.Value)
}
Subscriptions & Events
sub, err := client.Subscribe([]string{"/CameraPublisher/"}, nt4.SubscriptionOptions{
	Prefix:         true,
	All:            true,
	Mode:           nt4.DeliveryAll,
	BufferCapacity: 256,
})
defer sub.Close()

for ev := range sub.Events() {
	switch ev.Kind {
	case nt4.Announced:
		fmt.Println("Announced:", ev.Topic.Name, ev.Topic.Type)
	case nt4.ValueReceived:
		fmt.Printf("Value: %s = %v\n", ev.Topic.Name, ev.Sample.Value)
	case nt4.ServerUnannounced:
		fmt.Println("Unannounced:", ev.Topic.Name)
	}
}
Connection with Retry
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

if err := client.ConnectWithRetry(ctx); err != nil {
	log.Fatal("Failed to connect:", err)
}

Data Types

NT4 Constant Type String Go Type Description
nt4.TypeBoolean "boolean" bool Boolean
nt4.TypeDouble "double" float64 64-bit float
nt4.TypeInt "int" int64 64-bit integer
nt4.TypeFloat "float" float32 32-bit float
nt4.TypeString "string" string String
nt4.TypeRaw "raw" []byte Binary bytes
nt4.TypeBooleanArray "boolean[]" []bool Boolean array
nt4.TypeDoubleArray "double[]" []float64 Float array
nt4.TypeIntArray "int[]" []int64 Integer array
nt4.TypeFloatArray "float[]" []float32 Float array
nt4.TypeStringArray "string[]" []string String array
nt4.TypeJSON "json" string JSON string

Examples

See the examples/ directory for complete working examples:

Documentation

Full API documentation is available at pkg.go.dev.

License

MIT

Documentation

Overview

Package nt4 implements an NT4.1/4.0 reconnecting NetworkTables client with owned values, bounded channel subscriptions, immediate cached reads, and robust reconnection. Timestamps are signed server-relative microseconds scoped to a connection epoch.

Index

Constants

View Source
const (
	TypeBoolean      = "boolean"
	TypeDouble       = "double"
	TypeInt          = "int"
	TypeFloat        = "float"
	TypeString       = "string"
	TypeBooleanArray = "boolean[]"
	TypeDoubleArray  = "double[]"
	TypeIntArray     = "int[]"
	TypeFloatArray   = "float[]"
	TypeStringArray  = "string[]"
	TypeRaw          = "raw"
	TypeMsgpack      = "msgpack"
	TypeProtobuf     = "protobuf"
	TypeJSON         = "json"
)

Topic type string constants.

View Source
const (
	DataTypeBoolean      = 0
	DataTypeDouble       = 1
	DataTypeInt          = 2
	DataTypeFloat        = 3
	DataTypeString       = 4
	DataTypeBinary       = 5
	DataTypeBooleanArray = 16
	DataTypeDoubleArray  = 17
	DataTypeIntArray     = 18
	DataTypeFloatArray   = 19
	DataTypeStringArray  = 20
)

Data type binary ID constants.

View Source
const DefaultPort = 5810

DefaultPort is the standard NetworkTables 4 server port.

Variables

View Source
var (
	ErrClosed                   = errors.New("nt4: closed")
	ErrAlreadyStarted           = errors.New("nt4: already started")
	ErrInvalidHandle            = errors.New("nt4: invalid handle")
	ErrForeignHandle            = errors.New("nt4: foreign handle")
	ErrInvalidOptions           = errors.New("nt4: invalid options")
	ErrInvalidValue             = errors.New("nt4: invalid value")
	ErrInvalidType              = errors.New("nt4: invalid type")
	ErrTypeConflict             = errors.New("nt4: type conflict")
	ErrQueueFull                = errors.New("nt4: queue full")
	ErrIncompatibleOptions      = errors.New("nt4: incompatible options")
	ErrTimestampUnrepresentable = errors.New("nt4: timestamp unrepresentable")
	ErrSubscriptionOverflow     = errors.New("nt4: subscription overflow")
	ErrProtocol                 = errors.New("nt4: protocol error")
)

Functions

func CloneValue added in v0.2.0

func CloneValue(v any) any

CloneValue owns the mutable NT families; use only with already validated values.

func JSONSize added in v0.2.0

func JSONSize(m map[string]any, limits JSONLimits) (int, error)

JSONSize reports the validated tree's conservative size for queue accounting.

func OwnJSON added in v0.2.0

func OwnJSON(input map[string]any, limits JSONLimits) (map[string]any, int, error)

OwnJSON validates JSON before encoding and returns a deep-owned tree. Null property values remain nil for protocol deletion semantics.

func OwnValue added in v0.2.0

func OwnValue(typeName string, input any, maxBytes int) (any, int, error)

OwnValue validates, copies and measures a value before admission. The size is its upper-bound payload estimate (array headers and lengths included).

func TeamNumberToAddress

func TeamNumberToAddress(teamNumber int) string

TeamNumberToAddress converts an FRC team number to a roboRIO server IP address. For example: 2064 becomes "10.20.64.2", and 254 becomes "10.2.54.2".

func TypeID added in v0.2.0

func TypeID(name string) (int, error)

TypeID preserves unknown textual types as binary, rather than guessing their encoding.

func TypeIDToString

func TypeIDToString(typeID int) string

TypeIDToString maps an NT4 numeric ID to its standard type string.

func TypeStringToID

func TypeStringToID(typeStr string) int

TypeStringToID maps an NT4 type string to a numeric ID.

func ValidatePatterns added in v0.2.0

func ValidatePatterns(patterns []string, prefix bool, maxNameBytes int) error

ValidatePatterns accepts slashless and empty prefix patterns; exact empty names are invalid.

func ValidatePublisherOptions added in v0.2.0

func ValidatePublisherOptions(o PublisherOptions, c ClientOptions) error

ValidatePublisherOptions checks both local and total offline-history bounds.

func ValidateTopicName added in v0.2.0

func ValidateTopicName(name string, maxBytes int) error

ValidateTopicName rejects only invalid UTF-8, oversize names and the reserved local '$' namespace.

func ValueSize added in v0.2.0

func ValueSize(v any) int

ValueSize counts a validated value's estimated serialized payload bytes.

Types

type Client

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

func NewClient

func NewClient(o ClientOptions) (*Client, error)

func (*Client) Close added in v0.2.0

func (c *Client) Close() error

func (*Client) Connect

func (c *Client) Connect() error

Connect starts the client background connection and reconnection loop using context.Background().

func (*Client) ConnectWithRetry

func (c *Client) ConnectWithRetry(ctx context.Context) error

ConnectWithRetry starts the client and waits for the initial connection to be established.

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect gracefully terminates all connections and worker goroutines.

func (*Client) GetBoolean

func (c *Client) GetBoolean(name string, timeout time.Duration) (bool, bool)

GetBoolean retrieves a boolean value from a topic within the timeout.

func (*Client) GetBooleanArray added in v0.2.0

func (c *Client) GetBooleanArray(name string, timeout time.Duration) ([]bool, bool)

GetBooleanArray retrieves a []bool slice from a topic within the timeout.

func (*Client) GetDouble

func (c *Client) GetDouble(name string, timeout time.Duration) (float64, bool)

GetDouble retrieves a 64-bit float value from a topic within the timeout.

func (*Client) GetDoubleArray added in v0.2.0

func (c *Client) GetDoubleArray(name string, timeout time.Duration) ([]float64, bool)

GetDoubleArray retrieves a []float64 slice from a topic within the timeout.

func (*Client) GetFloat added in v0.2.0

func (c *Client) GetFloat(name string, timeout time.Duration) (float32, bool)

GetFloat retrieves a 32-bit float value from a topic within the timeout.

func (*Client) GetInt

func (c *Client) GetInt(name string, timeout time.Duration) (int64, bool)

GetInt retrieves a 64-bit integer value from a topic within the timeout.

func (*Client) GetIntArray added in v0.2.0

func (c *Client) GetIntArray(name string, timeout time.Duration) ([]int64, bool)

GetIntArray retrieves a []int64 slice from a topic within the timeout.

func (*Client) GetLastRTT

func (c *Client) GetLastRTT() int64

GetLastRTT returns the last measured round-trip time in microseconds.

func (*Client) GetRaw added in v0.2.0

func (c *Client) GetRaw(name string, timeout time.Duration) ([]byte, bool)

GetRaw retrieves a []byte slice from a topic within the timeout.

func (*Client) GetServerTimeOffset

func (c *Client) GetServerTimeOffset() int64

GetServerTimeOffset returns the estimated server clock offset in microseconds.

func (*Client) GetString

func (c *Client) GetString(name string, timeout time.Duration) (string, bool)

GetString retrieves a string value from a topic within the timeout.

func (*Client) GetStringArray added in v0.2.0

func (c *Client) GetStringArray(name string, timeout time.Duration) ([]string, bool)

GetStringArray retrieves a []string slice from a topic within the timeout.

func (*Client) GetTopic

func (c *Client) GetTopic(name string) *Topic

GetTopic returns a *Topic representation of a topic by name, or nil if not found.

func (*Client) GetTopics

func (c *Client) GetTopics() []*Topic

GetTopics returns a slice of all currently known topics as *Topic objects.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected reports whether the client currently has an active connection to the server.

func (*Client) Latest added in v0.2.0

func (c *Client) Latest(name string) (Sample, bool)

func (*Client) Publish

func (c *Client) Publish(name, typeName string, props map[string]any, o PublisherOptions) (*Publisher, error)

func (*Client) PublishBoolean

func (c *Client) PublishBoolean(name string, value bool) (*Publisher, error)

PublishBoolean publishes or updates a boolean topic.

func (*Client) PublishBooleanArray

func (c *Client) PublishBooleanArray(name string, value []bool) (*Publisher, error)

PublishBooleanArray publishes or updates a []bool topic.

func (*Client) PublishDouble

func (c *Client) PublishDouble(name string, value float64) (*Publisher, error)

PublishDouble publishes or updates a 64-bit float topic.

func (*Client) PublishDoubleArray

func (c *Client) PublishDoubleArray(name string, value []float64) (*Publisher, error)

PublishDoubleArray publishes or updates a []float64 topic.

func (*Client) PublishFloat added in v0.2.0

func (c *Client) PublishFloat(name string, value float32) (*Publisher, error)

PublishFloat publishes or updates a 32-bit float topic.

func (*Client) PublishFloatArray added in v0.2.0

func (c *Client) PublishFloatArray(name string, value []float32) (*Publisher, error)

PublishFloatArray publishes or updates a []float32 topic.

func (*Client) PublishInt

func (c *Client) PublishInt(name string, value int64) (*Publisher, error)

PublishInt publishes or updates a 64-bit integer topic.

func (*Client) PublishIntArray

func (c *Client) PublishIntArray(name string, value []int64) (*Publisher, error)

PublishIntArray publishes or updates a []int64 topic.

func (*Client) PublishRaw

func (c *Client) PublishRaw(name string, value []byte) (*Publisher, error)

PublishRaw publishes or updates a raw binary []byte topic.

func (*Client) PublishString

func (c *Client) PublishString(name string, value string) (*Publisher, error)

PublishString publishes or updates a string topic.

func (*Client) PublishStringArray

func (c *Client) PublishStringArray(name string, value []string) (*Publisher, error)

PublishStringArray publishes or updates a []string topic.

func (*Client) PublishTopic added in v0.2.0

func (c *Client) PublishTopic(name, typeStr string, props map[string]any) (*Publisher, error)

PublishTopic publishes a topic with default options.

func (*Client) SetProperties

func (c *Client) SetProperties(name string, update map[string]any) error

func (*Client) SetValue

func (c *Client) SetValue(target any, value any) error

SetValue updates the value of a topic or publisher handle. Target can be a *Publisher, *Topic, or topic name string.

func (*Client) Start added in v0.2.0

func (c *Client) Start(ctx context.Context) error

func (*Client) StateChanges added in v0.2.0

func (c *Client) StateChanges() <-chan Status

func (*Client) Status added in v0.2.0

func (c *Client) Status() Status

func (*Client) Subscribe

func (c *Client) Subscribe(patterns []string, o SubscriptionOptions) (*Subscription, error)

func (*Client) SubscribeAndRetrieve

func (c *Client) SubscribeAndRetrieve(topic string, timeout time.Duration) any

SubscribeAndRetrieve temporarily subscribes to a topic, waits for its value, and returns it.

func (*Client) SubscribeWithOptions added in v0.2.0

func (c *Client) SubscribeWithOptions(patterns []string, o SubscribeOptions) (*Subscription, error)

SubscribeWithOptions subscribes using the v0.1.1 SubscribeOptions configuration struct.

func (*Client) SubscribeWithPrefix

func (c *Client) SubscribeWithPrefix(prefix string, callback func(topic *Topic, timestamp int64, value any)) (*Subscription, error)

SubscribeWithPrefix subscribes to all topics under a prefix and delivers updates to a callback.

func (*Client) Topic added in v0.2.0

func (c *Client) Topic(name string) (TopicSnapshot, bool)

func (*Client) Topics added in v0.2.0

func (c *Client) Topics() []TopicSnapshot

Topics returns snapshots of all currently known topics.

func (*Client) Unpublish

func (c *Client) Unpublish(p *Publisher) error

Unpublish closes and removes a publisher handle.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(s *Subscription) error

Unsubscribe closes the given subscription handle.

func (*Client) WaitConnected added in v0.2.0

func (c *Client) WaitConnected(ctx context.Context) error

func (*Client) WaitForConnection

func (c *Client) WaitForConnection(ctx context.Context) error

WaitForConnection blocks until the client is connected or the context expires.

func (*Client) WaitForValue added in v0.2.0

func (c *Client) WaitForValue(ctx context.Context, name string) (Sample, error)

WaitForValue observes a current value without consuming any existing subscription. It owns and disposes its bounded temporary subscription on every exit path.

func (*Client) WaitReady added in v0.2.0

func (c *Client) WaitReady(ctx context.Context) error

type ClientBuilder added in v0.2.0

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

ClientBuilder provides a fluent interface for configuring and creating a Client.

func NewClientBuilder added in v0.2.0

func NewClientBuilder() *ClientBuilder

NewClientBuilder creates a new ClientBuilder with default settings (127.0.0.1:5810).

func (*ClientBuilder) Build added in v0.2.0

func (b *ClientBuilder) Build() (*Client, error)

Build validates options and creates a new NT4 Client.

func (*ClientBuilder) BuildAndStart added in v0.2.0

func (b *ClientBuilder) BuildAndStart(ctx context.Context) (*Client, error)

BuildAndStart creates and starts the Client with the provided context. If starting fails, the client is closed automatically before returning the error.

func (*ClientBuilder) DialTimeout added in v0.2.0

func (b *ClientBuilder) DialTimeout(d time.Duration) *ClientBuilder

DialTimeout sets the connection timeout for dialing the server.

func (*ClientBuilder) EndpointURL added in v0.2.0

func (b *ClientBuilder) EndpointURL(url string) *ClientBuilder

EndpointURL overrides the server address and port with an explicit ws:// or wss:// URL.

func (*ClientBuilder) Identity added in v0.2.0

func (b *ClientBuilder) Identity(id string) *ClientBuilder

Identity sets the client identifier (alias for Name).

func (*ClientBuilder) Keepalive added in v0.2.0

func (b *ClientBuilder) Keepalive(interval time.Duration) *ClientBuilder

Keepalive sets the ping keepalive interval.

func (*ClientBuilder) Logger added in v0.2.0

func (b *ClientBuilder) Logger(l Logger) *ClientBuilder

Logger sets the logger instance.

func (*ClientBuilder) Name added in v0.2.0

func (b *ClientBuilder) Name(name string) *ClientBuilder

Name sets the client identification name sent to the server.

func (*ClientBuilder) OnConnect added in v0.2.0

func (b *ClientBuilder) OnConnect(fn func()) *ClientBuilder

OnConnect sets a callback invoked when the client connects to the server.

func (*ClientBuilder) OnDisconnect added in v0.2.0

func (b *ClientBuilder) OnDisconnect(fn func()) *ClientBuilder

OnDisconnect sets a callback invoked when the client disconnects from the server.

func (*ClientBuilder) OnTopicAnnounce added in v0.2.0

func (b *ClientBuilder) OnTopicAnnounce(fn func(topic *Topic)) *ClientBuilder

OnTopicAnnounce sets a callback invoked when a topic is announced.

func (*ClientBuilder) OnTopicUnannounce added in v0.2.0

func (b *ClientBuilder) OnTopicUnannounce(fn func(topic *Topic)) *ClientBuilder

OnTopicUnannounce sets a callback invoked when a topic is unannounced.

func (*ClientBuilder) Options added in v0.2.0

func (b *ClientBuilder) Options(opts ClientOptions) *ClientBuilder

Options sets or overrides the underlying ClientOptions directly.

func (*ClientBuilder) Port added in v0.2.0

func (b *ClientBuilder) Port(port int) *ClientBuilder

Port sets the server port (default: 5810).

func (*ClientBuilder) ReadTimeout added in v0.2.0

func (b *ClientBuilder) ReadTimeout(d time.Duration) *ClientBuilder

ReadTimeout sets the read timeout for inbound WebSocket frames.

func (*ClientBuilder) ReconnectInterval added in v0.2.0

func (b *ClientBuilder) ReconnectInterval(d time.Duration) *ClientBuilder

ReconnectInterval sets the delay between reconnection attempts.

func (*ClientBuilder) Retry added in v0.2.0

func (b *ClientBuilder) Retry(min, max time.Duration) *ClientBuilder

Retry sets the minimum and maximum reconnect backoff intervals.

func (*ClientBuilder) Server added in v0.2.0

func (b *ClientBuilder) Server(address string) *ClientBuilder

Server sets the server host or IP address.

func (*ClientBuilder) Team added in v0.2.0

func (b *ClientBuilder) Team(teamNumber int) *ClientBuilder

Team sets the server address to the standard FRC roboRIO IP for the given team number. For example, b.Team(2064) sets the address to "10.20.64.2".

func (*ClientBuilder) WriteTimeout added in v0.2.0

func (b *ClientBuilder) WriteTimeout(d time.Duration) *ClientBuilder

WriteTimeout sets the write timeout for outbound WebSocket frames.

type ClientOptions

type ClientOptions struct {
	ServerAddress                                                                 string
	Port                                                                          int
	ClientName                                                                    string
	Identity                                                                      string
	EndpointURL                                                                   string
	OnConnect                                                                     func()
	OnDisconnect                                                                  func()
	OnTopicAnnounce                                                               func(topic *Topic)
	OnTopicUnannounce                                                             func(topic *Topic)
	ReconnectInterval                                                             time.Duration
	Logger                                                                        Logger
	CommandCapacity, CommandMaxBytes                                              int
	InboundCapacity, InboundMaxBytes                                              int
	WriterCapacity, WriterMaxBytes                                                int
	TotalOfflineCapacity, TotalOfflineMaxBytes                                    int
	RetainedMaxBytes                                                              int
	MaxTopics, MaxPublishers, MaxSubscriptions                                    int
	MaxTextBytes, MaxBinaryBytes                                                  int
	MaxJSONDepth, MaxJSONContainerItems, MaxNameBytes                             int
	DialTimeout, WriteTimeout, ReadTimeout, RetryMin, RetryMax, KeepaliveInterval time.Duration
}

Zero-valued limits select finite defaults. Negative limits and durations are invalid.

func DefaultClientOptions

func DefaultClientOptions(serverAddress string) ClientOptions

DefaultClientOptions returns ClientOptions initialized with sensible defaults for the given server address.

func NormalizeClientOptions added in v0.2.0

func NormalizeClientOptions(o ClientOptions) (ClientOptions, error)

NormalizeClientOptions validates and fills finite resource and time limits.

type DefaultLogger

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

DefaultLogger provides a simple logger that writes to stdout using the standard library log package.

func NewDefaultLogger

func NewDefaultLogger(level LogLevel) *DefaultLogger

NewDefaultLogger creates a new DefaultLogger with the specified log level.

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(msg string, keysAndValues ...any)

Debug logs a debug message if the log level is LogLevelDebug.

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string, keysAndValues ...any)

Error logs an error message if the log level is LogLevelError or lower.

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string, keysAndValues ...any)

Info logs an informational message if the log level is LogLevelInfo or lower.

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(msg string, keysAndValues ...any)

Warn logs a warning message if the log level is LogLevelWarn or lower.

type DeliveryMode added in v0.2.0

type DeliveryMode uint8
const (
	DeliveryLatest DeliveryMode = iota
	DeliveryAll
)

type Event added in v0.2.0

type Event struct {
	Kind       EventKind
	Topic      TopicSnapshot
	Sample     Sample
	Epoch      uint64
	ReceivedAt time.Time
	Ack        bool
}

func (Event) Clone added in v0.2.0

func (e Event) Clone() Event

type EventKind added in v0.2.0

type EventKind uint8
const (
	Announced EventKind = iota
	PropertiesChanged
	ValueReceived
	ServerUnannounced
	LocalInvalidated
)

type JSONLimits added in v0.2.0

type JSONLimits struct{ MaxBytes, MaxDepth, MaxContainerItems, MaxNameBytes int }

JSONLimits are finite admission limits, independent of transport frame limits.

type LifecycleState added in v0.2.0

type LifecycleState uint8
const (
	StateIdle LifecycleState = iota
	StateDialing
	StateOnlineUnsynchronized
	StateOnlineReady
	StateBackoff
	StateClosing
	StateClosed
)

type LogLevel

type LogLevel int

LogLevel represents the severity of a log message.

const (
	// LogLevelDebug enables all logging including verbose debug messages.
	LogLevelDebug LogLevel = iota
	// LogLevelInfo enables informational messages, warnings, and errors.
	LogLevelInfo
	// LogLevelWarn enables warnings and errors only.
	LogLevelWarn
	// LogLevelError enables error messages only.
	LogLevelError
	// LogLevelSilent disables all logging.
	LogLevelSilent
)

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of a LogLevel.

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Warn(msg string, keysAndValues ...any)
	Error(msg string, keysAndValues ...any)
}

Logger is the interface for logging within the NT4 client.

func NewSilentLogger

func NewSilentLogger() Logger

NewSilentLogger returns a logger that discards all log messages.

type Publisher added in v0.2.0

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

func (*Publisher) Close added in v0.2.0

func (p *Publisher) Close() error

func (*Publisher) DiscardPending added in v0.2.0

func (p *Publisher) DiscardPending() error

func (*Publisher) Err added in v0.2.0

func (p *Publisher) Err() error

func (*Publisher) Errors added in v0.2.0

func (p *Publisher) Errors() <-chan error

Errors is an independent coalescing asynchronous notification channel. The owner calls report on conflicting remote announcements and mapping failures.

func (*Publisher) Set added in v0.2.0

func (p *Publisher) Set(v any) error

func (*Publisher) SetAt added in v0.2.0

func (p *Publisher) SetAt(at time.Time, v any) error

func (*Publisher) SetContext added in v0.2.0

func (p *Publisher) SetContext(ctx context.Context, v any) error

func (*Publisher) SetDefault added in v0.2.0

func (p *Publisher) SetDefault(v any) error

func (*Publisher) TrySet added in v0.2.0

func (p *Publisher) TrySet(v any) error

type PublisherOptions added in v0.2.0

type PublisherOptions struct{ OfflineQueueCapacity, OfflineQueueMaxBytes int }

type Sample added in v0.2.0

type Sample struct {
	Value      any
	Timestamp  int64
	Epoch      uint64
	ReceivedAt time.Time
	Stale      bool
}

Snapshots handed to callers must be copied from the owner's private records.

func (Sample) Clone added in v0.2.0

func (s Sample) Clone() Sample

type SilentLogger

type SilentLogger struct{}

SilentLogger is a logger that discards all log messages.

func (*SilentLogger) Debug

func (l *SilentLogger) Debug(msg string, keysAndValues ...any)

func (*SilentLogger) Error

func (l *SilentLogger) Error(msg string, keysAndValues ...any)

func (*SilentLogger) Info

func (l *SilentLogger) Info(msg string, keysAndValues ...any)

func (*SilentLogger) Warn

func (l *SilentLogger) Warn(msg string, keysAndValues ...any)

type Status added in v0.2.0

type Status struct {
	State                                             LifecycleState
	Epoch                                             uint64
	Protocol                                          string
	Ready                                             bool
	ClockValid                                        bool
	RTT, ClockOffset                                  time.Duration
	LastLoss, LastError                               error
	CommandItems, CommandBytes                        uint64
	InboundItems, InboundBytes                        uint64
	WriterItems, WriterBytes                          uint64
	OfflineItems, OfflineBytes                        uint64
	RetainedBytes                                     uint64
	Dropped, Rejected, Uncertain, StateChangesDropped uint64
}

Status is a point-in-time diagnostic, not a delivery acknowledgement.

type SubscribeOptions

type SubscribeOptions struct {
	Periodic   time.Duration
	All        bool
	TopicsOnly bool
	Prefix     bool
}

SubscribeOptions provides an intuitive configuration for subscriptions.

type Subscription

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

Subscription is an opaque identity. Copying it does not create a second registration.

func (*Subscription) Close added in v0.2.0

func (s *Subscription) Close() error

func (*Subscription) Dropped added in v0.2.0

func (s *Subscription) Dropped() uint64

func (*Subscription) Err added in v0.2.0

func (s *Subscription) Err() <-chan error

func (*Subscription) Events added in v0.2.0

func (s *Subscription) Events() <-chan Event

func (*Subscription) GetCallback

func (s *Subscription) GetCallback() func(topic *Topic, timestamp int64, value any)

GetCallback returns the currently registered callback, if any.

func (*Subscription) SetCallback

func (s *Subscription) SetCallback(callback func(topic *Topic, timestamp int64, value any))

SetCallback registers a callback to be called whenever a new value arrives for this subscription.

func (*Subscription) Updates

func (s *Subscription) Updates() <-chan TopicUpdate

Updates returns a channel delivering TopicUpdate values.

type SubscriptionOptions added in v0.2.0

type SubscriptionOptions struct {
	Prefix, All, TopicsOnly        bool
	Periodic                       time.Duration
	Mode                           DeliveryMode
	BufferCapacity, BufferMaxBytes int
}

func NormalizeSubscriptionOptions added in v0.2.0

func NormalizeSubscriptionOptions(o SubscriptionOptions) (SubscriptionOptions, error)

NormalizeSubscriptionOptions fills bounded delivery defaults and checks server All for lossless local delivery.

type Topic

type Topic struct {
	ID         int32
	Name       string
	Type       string
	TypeID     int
	Properties map[string]any
	PubUID     int32
	Publisher  *Publisher
	// contains filtered or unexported fields
}

Topic represents a NetworkTables topic.

func (*Topic) UpdateProperties

func (t *Topic) UpdateProperties(props map[string]any)

UpdateProperties merges new properties into the topic's property map.

type TopicSnapshot added in v0.2.0

type TopicSnapshot struct {
	Name, Type string
	ID         int32
	HasID      bool
	Properties map[string]any
	Epoch      uint64
	Stale      bool
}

func (TopicSnapshot) Clone added in v0.2.0

func (t TopicSnapshot) Clone() TopicSnapshot

type TopicUpdate

type TopicUpdate struct {
	Topic     *Topic
	Timestamp int64
	Value     any
}

TopicUpdate represents an update to a subscribed topic.

Directories

Path Synopsis
examples
bidirectional command
publisher command
subscriber command
team_robot command
internal
testpeer
Package testpeer provides a scripted raw WebSocket peer for NT4 client tests.
Package testpeer provides a scripted raw WebSocket peer for NT4 client tests.
wire
Package wire implements the NT4 protocol wire format: the JSON control messages exchanged as WebSocket text frames and the MessagePack value frames exchanged as binary frames.
Package wire implements the NT4 protocol wire format: the JSON control messages exchanged as WebSocket text frames and the MessagePack value frames exchanged as binary frames.

Jump to

Keyboard shortcuts

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