Documentation
¶
Overview ¶
Package goadstc provides a Go client library for TwinCAT ADS/AMS communication over TCP.
Index ¶
- Constants
- func ContextWithLogFields(ctx context.Context, args ...any) context.Context
- func NewADSError(operation string, adsErr ads.Error) error
- func NewNetworkError(operation string, err error) error
- func NewStateError(operation, message string) error
- func NewValidationError(operation, message string) error
- func Version() string
- type BuildInfo
- type ClassifiedError
- type Client
- func (c *Client) Close() error
- func (c *Client) FindSymbols(ctx context.Context, pattern string) ([]*symbols.Symbol, error)
- func (c *Client) GetDataTypeUploadInfo(ctx context.Context) (dataTypeCount, dataTypeSize uint32, err error)
- func (c *Client) GetRegisteredType(typeName string) (symbols.TypeInfo, bool)
- func (c *Client) GetSymbol(name string) (*symbols.Symbol, error)
- func (c *Client) GetSymbolHandle(ctx context.Context, symbolName string) (uint32, error)
- func (c *Client) GetSymbolUploadInfo(ctx context.Context) (symbolCount, symbolLength uint32, err error)
- func (c *Client) ListRegisteredTypes() []string
- func (c *Client) ListSymbols(ctx context.Context) ([]*symbols.Symbol, error)
- func (c *Client) Read(ctx context.Context, indexGroup, indexOffset, length uint32) ([]byte, error)
- func (c *Client) ReadBool(ctx context.Context, symbolName string) (bool, error)
- func (c *Client) ReadDate(ctx context.Context, symbolName string) (time.Time, error)
- func (c *Client) ReadDateAndTime(ctx context.Context, symbolName string) (time.Time, error)
- func (c *Client) ReadDeviceInfo(ctx context.Context) (*DeviceInfo, error)
- func (c *Client) ReadFloat32(ctx context.Context, symbolName string) (float32, error)
- func (c *Client) ReadFloat64(ctx context.Context, symbolName string) (float64, error)
- func (c *Client) ReadInt8(ctx context.Context, symbolName string) (int8, error)
- func (c *Client) ReadInt16(ctx context.Context, symbolName string) (int16, error)
- func (c *Client) ReadInt32(ctx context.Context, symbolName string) (int32, error)
- func (c *Client) ReadInt64(ctx context.Context, symbolName string) (int64, error)
- func (c *Client) ReadMultipleSymbolValues(ctx context.Context, symbolNames ...string) (map[string]interface{}, error)
- func (c *Client) ReadState(ctx context.Context) (*DeviceState, error)
- func (c *Client) ReadString(ctx context.Context, symbolName string) (string, error)
- func (c *Client) ReadStructAsMap(ctx context.Context, symbolName string) (map[string]interface{}, error)deprecated
- func (c *Client) ReadStructFieldBool(ctx context.Context, fieldPath string) (bool, error)deprecated
- func (c *Client) ReadStructFieldInt16(ctx context.Context, fieldPath string) (int16, error)deprecated
- func (c *Client) ReadStructFieldInt32(ctx context.Context, fieldPath string) (int32, error)deprecated
- func (c *Client) ReadStructFieldUint16(ctx context.Context, fieldPath string) (uint16, error)deprecated
- func (c *Client) ReadStructFieldUint32(ctx context.Context, fieldPath string) (uint32, error)deprecated
- func (c *Client) ReadSymbol(ctx context.Context, symbolName string) ([]byte, error)
- func (c *Client) ReadSymbolValue(ctx context.Context, symbolName string) (interface{}, error)
- func (c *Client) ReadTime(ctx context.Context, symbolName string) (time.Duration, error)
- func (c *Client) ReadTimeOfDay(ctx context.Context, symbolName string) (time.Duration, error)
- func (c *Client) ReadUint8(ctx context.Context, symbolName string) (uint8, error)
- func (c *Client) ReadUint16(ctx context.Context, symbolName string) (uint16, error)
- func (c *Client) ReadUint32(ctx context.Context, symbolName string) (uint32, error)
- func (c *Client) ReadUint64(ctx context.Context, symbolName string) (uint64, error)
- func (c *Client) ReadWString(ctx context.Context, symbolName string) (string, error)
- func (c *Client) ReadWrite(ctx context.Context, indexGroup, indexOffset, readLength uint32, ...) ([]byte, error)
- func (c *Client) ReconnectAttempts() int
- func (c *Client) RefreshSymbols(ctx context.Context) error
- func (c *Client) RegisterType(typeInfo symbols.TypeInfo)
- func (c *Client) ReleaseSymbolHandle(ctx context.Context, handle uint32) error
- func (c *Client) SetStateCallback(callback ConnectionStateCallback)
- func (c *Client) Subscribe(ctx context.Context, opts NotificationOptions) (*Subscription, error)
- func (c *Client) SubscribeSymbol(ctx context.Context, symbolName string, opts SymbolNotificationOptions) (*Subscription, error)
- func (c *Client) UploadDataTypeTable(ctx context.Context) ([]byte, error)
- func (c *Client) UploadSymbolTable(ctx context.Context) ([]byte, error)
- func (c *Client) Write(ctx context.Context, indexGroup, indexOffset uint32, data []byte) error
- func (c *Client) WriteBool(ctx context.Context, symbolName string, value bool) error
- func (c *Client) WriteControl(ctx context.Context, adsState ads.ADSState, deviceState uint16, data []byte) error
- func (c *Client) WriteDate(ctx context.Context, symbolName string, value time.Time) error
- func (c *Client) WriteDateAndTime(ctx context.Context, symbolName string, value time.Time) error
- func (c *Client) WriteFloat32(ctx context.Context, symbolName string, value float32) error
- func (c *Client) WriteFloat64(ctx context.Context, symbolName string, value float64) error
- func (c *Client) WriteInt8(ctx context.Context, symbolName string, value int8) error
- func (c *Client) WriteInt16(ctx context.Context, symbolName string, value int16) error
- func (c *Client) WriteInt32(ctx context.Context, symbolName string, value int32) error
- func (c *Client) WriteInt64(ctx context.Context, symbolName string, value int64) error
- func (c *Client) WriteString(ctx context.Context, symbolName string, value string) error
- func (c *Client) WriteStructFieldBool(ctx context.Context, fieldPath string, value bool) errordeprecated
- func (c *Client) WriteStructFieldInt16(ctx context.Context, fieldPath string, value int16) errordeprecated
- func (c *Client) WriteStructFieldInt32(ctx context.Context, fieldPath string, value int32) errordeprecated
- func (c *Client) WriteStructFieldUint16(ctx context.Context, fieldPath string, value uint16) errordeprecated
- func (c *Client) WriteStructFieldUint32(ctx context.Context, fieldPath string, value uint32) errordeprecated
- func (c *Client) WriteStructFields(ctx context.Context, symbolName string, fieldValues map[string]interface{}) error
- func (c *Client) WriteSymbol(ctx context.Context, symbolName string, data []byte) error
- func (c *Client) WriteSymbolValue(ctx context.Context, symbolName string, value interface{}) error
- func (c *Client) WriteTime(ctx context.Context, symbolName string, value time.Duration) error
- func (c *Client) WriteTimeOfDay(ctx context.Context, symbolName string, value time.Duration) error
- func (c *Client) WriteUint8(ctx context.Context, symbolName string, value uint8) error
- func (c *Client) WriteUint16(ctx context.Context, symbolName string, value uint16) error
- func (c *Client) WriteUint32(ctx context.Context, symbolName string, value uint32) error
- func (c *Client) WriteUint64(ctx context.Context, symbolName string, value uint64) error
- func (c *Client) WriteWString(ctx context.Context, symbolName string, value string) error
- type ConnectionState
- type ConnectionStateCallback
- type DeviceInfo
- type DeviceState
- type ErrorCategory
- type InMemoryMetrics
- func (m *InMemoryMetrics) BytesReceived(bytes int64)
- func (m *InMemoryMetrics) BytesSent(bytes int64)
- func (m *InMemoryMetrics) ConnectionActive(active bool)
- func (m *InMemoryMetrics) ConnectionAttempts()
- func (m *InMemoryMetrics) ConnectionFailures()
- func (m *InMemoryMetrics) ConnectionSuccesses()
- func (m *InMemoryMetrics) ErrorOccurred(category ErrorCategory, operation string)
- func (m *InMemoryMetrics) HealthCheckCompleted(success bool)
- func (m *InMemoryMetrics) HealthCheckStarted()
- func (m *InMemoryMetrics) NotificationDropped()
- func (m *InMemoryMetrics) NotificationReceived()
- func (m *InMemoryMetrics) OperationCompleted(operation string, duration time.Duration, err error)
- func (m *InMemoryMetrics) OperationStarted(operation string)
- func (m *InMemoryMetrics) Reconnections()
- func (m *InMemoryMetrics) Snapshot() MetricsSnapshot
- func (m *InMemoryMetrics) SubscriptionsActive(count int)
- type Logger
- type Metrics
- type MetricsSnapshot
- type Notification
- type NotificationOptions
- type Option
- func WithAMSNetID(netID ams.NetID) Option
- func WithAMSPort(port ams.Port) Option
- func WithAutoReconnect(enabled bool) Option
- func WithHealthCheck(period time.Duration) Option
- func WithLogger(logger Logger) Option
- func WithMaxReconnectDelay(delay time.Duration) Option
- func WithMetrics(metrics Metrics) Option
- func WithSourceNetID(netID ams.NetID) Option
- func WithSourcePort(port ams.Port) Option
- func WithStateCallback(callback ConnectionStateCallback) Option
- func WithTarget(address string) Option
- func WithTimeout(timeout time.Duration) Option
- type Subscription
- type SymbolNotificationOptions
Constants ¶
const ( StateConnecting = transport.StateConnecting StateConnected = transport.StateConnected StateDisconnecting = transport.StateDisconnecting StateClosed = transport.StateClosed StateError = transport.StateError )
Connection state constants
const ( // VersionMajor is the major version number. VersionMajor = 0 // VersionMinor is the minor version number. VersionMinor = 2 // VersionPatch is the patch version number. VersionPatch = 2 // VersionPrerelease is the pre-release version string (e.g., "alpha", "beta", "rc.1"). // Empty string for stable releases. VersionPrerelease = "" )
Variables ¶
This section is empty.
Functions ¶
func ContextWithLogFields ¶
ContextWithLogFields adds log fields to a context that will be automatically included in log messages when using LoggerFromContext.
func NewADSError ¶
NewADSError creates a classified ADS error.
func NewNetworkError ¶
NewNetworkError creates a classified network error.
func NewStateError ¶
NewStateError creates a classified state error.
func NewValidationError ¶
NewValidationError creates a classified validation error.
Types ¶
type BuildInfo ¶
type BuildInfo struct {
Version string
GitCommit string
GitTag string
BuildTime string
GoVersion string
Dirty bool
}
BuildInfo contains version and build information.
func GetBuildInfo ¶
func GetBuildInfo() BuildInfo
GetBuildInfo returns detailed build information including version and VCS details. When built with build info, it includes git commit hash and other metadata.
type ClassifiedError ¶
type ClassifiedError struct {
Category ErrorCategory
Operation string // The operation that failed (e.g., "read", "write", "connect")
Err error
Retryable bool // Whether the operation can be retried
ADSError *ads.Error
SymbolName string // Optional: the symbol name if relevant
IndexGroup *uint32 // Optional: index group if relevant
IndexOffset *uint32 // Optional: index offset if relevant
}
ClassifiedError wraps an error with additional classification metadata.
func ClassifyError ¶
func ClassifyError(err error, operation string) *ClassifiedError
ClassifyError attempts to classify an error into a category.
func (*ClassifiedError) Error ¶
func (e *ClassifiedError) Error() string
func (*ClassifiedError) IsRetryable ¶
func (e *ClassifiedError) IsRetryable() bool
IsRetryable returns whether the error indicates a retryable condition.
func (*ClassifiedError) Unwrap ¶
func (e *ClassifiedError) Unwrap() error
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents an ADS client connection.
func (*Client) FindSymbols ¶
FindSymbols searches for symbols matching the pattern (case-insensitive substring).
func (*Client) GetDataTypeUploadInfo ¶
func (c *Client) GetDataTypeUploadInfo(ctx context.Context) (dataTypeCount, dataTypeSize uint32, err error)
GetDataTypeUploadInfo retrieves information about the data type table.
func (*Client) GetRegisteredType ¶
GetRegisteredType retrieves a registered type definition.
func (*Client) GetSymbolHandle ¶
GetSymbolHandle retrieves a handle for the given symbol name. The handle can be used with Read/Write operations using the handle's IndexGroup/IndexOffset. Handles should be released with ReleaseSymbolHandle when no longer needed.
func (*Client) GetSymbolUploadInfo ¶
func (c *Client) GetSymbolUploadInfo(ctx context.Context) (symbolCount, symbolLength uint32, err error)
GetSymbolUploadInfo retrieves information about the PLC symbol table. Returns the number of symbols and total size of symbol data.
func (*Client) ListRegisteredTypes ¶
ListRegisteredTypes returns all registered type names.
func (*Client) ListSymbols ¶
ListSymbols returns all symbols in the cache. Calls RefreshSymbols automatically if symbols not loaded.
func (*Client) ReadDate ¶
ReadDate reads a DATE value from a symbol and returns it as time.Time. DATE is stored as a 32-bit unsigned integer representing seconds since 1970-01-01.
func (*Client) ReadDateAndTime ¶
ReadDateAndTime reads a DATE_AND_TIME value from a symbol and returns it as time.Time. DATE_AND_TIME is stored as a 32-bit unsigned integer representing seconds since 1970-01-01.
func (*Client) ReadDeviceInfo ¶
func (c *Client) ReadDeviceInfo(ctx context.Context) (*DeviceInfo, error)
ReadDeviceInfo reads the device name and version.
func (*Client) ReadFloat32 ¶
ReadFloat32 reads a REAL/FLOAT value from a symbol by name.
func (*Client) ReadFloat64 ¶
ReadFloat64 reads an LREAL/DOUBLE value from a symbol by name.
func (*Client) ReadMultipleSymbolValues ¶ added in v0.2.2
func (c *Client) ReadMultipleSymbolValues(ctx context.Context, symbolNames ...string) (map[string]interface{}, error)
ReadMultipleSymbolValues reads multiple symbols in individual requests and returns a map of results. TODO: Future enhancement - use SumCommand (0xF080) for batched reads in single request.
func (*Client) ReadState ¶
func (c *Client) ReadState(ctx context.Context) (*DeviceState, error)
ReadState reads the ADS and device state.
func (*Client) ReadString ¶
ReadString reads a STRING value from a symbol by name. TwinCAT strings are null-terminated and may have a fixed buffer size. Returns the string up to the first null byte.
func (*Client) ReadStructAsMap
deprecated
func (c *Client) ReadStructAsMap(ctx context.Context, symbolName string) (map[string]interface{}, error)
ReadStructAsMap reads a struct symbol and returns its fields as a map. The map keys are field names and values are interface{} containing the parsed values. If the struct type is registered via RegisterType, it will use that information for parsing.
Deprecated: Use ReadSymbolValue instead, which automatically detects and parses all types. ReadSymbolValue provides the same functionality with better ergonomics and no manual type registration needed.
func (*Client) ReadSymbol ¶
ReadSymbol reads data from a PLC symbol by name. Supports array element access using bracket notation: "MAIN.myArray[5]" Automatically loads symbol table on first call.
func (*Client) ReadSymbolValue ¶ added in v0.2.2
ReadSymbolValue automatically detects the type of a symbol and returns its parsed value. For basic types (INT, REAL, BOOL, etc.), it returns the appropriate Go primitive type. For arrays, it returns []interface{} with all elements. For structs, it returns map[string]interface{} with all fields. This method uses the symbol table to determine the type and reads/parses in one call.
func (*Client) ReadTime ¶
ReadTime reads a TIME value from a symbol and returns it as time.Duration. TIME is stored as a 32-bit signed integer representing milliseconds.
func (*Client) ReadTimeOfDay ¶
ReadTimeOfDay reads a TIME_OF_DAY value from a symbol and returns it as time.Duration. TIME_OF_DAY is stored as a 32-bit unsigned integer representing milliseconds since midnight.
func (*Client) ReadUint16 ¶
ReadUint16 reads a UINT16/UINT/WORD value from a symbol by name.
func (*Client) ReadUint32 ¶
ReadUint32 reads a UINT32/UDINT/DWORD value from a symbol by name.
func (*Client) ReadUint64 ¶
ReadUint64 reads a UINT64/ULINT/LWORD value from a symbol by name.
func (*Client) ReadWString ¶
ReadWString reads a WSTRING (wide string, UTF-16LE) value from a symbol. Returns the string as UTF-8.
func (*Client) ReadWrite ¶
func (c *Client) ReadWrite(ctx context.Context, indexGroup, indexOffset, readLength uint32, writeData []byte) ([]byte, error)
ReadWrite writes and reads data in a single operation.
func (*Client) ReconnectAttempts ¶
ReconnectAttempts returns the current number of reconnection attempts. Returns 0 if connected or auto-reconnect is disabled.
func (*Client) RefreshSymbols ¶
RefreshSymbols downloads and parses the symbol table from the PLC. This method should be called before using symbol-based operations. It can be called multiple times to refresh the cache if the PLC program changes.
func (*Client) RegisterType ¶
RegisterType registers a custom type definition for automatic struct parsing. This allows ReadStructAsMap to automatically parse structs based on registered type information.
func (*Client) ReleaseSymbolHandle ¶
ReleaseSymbolHandle releases a previously acquired symbol handle.
func (*Client) SetStateCallback ¶
func (c *Client) SetStateCallback(callback ConnectionStateCallback)
SetStateCallback sets or updates the connection state callback.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(ctx context.Context, opts NotificationOptions) (*Subscription, error)
Subscribe creates a new notification subscription. The returned Subscription will deliver notifications via its Notifications() channel. Call Close() on the Subscription when done to clean up resources.
func (*Client) SubscribeSymbol ¶
func (c *Client) SubscribeSymbol(ctx context.Context, symbolName string, opts SymbolNotificationOptions) (*Subscription, error)
SubscribeSymbol creates a notification subscription using a symbol name. This is a convenience method that automatically looks up the symbol's index group, offset, and length. The returned Subscription will deliver notifications via its Notifications() channel. Call Close() on the Subscription when done.
func (*Client) UploadDataTypeTable ¶
UploadDataTypeTable retrieves the complete data type table from the PLC.
func (*Client) UploadSymbolTable ¶
UploadSymbolTable downloads the complete symbol table from the PLC. The returned data is in raw TwinCAT format and needs parsing.
func (*Client) WriteControl ¶
func (c *Client) WriteControl(ctx context.Context, adsState ads.ADSState, deviceState uint16, data []byte) error
WriteControl changes the ADS state of the device. This can be used to start, stop, reset the PLC, or perform other state transitions. The data parameter is optional and can be nil for most operations.
func (*Client) WriteDate ¶
WriteDate writes a time.Time value to a DATE symbol. DATE is stored as a 32-bit unsigned integer representing seconds since 1970-01-01.
func (*Client) WriteDateAndTime ¶
WriteDateAndTime writes a time.Time value to a DATE_AND_TIME symbol. DATE_AND_TIME is stored as a 32-bit unsigned integer representing seconds since 1970-01-01.
func (*Client) WriteFloat32 ¶
WriteFloat32 writes a REAL/FLOAT value to a symbol by name.
func (*Client) WriteFloat64 ¶
WriteFloat64 writes an LREAL/DOUBLE value to a symbol by name.
func (*Client) WriteInt16 ¶
WriteInt16 writes an INT16/INT value to a symbol by name.
func (*Client) WriteInt32 ¶
WriteInt32 writes an INT32/DINT value to a symbol by name.
func (*Client) WriteInt64 ¶
WriteInt64 writes an INT64/LINT value to a symbol by name.
func (*Client) WriteString ¶
WriteString writes a STRING value to a symbol by name. TwinCAT strings have a fixed buffer size. The value is null-terminated and padded with zeros to fill the buffer.
func (*Client) WriteStructFields ¶ added in v0.2.2
func (c *Client) WriteStructFields(ctx context.Context, symbolName string, fieldValues map[string]interface{}) error
WriteStructFields writes multiple fields to a struct by reading the entire struct, modifying the specified fields at their byte offsets, and writing the struct back. This is useful when individual field symbols aren't exported in the PLC.
fieldValues is a map where keys are field names and values are the Go values to write. The function automatically encodes each value based on its type information from the PLC.
Example:
err := client.WriteStructFields(ctx, "MAIN.myStruct", map[string]interface{}{
"temperature": float32(25.5),
"enabled": true,
"counter": int16(42),
})
func (*Client) WriteSymbol ¶
WriteSymbol writes data to a PLC symbol by name. Supports array element access using bracket notation: "MAIN.myArray[5]" Automatically loads symbol table on first call.
func (*Client) WriteSymbolValue ¶ added in v0.2.2
WriteSymbolValue automatically encodes and writes a value to a symbol based on its type. Supports basic types (int, float, bool, string), time.Duration, and time.Time. For complex types (structs, arrays), use the specific Write methods or WriteSymbol with raw bytes.
func (*Client) WriteTime ¶
WriteTime writes a time.Duration value to a TIME symbol. TIME is stored as a 32-bit signed integer representing milliseconds.
func (*Client) WriteTimeOfDay ¶
WriteTimeOfDay writes a time.Duration value to a TIME_OF_DAY symbol. TIME_OF_DAY is stored as a 32-bit unsigned integer representing milliseconds since midnight.
func (*Client) WriteUint8 ¶
WriteUint8 writes a UINT8/USINT/BYTE value to a symbol by name.
func (*Client) WriteUint16 ¶
WriteUint16 writes a UINT16/UINT/WORD value to a symbol by name.
func (*Client) WriteUint32 ¶
WriteUint32 writes a UINT32/UDINT/DWORD value to a symbol by name.
func (*Client) WriteUint64 ¶
WriteUint64 writes a UINT64/ULINT/LWORD value to a symbol by name.
func (*Client) WriteWString ¶
WriteWString writes a string value to a WSTRING symbol. The string is converted from UTF-8 to UTF-16LE. WSTRING has a fixed buffer size, and the value is null-terminated and padded with zeros.
type ConnectionState ¶
type ConnectionState = transport.ConnectionState
ConnectionState represents the state of the client connection.
type ConnectionStateCallback ¶
type ConnectionStateCallback func(oldState, newState ConnectionState, err error)
ConnectionStateCallback is called when connection state changes.
type DeviceInfo ¶
DeviceInfo represents device information returned by ReadDeviceInfo.
type DeviceState ¶
DeviceState represents the state of an ADS device.
type ErrorCategory ¶
type ErrorCategory int
ErrorCategory represents the type of error for better error handling.
const ( // ErrorCategoryUnknown represents an unclassified error. ErrorCategoryUnknown ErrorCategory = iota // ErrorCategoryNetwork represents network-level errors (connection, timeout, etc.). ErrorCategoryNetwork // ErrorCategoryProtocol represents AMS/ADS protocol errors. ErrorCategoryProtocol // ErrorCategoryADS represents ADS device errors returned by the PLC. ErrorCategoryADS // ErrorCategoryValidation represents input validation errors. ErrorCategoryValidation // ErrorCategoryConfiguration represents configuration errors. ErrorCategoryConfiguration // ErrorCategoryTimeout represents timeout errors. ErrorCategoryTimeout // ErrorCategoryState represents state-related errors (e.g., client closed). ErrorCategoryState )
func (ErrorCategory) String ¶
func (c ErrorCategory) String() string
type InMemoryMetrics ¶
type InMemoryMetrics struct {
// Connection metrics
ConnectionAttemptsCount atomic.Int64
ConnectionSuccessesCount atomic.Int64
ConnectionFailuresCount atomic.Int64
ConnectionActiveState atomic.Bool
ReconnectionsCount atomic.Int64
// Operation metrics
OperationCounts map[string]*atomic.Int64
OperationDurations map[string][]time.Duration
OperationErrors map[string]*atomic.Int64
// Data transfer metrics
BytesSentCount atomic.Int64
BytesReceivedCount atomic.Int64
// Notification metrics
NotificationsReceivedCount atomic.Int64
NotificationsDroppedCount atomic.Int64
SubscriptionsActiveCount atomic.Int64
// Error metrics
ErrorsByCategory map[ErrorCategory]*atomic.Int64
ErrorsByOperation map[string]*atomic.Int64
// Health metrics
HealthChecksStartedCount atomic.Int64
HealthChecksSuccessCount atomic.Int64
HealthChecksFailureCount atomic.Int64
// contains filtered or unexported fields
}
InMemoryMetrics provides a simple in-memory metrics collector for testing and debugging.
func NewInMemoryMetrics ¶
func NewInMemoryMetrics() *InMemoryMetrics
NewInMemoryMetrics creates a new in-memory metrics collector.
func (*InMemoryMetrics) BytesReceived ¶
func (m *InMemoryMetrics) BytesReceived(bytes int64)
func (*InMemoryMetrics) BytesSent ¶
func (m *InMemoryMetrics) BytesSent(bytes int64)
func (*InMemoryMetrics) ConnectionActive ¶
func (m *InMemoryMetrics) ConnectionActive(active bool)
func (*InMemoryMetrics) ConnectionAttempts ¶
func (m *InMemoryMetrics) ConnectionAttempts()
func (*InMemoryMetrics) ConnectionFailures ¶
func (m *InMemoryMetrics) ConnectionFailures()
func (*InMemoryMetrics) ConnectionSuccesses ¶
func (m *InMemoryMetrics) ConnectionSuccesses()
func (*InMemoryMetrics) ErrorOccurred ¶
func (m *InMemoryMetrics) ErrorOccurred(category ErrorCategory, operation string)
func (*InMemoryMetrics) HealthCheckCompleted ¶
func (m *InMemoryMetrics) HealthCheckCompleted(success bool)
func (*InMemoryMetrics) HealthCheckStarted ¶
func (m *InMemoryMetrics) HealthCheckStarted()
func (*InMemoryMetrics) NotificationDropped ¶
func (m *InMemoryMetrics) NotificationDropped()
func (*InMemoryMetrics) NotificationReceived ¶
func (m *InMemoryMetrics) NotificationReceived()
func (*InMemoryMetrics) OperationCompleted ¶
func (m *InMemoryMetrics) OperationCompleted(operation string, duration time.Duration, err error)
func (*InMemoryMetrics) OperationStarted ¶
func (m *InMemoryMetrics) OperationStarted(operation string)
func (*InMemoryMetrics) Reconnections ¶
func (m *InMemoryMetrics) Reconnections()
func (*InMemoryMetrics) Snapshot ¶
func (m *InMemoryMetrics) Snapshot() MetricsSnapshot
Snapshot returns a copy of current metrics for reporting.
func (*InMemoryMetrics) SubscriptionsActive ¶
func (m *InMemoryMetrics) SubscriptionsActive(count int)
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
With(args ...any) Logger
}
Logger defines the interface for structured logging in goadstc. It follows the standard slog.Logger interface for compatibility.
var ( // DefaultLogger is a no-op logger to minimize overhead when logging is not configured. DefaultLogger Logger = &noopLogger{} )
func LoggerFromContext ¶
LoggerFromContext returns a logger with context fields attached.
func NewDefaultLogger ¶
func NewDefaultLogger() Logger
NewDefaultLogger creates a basic JSON logger writing to stderr.
func NewSlogLogger ¶
NewSlogLogger creates a Logger from a slog.Logger.
type Metrics ¶
type Metrics interface {
// Connection metrics
ConnectionAttempts()
ConnectionSuccesses()
ConnectionFailures()
ConnectionActive(active bool)
Reconnections()
// Operation metrics
OperationStarted(operation string)
OperationCompleted(operation string, duration time.Duration, err error)
// Data transfer metrics
BytesSent(bytes int64)
BytesReceived(bytes int64)
// Notification metrics
NotificationReceived()
NotificationDropped()
SubscriptionsActive(count int)
// Error metrics
ErrorOccurred(category ErrorCategory, operation string)
// Health metrics
HealthCheckStarted()
HealthCheckCompleted(success bool)
}
Metrics defines the interface for collecting operational metrics. Implementations can export metrics to various backends (Prometheus, StatsD, etc.).
var ( // DefaultMetrics is a no-op metrics collector to minimize overhead when metrics are not configured. DefaultMetrics Metrics = &noopMetrics{} )
type MetricsSnapshot ¶
type MetricsSnapshot struct {
ConnectionAttempts int64
ConnectionSuccesses int64
ConnectionFailures int64
ConnectionActive bool
Reconnections int64
BytesSent int64
BytesReceived int64
NotificationsReceived int64
NotificationsDropped int64
SubscriptionsActive int64
HealthChecksStarted int64
HealthChecksSuccess int64
HealthChecksFailure int64
OperationCounts map[string]int64
OperationErrors map[string]int64
ErrorsByCategory map[ErrorCategory]int64
ErrorsByOperation map[string]int64
}
MetricsSnapshot represents a point-in-time snapshot of metrics.
type Notification ¶
Notification represents a single notification event from the PLC.
type NotificationOptions ¶
type NotificationOptions struct {
IndexGroup uint32
IndexOffset uint32
Length uint32
TransmissionMode ads.TransmissionMode
MaxDelay time.Duration // Maximum delay before notification is sent
CycleTime time.Duration // Cycle time for cyclic notifications
}
NotificationOptions configures a notification subscription.
type Option ¶
type Option func(*clientConfig) error
Option is a functional option for configuring a Client.
func WithAMSNetID ¶
WithAMSNetID sets the target AMS NetID (required).
func WithAMSPort ¶
WithAMSPort sets the target AMS port (optional, defaults to 851).
func WithAutoReconnect ¶
WithAutoReconnect enables automatic reconnection on connection loss (optional). When enabled, the client will automatically attempt to reconnect with exponential backoff. Subscriptions will be re-established after successful reconnection.
func WithHealthCheck ¶
WithHealthCheck enables periodic health checks (optional). The client will periodically send a ReadState request to verify connection. If health check fails and auto-reconnect is enabled, reconnection will be triggered.
func WithLogger ¶
WithLogger returns a new option that sets the logger for the client.
func WithMaxReconnectDelay ¶
WithMaxReconnectDelay sets the maximum delay between reconnection attempts (optional). Default is 60 seconds. Only applies when auto-reconnect is enabled.
func WithMetrics ¶
WithMetrics returns a new option that sets the metrics collector for the client.
func WithSourceNetID ¶
WithSourceNetID sets the source AMS NetID (optional).
func WithSourcePort ¶
WithSourcePort sets the source AMS port (optional).
func WithStateCallback ¶
func WithStateCallback(callback ConnectionStateCallback) Option
WithStateCallback sets a callback for connection state changes (optional). The callback is invoked whenever the connection state changes (connected, disconnected, etc.).
func WithTarget ¶
WithTarget sets the target TCP address (required).
func WithTimeout ¶
WithTimeout sets the timeout for requests (optional).
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription represents an active ADS notification subscription.
func (*Subscription) Close ¶
func (s *Subscription) Close() error
Close unsubscribes from the notification and closes the notification channel. It's safe to call Close multiple times.
func (*Subscription) Handle ¶
func (s *Subscription) Handle() uint32
Handle returns the notification handle assigned by the PLC.
func (*Subscription) Notifications ¶
func (s *Subscription) Notifications() <-chan Notification
Notifications returns the channel for receiving notifications. The channel is closed when the subscription is closed.
type SymbolNotificationOptions ¶
type SymbolNotificationOptions struct {
TransmissionMode ads.TransmissionMode
MaxDelay time.Duration // Maximum delay before notification is sent
CycleTime time.Duration // Cycle time for cyclic notifications
}
SymbolNotificationOptions configures a symbol-based notification subscription.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package docs Code generated by swaggo/swag.
|
Package docs Code generated by swaggo/swag. |
|
examples
|
|
|
arrays
command
|
|
|
autoreconnect
command
|
|
|
autotype
command
|
|
|
comprehensive
command
|
|
|
control
command
|
|
|
field-symbols
command
|
|
|
middleware-server
command
|
|
|
notifications
command
|
|
|
observability
command
|
|
|
struct-manipulation
command
|
|
|
structs
command
|
|
|
symbol-notifications
command
|
|
|
symbols
command
|
|
|
timedate
command
|
|
|
typesafe
command
|
|
|
version
command
|
|
|
internal
|
|
|
ads
Package ads implements ADS (Automation Device Specification) command handling.
|
Package ads implements ADS (Automation Device Specification) command handling. |
|
ams
Package ams implements AMS (Automation Message Specification) protocol handling.
|
Package ams implements AMS (Automation Message Specification) protocol handling. |
|
symbols
Package symbols implements symbol table parsing and caching for TwinCAT 3.
|
Package symbols implements symbol table parsing and caching for TwinCAT 3. |
|
transport
Package transport implements TCP transport for AMS/ADS communication.
|
Package transport implements TCP transport for AMS/ADS communication. |