Documentation
¶
Overview ¶
Package n2k is a standalone Go toolkit for NMEA 2000 marine networks. It reads and writes messages from CAN hardware, USB-CAN adapters, network gateways, and capture/replay sources, decoding PGNs into strongly typed Go structs from package pgn.
Index ¶
- Constants
- Variables
- func EncodeActisenseCANASCII(frame can.Frame, direction Direction, transportTimestamp time.Duration) ([]byte, error)
- func EncodeActisenseN2KASCII(pgn uint32, priority, source, destination uint8, payload []byte, ...) ([]byte, error)
- func Observe(ctx context.Context, opts ...Option) iter.Seq2[Observation, error]
- func Receive(ctx context.Context, opts ...Option) iter.Seq2[pgn.Message, error]
- func Request[T pgn.Message](ctx context.Context, c *Client, target uint8) (T, error)
- type ActisenseBEMOrigin
- type ActisenseBEMPath
- type ActisenseBEMResponse
- type ActisenseByteStream
- type ActisenseCANConfig
- type ActisenseCANInfoField
- type ActisenseDevice
- type ActisenseDeviceCapabilities
- type ActisenseDeviceError
- type ActisenseDiagnostic
- type ActisenseDiagnosticKind
- type ActisenseEBLTrace
- type ActisenseErrorReport
- type ActisenseGatewaySession
- func NewActisenseGatewaySession(ctx context.Context, endpoint string, open ActisenseOpenFunc, ...) (*ActisenseGatewaySession, error)
- func NewActisenseSerialSession(ctx context.Context, port string, serialConfig ActisenseSerialConfig, ...) (*ActisenseGatewaySession, error)
- func NewActisenseTCPSession(ctx context.Context, address string, options ...ActisenseSessionOption) (*ActisenseGatewaySession, error)
- func (s *ActisenseGatewaySession) ActisenseRemoteDevice(source uint8, options ...ActisenseRemoteOption) (*ActisenseRemoteDevice, error)
- func (s *ActisenseGatewaySession) Close() error
- func (s *ActisenseGatewaySession) ConfigureTransmitPGNs(ctx context.Context, configurations []ActisenseTxPGNConfiguration) error
- func (s *ActisenseGatewaySession) Diagnostics() iter.Seq2[ActisenseDiagnostic, error]
- func (s *ActisenseGatewaySession) Err() error
- func (s *ActisenseGatewaySession) Observations() iter.Seq2[Observation, error]
- func (s *ActisenseGatewaySession) SendBST(ctx context.Context, bst []byte) error
- func (s *ActisenseGatewaySession) SendPGN(ctx context.Context, message pgn.Message) error
- func (s *ActisenseGatewaySession) SendRaw(ctx context.Context, wire []byte) error
- func (s *ActisenseGatewaySession) SendRawPGN(ctx context.Context, pgnNumber uint32, priority, destination uint8, ...) error
- func (s *ActisenseGatewaySession) Status() ActisenseSessionStatus
- type ActisenseHardwareProtocol
- type ActisenseModeError
- type ActisenseModelID
- type ActisenseNegativeAck
- type ActisenseNegativeAckError
- type ActisenseOpenFunc
- type ActisenseOperatingMode
- type ActisensePGNEnableFlag
- type ActisensePGNListParameters
- type ActisensePGNListSelector
- type ActisenseParity
- type ActisensePortBaudrate
- type ActisensePortDuplicateDelete
- type ActisensePortInventory
- type ActisensePortInventoryEntry
- type ActisensePortMedia
- type ActisensePortPCode
- type ActisenseProductInfo
- type ActisenseProprietaryPGNList
- type ActisenseProtocolMetrics
- type ActisenseRemoteDevice
- type ActisenseRemoteOption
- type ActisenseRxPGNEnableList
- type ActisenseRxPGNEnableListF1
- type ActisenseRxPGNListEntry
- type ActisenseRxPGNListF1Entry
- type ActisenseRxPGNState
- type ActisenseSerialConfig
- type ActisenseSerialOption
- type ActisenseSessionMetrics
- type ActisenseSessionOption
- func WithActisenseCommandTimeout(timeout time.Duration) ActisenseSessionOption
- func WithActisenseMultiReplyInactivity(timeout time.Duration) ActisenseSessionOption
- func WithActisensePreserveOperatingMode() ActisenseSessionOption
- func WithActisenseSessionBuffer(size int) ActisenseSessionOption
- func WithActisenseSessionLogger(logger *slog.Logger) ActisenseSessionOption
- func WithActisenseSessionMode(mode ActisenseOperatingMode) ActisenseSessionOption
- func WithActisenseSessionReadyTimeout(timeout time.Duration) ActisenseSessionOption
- func WithActisenseSessionReconnect(policy ReconnectPolicy) ActisenseSessionOption
- func WithActisenseWireTrace(trace *ActisenseEBLTrace) ActisenseSessionOption
- type ActisenseSessionStatus
- type ActisenseStartupStatus
- type ActisenseStopBits
- type ActisenseSupportedPGN
- type ActisenseSupportedPGNList
- type ActisenseSystemStatus
- type ActisenseTxPGNConfiguration
- type ActisenseTxPGNEnableList
- type ActisenseTxPGNEnableListF1
- type ActisenseTxPGNListEntry
- type ActisenseTxPGNListF1Entry
- type ActisenseTxPGNState
- type Bus
- type Client
- func (c *Client) ActisenseRemoteDevice(source uint8, options ...ActisenseRemoteOption) (*ActisenseRemoteDevice, error)
- func (c *Client) Broadcast(interval time.Duration, provide func(context.Context) pgn.Message) (stop func(), err error)
- func (c *Client) BroadcastPGN(pgnNum uint32, interval time.Duration, ...) (stop func(), err error)
- func (c *Client) Close() error
- func (c *Client) DeviceAt(source uint8) (Device, bool)
- func (c *Client) Devices() []Device
- func (c *Client) Err() error
- func (c *Client) Observations() iter.Seq2[Observation, error]
- func (c *Client) Receive() iter.Seq2[pgn.Message, error]
- func (c *Client) Scanner() *Scanner
- func (c *Client) Status() ClientStatus
- func (c *Client) Write(msg pgn.Message) *WriteResult
- func (c *Client) WriteContext(ctx context.Context, msg pgn.Message) *WriteResult
- func (c *Client) WrittenFrames() []can.Frame
- type ClientStatus
- type ConfigInfo
- type ConnectionLifecycleBus
- type ContextBus
- type ContextMessageWriter
- type Device
- type DeviceName
- type Direction
- type EBLWriter
- func (w *EBLWriter) Err() error
- func (w *EBLWriter) Metrics() EBLWriterMetrics
- func (w *EBLWriter) WriteDescription(description string) error
- func (w *EBLWriter) WriteRawBST(timestamp time.Time, direction Direction, rawBST []byte) error
- func (w *EBLWriter) WriteRawBytes(timestamp time.Time, direction Direction, data []byte) error
- type EBLWriterMetrics
- type EBLWriterOption
- type FileOption
- type MessageWriter
- type Observation
- type ObservationBus
- type ObservationKind
- type Option
- func ActisenseSerial(port string, options ...ActisenseSerialOption) Option
- func ActisenseTCP(addr string) Option
- func CAN(iface string) Option
- func EBL(path string, opts ...FileOption) Option
- func File(path string, opts ...FileOption) Option
- func Filter(expr string) Option
- func IncludeUnknown() Option
- func Replay(frames []can.Frame) Option
- func ReplayObservations(observations []Observation) Option
- func Serial(port string, format StreamFormat, options ...ActisenseSerialOption) Option
- func TCP(addr string, format StreamFormat) Option
- func UDP(listenAddr string, format StreamFormat) Option
- func USB(port string) Option
- func WithBus(bus Bus) Option
- func WithClaimTimeout(d time.Duration) Option
- func WithConfigInfo(ci ConfigInfo) Option
- func WithHeartbeatInterval(d time.Duration) Option
- func WithLogger(l *slog.Logger) Option
- func WithName(name DeviceName) Option
- func WithPreferredAddress(addr uint8) Option
- func WithProductInfo(p ProductInfo) Option
- func WithReadyTimeout(d time.Duration) Option
- func WithReceiveBuffer(size int) Option
- func WithReconnect(policy ReconnectPolicy) Option
- func WithSourceAddress(addr uint8) Option
- func WithWriteQueue(size int) Option
- func WithWriteTimeout(timeout time.Duration) Option
- func YachtDevicesTCP(addr string) Option
- func YachtDevicesUDP(listenAddr string) Option
- type ProductInfo
- type ReadyBus
- type ReconnectPolicy
- type Scanner
- type SerialDevice
- type StreamFormat
- type WriteError
- type WriteResult
Examples ¶
Constants ¶
const ( ActisenseModeUndefined = actisense.ModeUndefined ActisenseModeTransferNormal = actisense.ModeTransferNormal ActisenseModeTransferReceiveAll = actisense.ModeTransferReceiveAll ActisenseModeTransferLegacyRaw = actisense.ModeTransferLegacyRaw ActisenseModeConvertNormal = actisense.ModeConvertNormal ActisenseModeCANPacket = actisense.ModeCANPacket ActisenseModeCANPacketASCII = actisense.ModeCANPacketASCII ActisenseModeBuffer1 = actisense.ModeBuffer1 ActisenseModeBuffer2 = actisense.ModeBuffer2 ActisenseModeBuffer3 = actisense.ModeBuffer3 ActisenseModeAutoswitchDirect = actisense.ModeAutoswitchDirect ActisenseModeAutoswitchSmart = actisense.ModeAutoswitchSmart ActisenseModeCombineSlow = actisense.ModeCombineSlow ActisenseModeCombineFast = actisense.ModeCombineFast ActisenseModeTest1 = actisense.ModeTest1 ActisenseModeNSI1 = actisense.ModeNSI1 ActisenseModeNormal = actisense.ModeNormal ActisenseModePredefined1 = actisense.ModePredefined1 ActisenseModePredefined2 = actisense.ModePredefined2 ActisenseModeUser1 = actisense.ModeUser1 ActisenseModeUser2 = actisense.ModeUser2 ActisenseModeUser3 = actisense.ModeUser3 ActisenseModeUser4 = actisense.ModeUser4 ActisenseModeUser5 = actisense.ModeUser5 ActisenseModeNull = actisense.ModeNull )
const ( ActisenseBEMLocal = actisense.BEMPathLocal ActisenseBEMRemote = actisense.BEMPathRemote )
const ( ActisenseModelUnknown = actisense.ModelUnknown ActisenseModelNGT1 = actisense.ModelNGT1 ActisenseModelNGT1USB = actisense.ModelNGT1USB ActisenseModelNGW1 = actisense.ModelNGW1 ActisenseModelEMU1 = actisense.ModelEMU1 ActisenseModelPRONDC1 = actisense.ModelPRONDC1 ActisenseModelWGX1 = actisense.ModelWGX1 ActisenseModelNGX1 = actisense.ModelNGX1 )
const ( ActisenseHardwareSerialNMEA0183 = actisense.HardwareSerialNMEA0183 ActisenseHardwareSerialBST = actisense.HardwareSerialBST ActisenseHardwareCANNMEA2000 = actisense.HardwareCANNMEA2000 ActisenseHardwareCANJ1939 = actisense.HardwareCANJ1939 ActisenseHardwareEthernetBST = actisense.HardwareEthernetBST ActisenseHardwareEthernetNMEA0183 = actisense.HardwareEthernetNMEA0183 ActisenseHardwareEthernetOneNet = actisense.HardwareEthernetOneNet ActisensePortMediaCAN = actisense.PortMediaCAN ActisensePortMediaUART = actisense.PortMediaUART ActisensePortMediaUSB = actisense.PortMediaUSB ActisensePortMediaBLE = actisense.PortMediaBLE ActisensePortMediaWiFi = actisense.PortMediaWiFi ActisensePortMediaEthernet = actisense.PortMediaEthernet ActisensePortMediaIPStream = actisense.PortMediaIPStream ActisensePortMediaUnknown = actisense.PortMediaUnknown ActisensePortIndexNone = actisense.PortIndexNone ActisenseBaudRateNoChange = actisense.BaudRateNoChange ActisenseBaudRateDefault = actisense.BaudRateDefault ActisenseBaudRateAdoptAlternate = actisense.BaudRateAdoptAlternate ActisensePortPCodeOff = actisense.PortPCodeOff ActisensePortPCodeOn = actisense.PortPCodeOn ActisensePortPCodeNoChange = actisense.PortPCodeNoChange ActisenseCANInfoInstallationDescription1 = actisense.CANInfoInstallationDescription1 ActisenseCANInfoInstallationDescription2 = actisense.CANInfoInstallationDescription2 ActisenseCANInfoManufacturerInformation = actisense.CANInfoManufacturerInformation )
const ( ActisensePortDuplicateDeleteOff = actisense.PortDuplicateDeleteOff ActisensePortDuplicateDeleteOn = actisense.PortDuplicateDeleteOn ActisensePortDuplicateDeleteNoChange = actisense.PortDuplicateDeleteNoChange )
const ( ActisensePGNDisabled = actisense.PGNDisabled ActisensePGNEnabled = actisense.PGNEnabled ActisensePGNRespondMode = actisense.PGNRespondMode ActisenseRxPGNMaskPGN = actisense.RxPGNMaskPGN ActisenseRxPGNMaskPDUFormat = actisense.RxPGNMaskPDUFormat ActisenseRxPGNMaskPDUNibble = actisense.RxPGNMaskPDUNibble ActisenseRxPGNMaskDataPage = actisense.RxPGNMaskDataPage ActisenseRxPGNMaskDefault = actisense.RxPGNMaskDefault ActisenseRxPGNMaskNoChange = actisense.RxPGNMaskNoChange ActisenseTxPGNRateNoChange = actisense.TxPGNRateNoChange ActisenseTxPGNRateEvent = actisense.TxPGNRateEvent ActisensePGNListRx = actisense.PGNListRx ActisensePGNListTx = actisense.PGNListTx ActisensePGNListBoth = actisense.PGNListBoth )
const ( ActisenseDiagnosticStartup = actisense.DiagnosticStartup ActisenseDiagnosticError = actisense.DiagnosticError ActisenseDiagnosticSystem = actisense.DiagnosticSystem ActisenseDiagnosticNegativeAck = actisense.DiagnosticNegativeAck )
const ( ObservationFrame = raw.KindFrame ObservationMessage = raw.KindMessage ObservationDecodeError = raw.KindDecodeError ObservationGateway = raw.KindGateway ObservationTransportError = raw.KindTransportError DirectionUnknown = raw.DirectionUnknown DirectionReceived = raw.DirectionReceived DirectionTransmitted = raw.DirectionTransmitted )
const ActisenseMaxRawWrite = 65536
const ActisenseRxPGNMaskAcceptAll = uint32(0xFFFFFFFF)
Deprecated: the wire value means no change, not accept all. Use ActisenseRxPGNMaskNoChange.
const ActisenseTxPGNRateDefault = uint32(0xFFFFFFFF)
Deprecated: the wire value leaves the rate unchanged. Use ActisenseTxPGNRateNoChange.
const ReplayFrameCapacity = 4096
ReplayFrameCapacity bounds the recent written-frame capture of a replay Client. Older frames are evicted on overflow; Status reports every eviction.
Variables ¶
var ( // ErrBroadcastLimit reports that all bounded schedule slots are occupied. ErrBroadcastLimit = errors.New("n2k: broadcast schedule limit reached") // ErrBroadcastQueueFull reports that a required response cannot be queued. ErrBroadcastQueueFull = errors.New("n2k: broadcast response queue full") )
var ( // ErrWriteQueueFull reports that an asynchronous write could not be admitted // without blocking the caller. Callers may retry or apply their own policy. ErrWriteQueueFull = errors.New("n2k: write queue full") // ErrClientClosed reports an operation attempted after Client.Close. ErrClientClosed = errors.New("n2k: client closed") )
var ( // ErrNotReady reports that application transmission cannot be admitted // until the current connection has completed address claiming. ErrNotReady = errors.New("n2k: network session is not ready") // ErrEpochChanged reports work invalidated by disconnect or address change. ErrEpochChanged = errors.New("n2k: network session epoch changed") )
var ErrActisenseGatewaySessionRequired = errors.New("n2k: gateway-owned Actisense message formats cannot back Client; use NewActisenseTCPSession/NewActisenseSerialSession or a source-authoritative raw CAN format")
ErrActisenseGatewaySessionRequired reports an attempt to run a source- authoritative Client over gateway-owned BST-93/94 traffic. Use a public ActisenseGatewaySession for legacy message sends, or BST-95 raw mode for a Client with its own NMEA 2000 identity.
var ErrActisenseNotReady = gateway.ErrActisenseNotReady
ErrActisenseNotReady means no acknowledged gateway connection is available. The operation was not queued for a future connection.
var ErrActisenseRemoteEpochChanged = errors.New("n2k: Actisense remote request canceled because the local address or connection epoch changed")
ErrActisenseRemoteEpochChanged identifies an operation invalidated by a connection or local address-identity change. It may be wrapped.
var ErrObservationOverflow = errors.New("n2k: observation buffer overflow")
ErrObservationOverflow reports that an observation subscriber could not keep up. Only that subscriber is closed; protocol processing continues.
var ErrProtocolQueueFull = errors.New("n2k: protocol write queue full")
ErrProtocolQueueFull reports exhaustion of a bounded automatic-protocol transmission lane.
var ErrReceiveOverflow = errors.New("n2k: receive buffer overflow")
ErrReceiveOverflow reports that a live Client subscriber could not keep up with bus traffic. The subscriber is closed rather than allowing application backpressure to stall address claiming and other protocol processing.
var ErrRequestQueueFull = errors.New("n2k: request table full")
ErrRequestQueueFull reports that the bounded ISO request table is full.
Functions ¶
func EncodeActisenseCANASCII ¶ added in v1.2.0
func EncodeActisenseCANASCII(frame can.Frame, direction Direction, transportTimestamp time.Duration) ([]byte, error)
EncodeActisenseCANASCII renders one CAN frame in Actisense's documented RAW ASCII representation.
func EncodeActisenseN2KASCII ¶ added in v1.2.0
func EncodeActisenseN2KASCII(pgn uint32, priority, source, destination uint8, payload []byte, transportTimestamp time.Duration) ([]byte, error)
EncodeActisenseN2KASCII renders one assembled NMEA 2000 message in the documented Type-A representation.
func Observe ¶ added in v1.0.0
Observe returns a bounded iterator of owned transport observations from the configured read-only sources. Its bounded channel applies backpressure to the source, which makes file capture and replay lossless without unbounded memory growth. Use Client.Observations for a writable Client; that live protocol path fails only the slow subscriber with ErrObservationOverflow. Early iteration exit cancels and joins all source cleanup. WithBus is only accepted by NewClient; use Client.Observations to observe a custom bus.
func Receive ¶
Receive returns an iterator of decoded NMEA 2000 messages from the configured sources. Each yielded value is a pointer to a PGN struct (e.g., *pgn.VesselHeading) or *pgn.UnknownPGN if IncludeUnknown() is set.
Example ¶
Replay the bundled capture file -- no hardware required. Swap n2k.File(...) for n2k.CAN("can0"), n2k.TCP("192.168.4.1:1457", n2k.FormatYDRaw), or n2k.USB("/dev/ttyUSB0") to read a live bus.
package main
import (
"context"
"fmt"
"log"
"github.com/open-ships/n2k"
"github.com/open-ships/n2k/pgn"
)
func main() {
ctx := context.Background()
for msg, err := range n2k.Receive(ctx, n2k.File("testdata/sample.log")) {
if err != nil {
log.Fatal(err)
}
if heading, ok := msg.(*pgn.VesselHeading); ok {
if rad, present := heading.HeadingValue(); present {
fmt.Printf("heading: %.4f rad\n", rad)
return
}
}
}
}
Output: heading: 1.9624 rad
Example (Filter) ¶
Filter messages with a CEL expression; metadata-only expressions skip decoding entirely.
package main
import (
"context"
"fmt"
"log"
"github.com/open-ships/n2k"
"github.com/open-ships/n2k/pgn"
)
func main() {
ctx := context.Background()
for msg, err := range n2k.Receive(ctx,
n2k.File("testdata/sample.log"),
n2k.Filter("pgn == 128267"),
) {
if err != nil {
log.Fatal(err)
}
if depth, ok := msg.(*pgn.WaterDepth); ok {
if meters, present := depth.DepthValue(); present {
fmt.Printf("water depth: %.2f m\n", meters)
return
}
}
}
}
Output: water depth: 2.70 m
func Request ¶
Request sends an ISO Request (PGN 59904) for T's PGN to target and waits for the first matching reply. T names the expected response struct, e.g.
pi, err := n2k.Request[*pgn.ProductInformation](ctx, client, 0x23)
target 255 broadcasts the request and accepts a reply from any device. When ctx has no deadline, a default of 1250 ms (the ISO 11783 response time) is applied. Request works on bus clients only.
Types ¶
type ActisenseBEMOrigin ¶ added in v1.2.0
ActisenseBEMOrigin identifies the local or remote source of a BEM response.
type ActisenseBEMPath ¶ added in v1.2.0
ActisenseBEMPath distinguishes local gateway commands from remote bus commands.
type ActisenseBEMResponse ¶ added in v1.2.0
type ActisenseBEMResponse = actisense.BEMResponse
ActisenseBEMResponse is an owned decoded BEM response with command, origin, device identity, and data.
type ActisenseByteStream ¶ added in v1.2.0
ActisenseByteStream is a full-duplex byte transport for one Actisense connection epoch. Close must unblock Read and Write.
type ActisenseCANConfig ¶ added in v1.2.0
ActisenseCANConfig contains stored CAN identity configuration; it does not prove the live claimed address.
type ActisenseCANInfoField ¶ added in v1.2.0
type ActisenseCANInfoField = actisense.CANInfoField
ActisenseCANInfoField selects a CAN installation-description or manufacturer-information field.
type ActisenseDevice ¶ added in v1.2.0
type ActisenseDevice struct {
*actisense.CommandSet
}
ActisenseDevice exposes the same typed command Interface for a locally attached gateway and a remote Actisense device.
type ActisenseDeviceCapabilities ¶ added in v1.2.0
type ActisenseDeviceCapabilities = actisense.DeviceCapabilities
ActisenseDeviceCapabilities describes known protocol capabilities and model-specific restrictions.
type ActisenseDeviceError ¶ added in v1.2.0
type ActisenseDeviceError = actisense.DeviceError
ActisenseDeviceError reports a device error code for a BEM command; use errors.As to inspect it.
type ActisenseDiagnostic ¶ added in v1.2.0
type ActisenseDiagnostic = actisense.Diagnostic
ActisenseDiagnostic is an owned BEM diagnostic with its response and origin.
type ActisenseDiagnosticKind ¶ added in v1.2.0
type ActisenseDiagnosticKind = actisense.DiagnosticKind
ActisenseDiagnosticKind identifies a startup, error, status, or negative-acknowledgment event.
type ActisenseEBLTrace ¶ added in v1.2.0
type ActisenseEBLTrace struct {
// contains filtered or unexported fields
}
ActisenseEBLTrace converts raw transport reads/writes into the SDK's EBL wire-trace representation. Valid received frames become checksum-stripped BSTRawFrame records; invalid or unframed bytes remain exact raw evidence.
func NewActisenseEBLTrace ¶ added in v1.2.0
func NewActisenseEBLTrace(writer *EBLWriter) (*ActisenseEBLTrace, error)
NewActisenseEBLTrace creates a concurrent-safe trace using a non-nil EBL writer. Attach it with WithActisenseWireTrace; call Flush after the session ends to retain incomplete trailing input. It does not own the output stream.
func (*ActisenseEBLTrace) Err ¶ added in v1.2.0
func (t *ActisenseEBLTrace) Err() error
Err returns the first trace error. It is concurrency-safe and nil-safe.
func (*ActisenseEBLTrace) Flush ¶ added in v1.2.0
func (t *ActisenseEBLTrace) Flush() error
Flush records any incomplete trailing receive bytes and returns the first trace error. It does not flush or close the caller-owned output stream. A nil trace is a no-op.
type ActisenseErrorReport ¶ added in v1.2.0
type ActisenseErrorReport = actisense.ErrorReport
ActisenseErrorReport contains a decoded gateway error report.
type ActisenseGatewaySession ¶ added in v1.2.0
type ActisenseGatewaySession struct {
*ActisenseDevice
// contains filtered or unexported fields
}
ActisenseGatewaySession owns a gateway identity, a sole-reader BEM session, observations, typed diagnostics, and explicit PGN-list transactions. It is deliberately not a Bus and does not run address claiming.
func NewActisenseGatewaySession ¶ added in v1.2.0
func NewActisenseGatewaySession(ctx context.Context, endpoint string, open ActisenseOpenFunc, options ...ActisenseSessionOption) (*ActisenseGatewaySession, error)
NewActisenseGatewaySession opens a gateway-owned session over a custom full-duplex byte-stream Adapter.
func NewActisenseSerialSession ¶ added in v1.2.0
func NewActisenseSerialSession(ctx context.Context, port string, serialConfig ActisenseSerialConfig, options ...ActisenseSessionOption) (*ActisenseGatewaySession, error)
NewActisenseSerialSession opens a gateway-owned session with configurable serial settings. The zero serial config defaults to 115200 8N1.
func NewActisenseTCPSession ¶ added in v1.2.0
func NewActisenseTCPSession(ctx context.Context, address string, options ...ActisenseSessionOption) (*ActisenseGatewaySession, error)
NewActisenseTCPSession opens an honest gateway-owned BST-93/94 and BEM session over TCP.
func (*ActisenseGatewaySession) ActisenseRemoteDevice ¶ added in v1.4.0
func (s *ActisenseGatewaySession) ActisenseRemoteDevice(source uint8, options ...ActisenseRemoteOption) (*ActisenseRemoteDevice, error)
ActisenseRemoteDevice addresses a remote device through the gateway's own identity using BST-94 / PGN 126720. Each request first verifies its return address with a random Echo challenge, then binds correlation to that address and connection. It never claims a virtual node or changes PGN enable lists.
func (*ActisenseGatewaySession) Close ¶ added in v1.2.0
func (s *ActisenseGatewaySession) Close() error
Close cancels an active configuration transaction, waits for its cleanup, attempts same-epoch restoration, closes the transport, and joins the reader. Restoration has its own command timeout; failed restoration is included in the returned error. Close is concurrent-safe, idempotent, and nil-safe.
func (*ActisenseGatewaySession) ConfigureTransmitPGNs ¶ added in v1.2.0
func (s *ActisenseGatewaySession) ConfigureTransmitPGNs(ctx context.Context, configurations []ActisenseTxPGNConfiguration) error
ConfigureTransmitPGNs snapshots every affected session entry, stages all changes, then activates once. Transactions are serialized. On failure, a separate cleanup deadline attempts restoration on the same connection epoch; the returned error includes any restoration failure. The earliest original entries are retained for another restoration attempt by Close. Cancellation may therefore take up to the command timeout to finish cleanup. Direct Tx-list commands must not run concurrently with this transaction.
func (*ActisenseGatewaySession) Diagnostics ¶ added in v1.2.0
func (s *ActisenseGatewaySession) Diagnostics() iter.Seq2[ActisenseDiagnostic, error]
Diagnostics yields owned local BEM diagnostic events, including retained startup diagnostics. Subscriptions are independent and bounded by the session buffer; slow consumers terminate with ErrObservationOverflow.
func (*ActisenseGatewaySession) Err ¶ added in v1.2.0
func (s *ActisenseGatewaySession) Err() error
Err returns the terminal session error, or nil while healthy or after normal shutdown. It is safe concurrently with other session methods.
func (*ActisenseGatewaySession) Observations ¶ added in v1.2.0
func (s *ActisenseGatewaySession) Observations() iter.Seq2[Observation, error]
Observations subscribes when iteration starts and yields owned transport records until shutdown, error, or early loop exit. Independent bounded subscriptions fail with ErrObservationOverflow if a consumer falls behind.
func (*ActisenseGatewaySession) SendBST ¶ added in v1.4.0
func (s *ActisenseGatewaySession) SendBST(ctx context.Context, bst []byte) error
SendBST sends checksum-free BST bytes (ID, length, payload), adding the checksum, DLE escaping, and BDTP framing. Unknown BST IDs are supported. The input must contain exactly one complete datagram, at most 1800 bytes. This is an explicit protocol escape hatch; the caller selects a record appropriate for the connected device's operating mode.
func (*ActisenseGatewaySession) SendPGN ¶ added in v1.2.0
SendPGN transmits one assembled PGN under the gateway's own claimed source address. The message must implement pgn.PGN; nil or read-only messages return an error. It never enables or activates a Tx list implicitly.
func (*ActisenseGatewaySession) SendRaw ¶ added in v1.4.0
func (s *ActisenseGatewaySession) SendRaw(ctx context.Context, wire []byte) error
SendRaw sends an owned snapshot of verbatim wire bytes through the same serialized writer as BEM and PGN operations. It adds no checksum or framing. Each call is limited to ActisenseMaxRawWrite bytes and the command timeout. Cancellation or partial failure closes that connection; writes are never retried on a reconnect. It does not implement any additional wire protocol.
func (*ActisenseGatewaySession) SendRawPGN ¶ added in v1.2.0
func (s *ActisenseGatewaySession) SendRawPGN(ctx context.Context, pgnNumber uint32, priority, destination uint8, payload []byte) error
SendRawPGN synchronously sends up to 223 payload bytes using the gateway identity. Priority must be 0-7; broadcast PGNs require destination 255. It copies the payload, honors caller and command deadlines, and rejects an unready session. Success confirms the transport write, not remote acceptance. PGN lists are never changed implicitly.
func (*ActisenseGatewaySession) Status ¶ added in v1.2.0
func (s *ActisenseGatewaySession) Status() ActisenseSessionStatus
Status returns a concurrency-safe, owned snapshot of connection readiness, identity, subscribers, and cumulative metrics. A nil session is closed.
type ActisenseHardwareProtocol ¶ added in v1.2.0
type ActisenseHardwareProtocol = actisense.HardwareProtocol
ActisenseHardwareProtocol identifies the protocol supported by a hardware port.
type ActisenseModeError ¶ added in v1.1.0
ActisenseModeError reports that an Actisense gateway did not acknowledge a requested operating mode. RequestedMode is the Actisense wire value; raw CAN mode is 5. The wrapped error retains timeout, disconnect, negative acknowledgement, or device-error details.
func (*ActisenseModeError) Error ¶ added in v1.1.0
func (e *ActisenseModeError) Error() string
Error describes the requested operating mode and its setup failure.
func (*ActisenseModeError) Unwrap ¶ added in v1.1.0
func (e *ActisenseModeError) Unwrap() error
Unwrap returns the underlying gateway setup error.
type ActisenseModelID ¶ added in v1.2.0
ActisenseModelID identifies an Actisense hardware model from a BEM response.
type ActisenseNegativeAck ¶ added in v1.2.0
type ActisenseNegativeAck = actisense.NegativeAck
ActisenseNegativeAck contains the rejected command identity and device error code.
type ActisenseNegativeAckError ¶ added in v1.2.0
type ActisenseNegativeAckError = actisense.NegativeAckError
ActisenseNegativeAckError reports an asynchronous negative acknowledgment of a BEM command.
type ActisenseOpenFunc ¶ added in v1.2.0
type ActisenseOpenFunc func(context.Context) (ActisenseByteStream, error)
ActisenseOpenFunc opens one custom Actisense byte-stream connection epoch. It must return promptly when its context ends. It may be called again when reconnection is configured.
type ActisenseOperatingMode ¶ added in v1.2.0
type ActisenseOperatingMode = actisense.OperatingMode
ActisenseOperatingMode selects the gateway operating mode; use the ActisenseMode constants.
type ActisensePGNEnableFlag ¶ added in v1.2.0
type ActisensePGNEnableFlag = actisense.PGNEnableFlag
ActisensePGNEnableFlag selects disabled, enabled, or request-response PGN behavior.
type ActisensePGNListParameters ¶ added in v1.2.0
type ActisensePGNListParameters = actisense.PGNListParameters
ActisensePGNListParameters describes the gateway PGN-list configuration.
type ActisensePGNListSelector ¶ added in v1.2.0
type ActisensePGNListSelector = actisense.PGNListSelector
ActisensePGNListSelector selects the receive list, transmit list, or both lists.
type ActisenseParity ¶ added in v1.2.0
type ActisenseParity uint8
ActisenseParity configures parity on a directly connected Actisense serial Adapter without exposing the implementation's serial library.
const ( ActisenseParityNone ActisenseParity = iota ActisenseParityOdd ActisenseParityEven ActisenseParityMark ActisenseParitySpace )
type ActisensePortBaudrate ¶ added in v1.2.0
type ActisensePortBaudrate = actisense.PortBaudrate
ActisensePortBaudrate contains a port index and its baud-rate configuration.
type ActisensePortDuplicateDelete ¶ added in v1.4.0
type ActisensePortDuplicateDelete = actisense.PortDuplicateDelete
ActisensePortDuplicateDelete selects the port duplicate-suppression setting.
type ActisensePortInventory ¶ added in v1.2.0
type ActisensePortInventory = actisense.PortInventory
ActisensePortInventory contains the complete decoded device port inventory.
type ActisensePortInventoryEntry ¶ added in v1.2.0
type ActisensePortInventoryEntry = actisense.PortInventoryEntry
ActisensePortInventoryEntry describes one hardware port in a device inventory.
type ActisensePortMedia ¶ added in v1.2.0
ActisensePortMedia identifies a port medium, such as CAN, serial, or Ethernet.
type ActisensePortPCode ¶ added in v1.2.0
ActisensePortPCode contains a port index and its proprietary-code setting.
type ActisenseProductInfo ¶ added in v1.2.0
type ActisenseProductInfo = actisense.ProductInfo
ActisenseProductInfo contains the product identity returned by an Actisense device.
type ActisenseProprietaryPGNList ¶ added in v1.2.0
type ActisenseProprietaryPGNList = actisense.ProprietaryPGNList
ActisenseProprietaryPGNList contains an assembled proprietary PGN list.
type ActisenseProtocolMetrics ¶ added in v1.2.0
type ActisenseProtocolMetrics = actisense.SessionMetrics
ActisenseProtocolMetrics is an owned snapshot of cumulative transport and BEM counters.
type ActisenseRemoteDevice ¶ added in v1.2.0
type ActisenseRemoteDevice struct {
*ActisenseDevice
SourceAddress uint8
// contains filtered or unexported fields
}
ActisenseRemoteDevice issues the same typed commands as a local gateway through Actisense's addressed PGN-126720 envelope.
func (*ActisenseRemoteDevice) Diagnostics ¶ added in v1.2.0
func (d *ActisenseRemoteDevice) Diagnostics() iter.Seq2[ActisenseDiagnostic, error]
Diagnostics yields owned diagnostic events from this remote source address. The subscription ends on client/session shutdown, overflow, or early loop exit; it does not close the underlying connection.
func (*ActisenseRemoteDevice) Metrics ¶ added in v1.2.0
func (d *ActisenseRemoteDevice) Metrics() ActisenseProtocolMetrics
Metrics returns cumulative BEM correlation and latency counters shared by all remote-device handles on this Client or gateway session.
type ActisenseRemoteOption ¶ added in v1.2.0
type ActisenseRemoteOption interface {
// contains filtered or unexported methods
}
ActisenseRemoteOption configures a remote-device handle.
func WithActisenseRemoteMultiReplyInactivity ¶ added in v1.2.0
func WithActisenseRemoteMultiReplyInactivity(timeout time.Duration) ActisenseRemoteOption
WithActisenseRemoteMultiReplyInactivity bounds the gap between remote BEM replies. It must be positive; the default is 500 milliseconds.
func WithActisenseRemoteTimeout ¶ added in v1.2.0
func WithActisenseRemoteTimeout(timeout time.Duration) ActisenseRemoteOption
WithActisenseRemoteTimeout bounds one remote BEM command including its response train. It must be positive; the default is five seconds. An earlier caller deadline takes precedence.
type ActisenseRxPGNEnableList ¶ added in v1.2.0
type ActisenseRxPGNEnableList = actisense.RxPGNEnableList
ActisenseRxPGNEnableList contains a bounded, assembled F2 receive-enable list.
type ActisenseRxPGNEnableListF1 ¶ added in v1.4.0
type ActisenseRxPGNEnableListF1 = actisense.RxPGNEnableListF1
ActisenseRxPGNEnableListF1 contains an assembled legacy F1 receive-enable list.
type ActisenseRxPGNListEntry ¶ added in v1.2.0
type ActisenseRxPGNListEntry = actisense.RxPGNListEntry
ActisenseRxPGNListEntry describes one entry in a decoded F2 receive list.
type ActisenseRxPGNListF1Entry ¶ added in v1.4.0
type ActisenseRxPGNListF1Entry = actisense.RxPGNListF1Entry
ActisenseRxPGNListF1Entry describes one entry in a legacy F1 receive-enable list.
type ActisenseRxPGNState ¶ added in v1.2.0
type ActisenseRxPGNState = actisense.RxPGNState
ActisenseRxPGNState contains one receive PGN entry and its effective flag and mask.
type ActisenseSerialConfig ¶ added in v1.2.0
type ActisenseSerialConfig struct {
BaudRate int
DataBits int
Parity ActisenseParity
StopBits ActisenseStopBits
}
ActisenseSerialConfig is the complete host-side serial configuration. Its zero value selects the Actisense binary default of 115200 8N1.
type ActisenseSerialOption ¶ added in v1.2.0
type ActisenseSerialOption interface {
// contains filtered or unexported methods
}
ActisenseSerialOption configures one direct serial Adapter.
func WithActisenseBaudRate ¶ added in v1.2.0
func WithActisenseBaudRate(baudRate int) ActisenseSerialOption
WithActisenseBaudRate changes only the host-side baud rate.
func WithActisenseSerialConfig ¶ added in v1.2.0
func WithActisenseSerialConfig(config ActisenseSerialConfig) ActisenseSerialOption
WithActisenseSerialConfig replaces the host-side serial configuration. Zero BaudRate or DataBits fields retain the 115200 8N1 defaults.
type ActisenseSessionMetrics ¶ added in v1.2.0
type ActisenseSessionMetrics struct {
ConnectionEpochs uint64
Reconnects uint64
GatewayResets uint64
Protocol ActisenseProtocolMetrics
}
ActisenseSessionMetrics remains cumulative across reconnect epochs.
type ActisenseSessionOption ¶ added in v1.2.0
type ActisenseSessionOption interface {
// contains filtered or unexported methods
}
ActisenseSessionOption configures a public gateway-owned session.
func WithActisenseCommandTimeout ¶ added in v1.2.0
func WithActisenseCommandTimeout(timeout time.Duration) ActisenseSessionOption
WithActisenseCommandTimeout bounds each local command, physical send, and configuration restoration attempt. It must be positive; the default is five seconds. An earlier caller deadline also applies to the original operation.
func WithActisenseMultiReplyInactivity ¶ added in v1.2.0
func WithActisenseMultiReplyInactivity(timeout time.Duration) ActisenseSessionOption
WithActisenseMultiReplyInactivity bounds the gap between local BEM replies. It must be positive; the default is 500 milliseconds. The command timeout separately bounds the whole response train.
func WithActisensePreserveOperatingMode ¶ added in v1.4.0
func WithActisensePreserveOperatingMode() ActisenseSessionOption
WithActisensePreserveOperatingMode opens a control session that reads and preserves the device's mode on every connection. It sends no mode setter during startup or Close. The last mode/preserve option wins. PGN sends still require mode 1 or 2; raw BST and BEM commands remain available in other modes.
func WithActisenseSessionBuffer ¶ added in v1.2.0
func WithActisenseSessionBuffer(size int) ActisenseSessionOption
WithActisenseSessionBuffer sets the positive per-subscriber observation and diagnostic capacity; the default is 64. Overflow terminates the affected subscription with ErrObservationOverflow without blocking the session reader.
func WithActisenseSessionLogger ¶ added in v1.2.0
func WithActisenseSessionLogger(logger *slog.Logger) ActisenseSessionOption
WithActisenseSessionLogger selects the session logger; nil uses slog.Default.
func WithActisenseSessionMode ¶ added in v1.2.0
func WithActisenseSessionMode(mode ActisenseOperatingMode) ActisenseSessionOption
WithActisenseSessionMode selects gateway-owned BST message mode 1 or 2. Source-authoritative mode 5 belongs to NewClient via ActisenseTCP or ActisenseSerial and is intentionally rejected here.
func WithActisenseSessionReadyTimeout ¶ added in v1.2.0
func WithActisenseSessionReadyTimeout(timeout time.Duration) ActisenseSessionOption
WithActisenseSessionReadyTimeout bounds opening and mode negotiation. It must be positive; the default is five seconds.
func WithActisenseSessionReconnect ¶ added in v1.2.0
func WithActisenseSessionReconnect(policy ReconnectPolicy) ActisenseSessionOption
WithActisenseSessionReconnect enables reconnects after a dropped session. Each acknowledged connection starts a new epoch and cancels old requests. Zero backoff fields use the ReconnectPolicy defaults.
func WithActisenseWireTrace ¶ added in v1.2.0
func WithActisenseWireTrace(trace *ActisenseEBLTrace) ActisenseSessionOption
WithActisenseWireTrace records exact transmitted bytes and received wire evidence to an EBL trace. Valid received BDTP frames are stored in the checksum-stripped BSTRaw representation used by Actisense tooling.
type ActisenseSessionStatus ¶ added in v1.2.0
type ActisenseSessionStatus struct {
Connected bool
ConnectionEpoch uint64
Closed bool
TerminalError error
OperatingMode ActisenseOperatingMode
SourceAuthoritative bool
ReceiveAll bool
ISOControlPGNsVisible bool
ObservationSubscribers int
DiagnosticSubscribers int
DeviceCapabilities ActisenseDeviceCapabilities
WireTraceError error
Metrics ActisenseSessionMetrics
// GatewaySourceAddress is learned from a nonce-verified remote reply,
// never from the stored CAN configuration. It is nil until verified.
GatewaySourceAddress *uint8
IdentityEpoch uint64
RemoteMetrics ActisenseProtocolMetrics
}
ActisenseSessionStatus honestly describes the gateway-owned connection. A session never claims an independent NMEA 2000 source identity.
type ActisenseStartupStatus ¶ added in v1.2.0
type ActisenseStartupStatus = actisense.StartupStatus
ActisenseStartupStatus contains decoded gateway startup information.
type ActisenseStopBits ¶ added in v1.2.0
type ActisenseStopBits uint8
ActisenseStopBits configures stop bits on a directly connected Actisense serial Adapter.
const ( ActisenseStopBitsOne ActisenseStopBits = iota ActisenseStopBitsOnePointFive ActisenseStopBitsTwo )
type ActisenseSupportedPGN ¶ added in v1.2.0
type ActisenseSupportedPGN = actisense.SupportedPGN
ActisenseSupportedPGN describes one PGN supported by the gateway.
type ActisenseSupportedPGNList ¶ added in v1.2.0
type ActisenseSupportedPGNList = actisense.SupportedPGNList
ActisenseSupportedPGNList contains an assembled list of gateway-supported PGNs.
type ActisenseSystemStatus ¶ added in v1.2.0
type ActisenseSystemStatus = actisense.SystemStatus
ActisenseSystemStatus contains a decoded gateway system-status report.
type ActisenseTxPGNConfiguration ¶ added in v1.2.0
type ActisenseTxPGNConfiguration struct {
PGN uint32
Flag ActisensePGNEnableFlag
Rate *uint32
}
ActisenseTxPGNConfiguration is one staged transmit-list change. PGN is the message number and Flag selects enabled, disabled, or respond-only behavior. Rate is milliseconds: zero means event-driven; nil or a value >= 65535 leaves the current rate unchanged. The pointed-to rate must remain stable during ConfigureTransmitPGNs.
type ActisenseTxPGNEnableList ¶ added in v1.2.0
type ActisenseTxPGNEnableList = actisense.TxPGNEnableList
ActisenseTxPGNEnableList contains a bounded, assembled F2 transmit-enable list.
type ActisenseTxPGNEnableListF1 ¶ added in v1.4.0
type ActisenseTxPGNEnableListF1 = actisense.TxPGNEnableListF1
ActisenseTxPGNEnableListF1 contains an assembled legacy F1 transmit-enable list.
type ActisenseTxPGNListEntry ¶ added in v1.2.0
type ActisenseTxPGNListEntry = actisense.TxPGNListEntry
ActisenseTxPGNListEntry describes one entry in a decoded F2 transmit list.
type ActisenseTxPGNListF1Entry ¶ added in v1.4.0
type ActisenseTxPGNListF1Entry = actisense.TxPGNListF1Entry
ActisenseTxPGNListF1Entry describes one entry in a legacy F1 transmit-enable list.
type ActisenseTxPGNState ¶ added in v1.2.0
type ActisenseTxPGNState = actisense.TxPGNState
ActisenseTxPGNState contains one transmit PGN entry, effective flag, rate, timeout, and priority.
type Bus ¶
type Bus interface {
// Run opens the bus and delivers every incoming frame to handler until
// ctx is cancelled or an unrecoverable error occurs. Client serializes
// concurrent handler calls, though Bus implementations should normally
// preserve wire order.
Run(ctx context.Context, handler func(can.Frame)) error
// WriteFrame sends one frame.
WriteFrame(frame can.Frame) error
// Close releases resources. It must be safe if Run was never called and
// safe concurrently with Run or WriteFrame. It must interrupt blocked
// device I/O and return promptly; Client waits for the interrupted call.
Close() error
}
Bus is a physical or virtual CAN bus. External callers can implement Bus to inject fake hardware for testing, or to adapt transports this library does not ship. Pass an implementation via WithBus.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a read/write NMEA 2000 bus node. It composes address claiming, transport protocol, encoding, and framing into a single type that can both receive and transmit PGN messages.
func NewClient ¶
NewClient creates a Client that can read and write NMEA 2000 messages. Provide CAN, USB, Serial, TCP, Replay, or WithBus for writable clients; File, EBL, and UDP are read-only sources for Receive/NewScanner.
Example ¶
NewClient claims a bus address and provides write access. Not runnable without CAN hardware, so this example is compile-only.
package main
import (
"context"
"log"
"github.com/open-ships/n2k"
"github.com/open-ships/n2k/pgn"
)
func main() {
ctx := context.Background()
client, err := n2k.NewClient(ctx, n2k.CAN("can0"))
if err != nil {
log.Fatal(err)
}
defer func() { _ = client.Close() }()
heading := &pgn.VesselHeading{}
if err := heading.SetHeadingValue(1.5708); err != nil { // radians in, raw wire ticks underneath
log.Fatal(err)
}
if err := client.Write(heading).Wait(); err != nil {
log.Fatal(err)
}
}
Output:
func (*Client) ActisenseRemoteDevice ¶ added in v1.2.0
func (c *Client) ActisenseRemoteDevice(source uint8, options ...ActisenseRemoteOption) (*ActisenseRemoteDevice, error)
ActisenseRemoteDevice returns a handle for one addressed Actisense device. Incoming replies must target this Client's source snapshot and are canceled across connection or address-claim epochs.
func (*Client) Broadcast ¶
func (c *Client) Broadcast(interval time.Duration, provide func(context.Context) pgn.Message) (stop func(), err error)
Broadcast schedules a PGN, learning its identity from the first non-nil result. Prefer BroadcastPGN when peers need immediate group-function lookup. A nil result skips a periodic tick. Scheduling an existing PGN replaces it.
The provider runs synchronously on its schedule's owned worker. It must return promptly when ctx ends and must not call its own stop function or Client.Close; those operations wait for the provider to finish. Stop is idempotent, cancels the provider, and waits for the worker to exit.
func (*Client) BroadcastPGN ¶ added in v0.3.0
func (c *Client) BroadcastPGN(pgnNum uint32, interval time.Duration, provide func(context.Context) pgn.Message) (stop func(), err error)
BroadcastPGN declares a schedule's PGN before its first provider call, so group functions can retime or request it immediately. At most 64 schedule workers may be alive, including providers exiting after replacement.
func (*Client) Close ¶
Close shuts down the client, cancels the context, and releases resources. It is safe to call Close multiple times.
func (*Client) DeviceAt ¶
DeviceAt resolves a bus source address to the device currently holding it. Use it to correlate a message's SourceId with a stable device identity:
if dev, ok := client.DeviceAt(msg.MessageInfo().SourceId); ok { ... }
func (*Client) Devices ¶
Devices returns a snapshot of every device observed on the bus, sorted by address. The client builds this map passively from address claims, product information, and configuration information; it also requests those PGNs from newly seen devices and enumerates the bus once at startup. Replay clients always return an empty list.
func (*Client) Err ¶ added in v0.3.0
Err returns the terminal runtime error, if the bus or address-claiming lifecycle failed. A normal Close does not set an error.
func (*Client) Observations ¶ added in v1.0.0
func (c *Client) Observations() iter.Seq2[Observation, error]
Observations returns a bounded iterator of raw observations for a live client. Frame events are published before protocol handling; assembled message and decode-error events follow as the user pipeline processes them.
func (*Client) Receive ¶
Receive returns an iterator of decoded NMEA 2000 messages. For bus clients it reads from the internal message channel; for replay clients it builds a fresh Scanner over the client's config so each call gets a full replay.
func (*Client) Scanner ¶
Scanner creates a new Scanner that reads from this client. For bus clients it reads from the internal message channel; for replay clients it builds a fresh Scanner over the client's config.
func (*Client) Status ¶ added in v0.3.0
func (c *Client) Status() ClientStatus
Status returns a concurrency-safe snapshot of the client's lifecycle and bounded queues. It does not perform I/O.
func (*Client) Write ¶
func (c *Client) Write(msg pgn.Message) *WriteResult
Write snapshots a PGN message and asynchronously transmits it. After Write returns the caller may reuse the message. Application jobs retain FIFO order; protocol traffic can run between their wire frames. The message must implement pgn.PGN; nil and read-only messages return an errored WriteResult.
func (*Client) WriteContext ¶ added in v1.3.0
WriteContext cancels queued work and in-progress transmission when ctx ends. Cancellation after a physical write attempt may leave a partial transfer; WriteError reports that uncertainty. Writes are not replayed on reconnect.
func (*Client) WrittenFrames ¶
WrittenFrames returns an owned snapshot of the newest ReplayFrameCapacity frames written in replay mode, ordered oldest to newest. Once the capture fills, new writes evict its oldest frame and still succeed. Status exposes ReplayFramesDropped so capture loss is observable. Live clients return no captured frames; use Observe for live traffic.
type ClientStatus ¶ added in v0.3.0
type ClientStatus struct {
Address uint8
AddressClaimed bool
Connected bool
ConnectionEpoch uint64
ClaimEpoch uint64
Ready bool
Rejoining bool
Closed bool
TerminalError error
WriteQueueDepth int
WriteQueueCapacity int
ReceiveSubscribers int
ObservationSubscribers int
ProtocolRequiredQueueDepth int
ProtocolRequiredQueueCapacity int
ProtocolAdvisoryQueueDepth int
ProtocolAdvisoryQueueCapacity int
ApplicationWritesAccepted uint64
ApplicationWritesCompleted uint64
ApplicationWritesFailed uint64
ApplicationWritesRejected uint64
ProtocolWritesAccepted uint64
ProtocolWritesCompleted uint64
ProtocolWritesFailed uint64
ProtocolWritesRejected uint64
FramesReceived uint64
FramesTransmitted uint64
MessagesObserved uint64
DecodeErrorsObserved uint64
GatewayEventsObserved uint64
TransportErrorsObserved uint64
PendingRequests int
RequestCapacity int
DeviceInfoQueueDepth int
DeviceInfoQueueCapacity int
DeviceInfoRequestsDropped uint64
// Replay capture keeps the newest frames; each eviction increments Dropped.
// Capacity is zero for live clients and ReplayFrameCapacity for replay.
ReplayFramesRetained int
ReplayFrameCapacity int
ReplayFramesDropped uint64
// Actisense is populated for source-authoritative Actisense binary or CAN
// ASCII buses. Gateway-owned message sessions expose the same counters on
// ActisenseGatewaySession.Status instead.
Actisense *ActisenseSessionMetrics
}
ClientStatus is a point-in-time operational snapshot suitable for health endpoints and metrics collectors.
type ConfigInfo ¶
type ConfigInfo struct {
InstallationDescription1 string
InstallationDescription2 string
ManufacturerInformation string
}
ConfigInfo describes this installation of the device (PGN 126998). All three fields are free-form strings.
type ConnectionLifecycleBus ¶ added in v1.0.0
type ConnectionLifecycleBus interface {
SetConnectionObserver(observer func(connected bool, epoch uint64))
}
ConnectionLifecycleBus is optionally implemented by reconnecting buses. The observer is invoked synchronously whenever the underlying connection changes. On connect, it runs before the new connection becomes visible to writers, allowing Client to install a fresh transmission gate. Epoch starts at 1 and increases for every successful connection.
Implementations must not call the observer while holding locks that an ordinary WriteFrame needs. The observer must return promptly and must not perform bus I/O itself.
type ContextBus ¶ added in v1.3.0
ContextBus supports cancellation of physical writes without waiting for Client.Close. Implementations must not retry a write on a new connection. Client still supports Bus by closing it to interrupt canceled legacy I/O.
type ContextMessageWriter ¶ added in v1.3.0
type ContextMessageWriter interface {
WriteMessageContext(context.Context, uint32, uint8, uint8, uint8, []byte) error
}
ContextMessageWriter is the context-aware assembled-message writing seam.
type Device ¶
type Device struct {
// RawName is the packed 64-bit ISO 11783 NAME from the device's address
// claim.
RawName uint64
// Name is the decoded NAME.
Name DeviceName
// Address is the device's most recently claimed bus address.
Address uint8
// LastSeen is when the device last transmitted anything.
LastSeen time.Time
// ProductInfo is the device's PGN 126996 payload, nil until observed.
ProductInfo *pgn.ProductInformation
// ConfigInfo is the device's PGN 126998 payload, nil until observed.
ConfigInfo *pgn.ConfigurationInformation
}
Device is one node observed on the NMEA 2000 bus. Devices are identified by their 64-bit ISO 11783 NAME — bus addresses are dynamic and can change under address contention, so RawName is the stable key.
type DeviceName ¶
type DeviceName struct {
IdentityNumber uint32 // 21 bits (0-20)
ManufacturerCode uint16 // 11 bits (21-31)
DeviceInstance uint8 // 8 bits: lower 3 (32-34) + upper 5 (35-39)
DeviceFunction uint8 // 8 bits (40-47)
DeviceClass uint8 // 7 bits (49-55), bit 48 is reserved
SystemInstance uint8 // 4 bits (56-59)
IndustryGroup uint8 // 3 bits (60-62)
}
DeviceName represents the ISO 11783 / NMEA 2000 64-bit NAME that uniquely identifies a device on a CAN bus network. The NAME is used during address claiming (PGN 60928) to arbitrate bus addresses.
func DefaultDeviceName ¶
func DefaultDeviceName() DeviceName
DefaultDeviceName returns a development-oriented DeviceName for a PC-based software gateway. Production devices should use WithName with the vendor's assigned manufacturer code and a stable, persisted identity number. The default identity is randomized so multiple development processes can coexist on one bus, but it is not a substitute for a provisioned product identity.
func UnpackDeviceName ¶
func UnpackDeviceName(name uint64) DeviceName
UnpackDeviceName extracts a DeviceName from the 64-bit NAME integer defined by ISO 11783. The arbitraryAddressCapable flag (bit 63) is not stored in the struct; callers can check it directly via (name >> 63) & 1.
func (DeviceName) Pack ¶
func (d DeviceName) Pack(arbitraryAddressCapable bool) uint64
Pack encodes the DeviceName into the 64-bit NAME integer defined by ISO 11783. The arbitraryAddressCapable flag sets bit 63, indicating the device can participate in dynamic address negotiation.
64-bit NAME layout (LSB-first):
Bits 0-20: Identity Number (21 bits) Bits 21-31: Manufacturer Code (11 bits) Bits 32-34: Device Instance Lower (3 bits) Bits 35-39: Device Instance Upper (5 bits) Bits 40-47: Device Function (8 bits) Bit 48: Reserved (0) Bits 49-55: Device Class (7 bits) Bits 56-59: System Instance (4 bits) Bits 60-62: Industry Group (3 bits) Bit 63: Arbitrary Address Capable (1 bit)
func (DeviceName) Validate ¶
func (d DeviceName) Validate() error
Validate checks that each field fits within its bit width as defined by the ISO 11783 NAME specification. DeviceInstance and DeviceFunction are uint8 and always fit their 8-bit fields.
type Direction ¶ added in v1.0.0
Direction identifies received, transmitted, or unknown traffic direction.
type EBLWriter ¶ added in v1.2.0
type EBLWriter struct {
// contains filtered or unexported fields
}
EBLWriter writes interoperable Actisense Enhanced Binary Log records. It is safe for concurrent use and retains the first output error.
func NewEBLWriter ¶ added in v1.2.0
func NewEBLWriter(output io.Writer, options ...EBLWriterOption) (*EBLWriter, error)
NewEBLWriter writes the EBL header to output and returns a concurrent-safe writer. It returns an error for invalid options or header failures. The caller owns output and is responsible for flushing or closing it.
func (*EBLWriter) Err ¶ added in v1.2.0
Err returns the first output error, or nil while the writer is healthy.
func (*EBLWriter) Metrics ¶ added in v1.2.0
func (w *EBLWriter) Metrics() EBLWriterMetrics
Metrics returns an owned, concurrency-safe snapshot of output counters.
func (*EBLWriter) WriteDescription ¶ added in v1.2.0
WriteDescription appends a UTF-8 description tag and retains any output error.
func (*EBLWriter) WriteRawBST ¶ added in v1.2.0
WriteRawBST synchronously records one checksum-stripped BST record with its capture time and direction. It copies rawBST and retains the first output error.
type EBLWriterMetrics ¶ added in v1.2.0
type EBLWriterMetrics = ebl.WriterMetrics
EBLWriterMetrics is an owned snapshot of written records, bytes, and errors.
type EBLWriterOption ¶ added in v1.2.0
type EBLWriterOption interface {
// contains filtered or unexported methods
}
EBLWriterOption configures a new Enhanced Binary Log writer.
func WithEBLDescription ¶ added in v1.2.0
func WithEBLDescription(description string) EBLWriterOption
WithEBLDescription sets the initial UTF-8 capture description. Empty omits the description; descriptions must fit the EBL tag payload limit.
func WithEBLStartTime ¶ added in v1.2.0
func WithEBLStartTime(timestamp time.Time) EBLWriterOption
WithEBLStartTime sets the initial UTC capture timestamp. Zero uses the current host time.
type FileOption ¶
type FileOption interface {
// contains filtered or unexported methods
}
FileOption configures a candump File or EBL capture source.
func OriginalTiming ¶
func OriginalTiming() FileOption
OriginalTiming replays frames or messages paced by the capture's own timestamps instead of as fast as they can be read. Records without timestamps are delivered immediately.
type MessageWriter ¶
type MessageWriter interface {
WriteMessage(pgnNum uint32, priority, source, destination uint8, payload []byte) error
}
MessageWriter is optionally implemented by Bus implementations that transmit whole assembled PGN messages rather than raw CAN frames — custom transports that perform fast-packet fragmentation themselves. When a client's bus implements MessageWriter, writes that fit in one message (payloads up to 223 bytes) bypass CAN framing and use WriteMessage; larger ISO-TP transfers and protocol frames (address claims, ISO requests) still go frame-by-frame through WriteFrame.
Implementations must honor the exact source address and CAN identifier. Gateway-owned message modes that substitute their own source are not a Bus; use ActisenseGatewaySession for those modes.
type Observation ¶ added in v1.0.0
type Observation = raw.Observation
Public aliases keep the common observation surface in package n2k while allowing transport Adapter implementations to share the cycle-free raw package.
func ParseActisenseCANASCII ¶ added in v1.2.0
func ParseActisenseCANASCII(line string) (Observation, error)
ParseActisenseCANASCII parses one source-authoritative mode-6 CAN frame.
func ParseActisenseN2KASCII ¶ added in v1.2.0
func ParseActisenseN2KASCII(line string) (Observation, error)
ParseActisenseN2KASCII parses one gateway-assembled Type-A NMEA 2000 message.
type ObservationBus ¶ added in v1.0.0
type ObservationBus interface {
RunObservations(ctx context.Context, handler func(raw.Observation)) error
}
ObservationBus is optionally implemented by buses that can preserve transport timestamps, direction, and source identity. Client prefers this Interface over Run and still accepts ordinary Bus implementations.
type ObservationKind ¶ added in v1.0.0
ObservationKind identifies the frame, message, gateway, or error layer.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures Receive, Observe, NewScanner, or NewClient.
func ActisenseSerial ¶ added in v1.1.0
func ActisenseSerial(port string, options ...ActisenseSerialOption) Option
ActisenseSerial adds a directly connected Actisense gateway at 115200 8N1. Receive, Observe, and NewScanner use the compatible gateway-owned message session. NewClient requires acknowledged mode 5 and uses source-authoritative BST-95 raw CAN; it fails rather than falling back when raw mode is unavailable. Use Serial with an explicit Actisense format to override this role-based policy.
func ActisenseTCP ¶ added in v1.1.0
ActisenseTCP adds an Actisense gateway over TCP. Receive, Observe, and NewScanner passively decode all supported BST records without changing the gateway's operating mode. NewClient requires acknowledged mode 5 and uses source-authoritative BST-95 raw CAN; it fails rather than falling back when raw mode is unavailable. Use TCP with an explicit Actisense format to override this role-based policy.
func EBL ¶ added in v1.1.0
func EBL(path string, opts ...FileOption) Option
EBL adds an Actisense Enhanced Binary Log capture source. Both classic raw BDTP streams and BSTRawFrame records are decoded. OriginalTiming paces replay using FILETIME markers.
func File ¶
func File(path string, opts ...FileOption) Option
File adds a source that replays CAN frames from a candump -L / -l log file. By default frames are delivered as fast as they can be read; pass OriginalTiming() to pace them by the log's timestamps. File sources are read-only: they work with Receive and NewScanner but not NewClient.
func Filter ¶
Filter sets a CEL expression to filter messages. The expression is automatically partitioned into pre-decode (metadata) and post-decode (struct field) stages.
func IncludeUnknown ¶
func IncludeUnknown() Option
IncludeUnknown includes undecodable messages as *pgn.UnknownPGN in the output stream. By default, unknown PGNs are dropped and logged at debug level.
func ReplayObservations ¶ added in v1.0.0
func ReplayObservations(observations []Observation) Option
ReplayObservations adds owned source-aware observations for deterministic tests and capture replay. Each observation is copied before it is retained.
func Serial ¶ added in v1.1.0
func Serial(port string, format StreamFormat, options ...ActisenseSerialOption) Option
Serial adds a directly connected Actisense-format gateway at 115200 8N1. FormatActisense and FormatActisenseN2KASCII are passive, gateway-owned message sources. FormatActisenseRaw and FormatActisenseCANASCII perform an acknowledged mode setup and provide source-authoritative CAN frames.
func TCP ¶
func TCP(addr string, format StreamFormat) Option
TCP adds a source that dials a network gateway (e.g. a Yacht Devices YDWG-02 in RAW server mode, or an Actisense gateway) at addr ("host:port"). TCP works with Receive/NewScanner and can also back NewClient for writes. FormatYDRaw, FormatActisenseRaw, and FormatActisenseCANASCII provide frame-level access. The two Actisense message formats are read-only here; use NewActisenseTCPSession for a writable gateway-owned binary session.
func UDP ¶
func UDP(listenAddr string, format StreamFormat) Option
UDP adds a source that listens on listenAddr (e.g. ":1457" or "0.0.0.0:1457") for datagrams broadcast by a network gateway. UDP sources are read-only: they work with Receive and NewScanner but not NewClient. Raw/ASCII formats require the upstream gateway to already emit the selected representation because UDP has no return channel for BEM mode setup.
func WithBus ¶
WithBus provides a pre-constructed Bus for the client to use — either a custom transport not shipped by this library, or a fake for testing. When set, the client uses this bus directly instead of constructing one from CAN/USB sources. This option is only accepted by NewClient; use its Receive, Scanner, or Observations methods for reading. Standalone readers reject it.
func WithClaimTimeout ¶
WithClaimTimeout sets how long NewClient blocks waiting for address claiming to complete on a real CAN bus. Default is 1500ms. This allows time for the initial 250ms claim window plus several rounds of contention renegotiation.
func WithConfigInfo ¶
func WithConfigInfo(ci ConfigInfo) Option
WithConfigInfo sets the installation description (PGN 126998) this client reports when another device requests it.
func WithHeartbeatInterval ¶
WithHeartbeatInterval sets the cadence of the client's automatic heartbeat (PGN 126993). The NMEA 2000 standard requires every device to heartbeat at least every 60 seconds, which is the default. Pass 0 to disable automatic heartbeats. Only bus clients heartbeat; replay clients never do.
func WithLogger ¶
WithLogger overrides the default slog.Default() logger.
func WithName ¶
func WithName(name DeviceName) Option
WithName sets the ISO 11783 device NAME used for address claiming. The NAME is a 64-bit identifier that uniquely identifies this device on the NMEA 2000 network. In address contention, the device with the lower NAME wins. When not set, a default NAME is used (see DefaultDeviceName).
func WithPreferredAddress ¶ added in v0.3.0
WithPreferredAddress sets the starting address for automatic address claiming while retaining arbitrary-address capability. Persist the last Client.Status().Address and pass it here on the next start to reclaim the device's prior address when available. Valid addresses are 0 through 251. Unlike WithSourceAddress, contention moves the client to another address.
func WithProductInfo ¶
func WithProductInfo(p ProductInfo) Option
WithProductInfo sets the product identity (PGN 126996) this client reports when another device requests it. Without it, a generic software-gateway identity is reported. String fields longer than 32 bytes are rejected when the client is created.
func WithReadyTimeout ¶ added in v1.2.0
WithReadyTimeout sets how long NewClient waits for an asynchronous Bus to open and finish transport-specific readiness work before address claiming starts. The default is five seconds. This deadline is intentionally separate from WithClaimTimeout so a gateway handshake can return its typed failure instead of being hidden by the address-claim deadline.
func WithReceiveBuffer ¶ added in v0.3.0
WithReceiveBuffer sets the number of decoded messages retained per live Client subscription. The default is 64. A subscriber that falls behind this bound is closed with ErrReceiveOverflow so it cannot stall protocol processing or other subscribers.
func WithReconnect ¶ added in v0.2.0
func WithReconnect(policy ReconnectPolicy) Option
WithReconnect enables automatic reconnection for TCP gateway sources. After a connection drops, the source re-dials with exponential backoff (starting at InitialBackoff, capped at MaxBackoff) until it reconnects or the context is cancelled. Without this option, a dropped TCP connection ends the read loop and surfaces as an error (the historical behavior).
Reconnection covers connections that drop mid-session; the initial connection must still succeed (for NewClient, within the claim timeout). It applies only to TCP sources — CAN, USB, UDP, file, and replay sources are unaffected. A bus client starts a new network epoch after reconnect: it reclaims its address, waits through contention, refreshes device discovery, and then resumes scheduled transmissions.
func WithSourceAddress ¶
WithSourceAddress sets an explicit NMEA 2000 source address for the client. When set, the client uses this address and treats contention as a fatal error. When not set (default), the client uses auto mode — starting at address 251 and working downward if contention occurs.
func WithWriteQueue ¶ added in v0.3.0
WithWriteQueue sets the number of asynchronous writes that can wait behind the active write. The default is 64. Once full, Write completes immediately with ErrWriteQueueFull rather than blocking an application goroutine.
func WithWriteTimeout ¶ added in v1.3.0
WithWriteTimeout bounds one physical frame or gateway record write. The default is one second. A stalled legacy Bus is closed to interrupt I/O.
func YachtDevicesTCP ¶ added in v1.5.0
YachtDevicesTCP adds a Yacht Devices RAW TCP gateway (for example, a YDWG-02 in RAW server mode). Compatible gateways that speak the same protocol are also supported. It provides source-authoritative CAN frames and can back NewClient.
func YachtDevicesUDP ¶ added in v1.5.0
YachtDevicesUDP adds a read-only Yacht Devices RAW UDP broadcast source. Compatible gateways that speak the same protocol are also supported.
type ProductInfo ¶
type ProductInfo struct {
// N2KVersion is the supported NMEA 2000 standard version in thousandths,
// e.g. 2101 means version 2.101. Zero means the default (2101).
N2KVersion uint16
// ProductCode is the manufacturer-assigned product code.
ProductCode uint16
// ModelID names the product (at most 32 bytes on the wire).
ModelID string
// SoftwareVersion is the software version string (at most 32 bytes).
SoftwareVersion string
// ModelVersion is the model version string (at most 32 bytes).
ModelVersion string
// SerialNumber is the device serial code (at most 32 bytes).
SerialNumber string
// CertificationLevel is the NMEA 2000 certification level lookup value.
CertificationLevel uint8
// LoadEquivalency is the device's bus load in units of 50 mA.
LoadEquivalency uint8
}
ProductInfo describes this client as an NMEA 2000 product. Other devices (chartplotters, network analyzers) request it via PGN 126996 and display it in their device lists.
type ReadyBus ¶ added in v0.3.0
type ReadyBus interface {
Ready() <-chan struct{}
}
ReadyBus is optionally implemented by buses that are not writable until Run has opened their underlying device. Client waits for Ready before starting address claiming, removing scheduler-dependent startup races.
type ReconnectPolicy ¶ added in v0.2.0
type ReconnectPolicy struct {
// InitialBackoff is the delay before the first reconnect attempt after a
// drop, and the delay restored after any successful connection. Defaults
// to 500ms when zero.
InitialBackoff time.Duration
// MaxBackoff caps the exponentially growing delay between attempts while
// the gateway stays unreachable. Defaults to 30s when zero.
MaxBackoff time.Duration
}
ReconnectPolicy configures automatic reconnection for network gateway (TCP) sources after a dropped connection. The zero value is valid: both fields fall back to their defaults.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner reads decoded NMEA 2000 messages one at a time. Call Next() to advance, Message() to get the current message, and Err() after Next returns false. Use one goroutine for these methods; Close may run concurrently to cancel a blocked Next and wait for source cleanup.
func NewScanner ¶
NewScanner creates a Scanner that reads from the configured passive sources. Invalid options are reported by Err after the first Next returns false. WithBus requires NewClient; use Client.Scanner for a custom bus.
Example ¶
The Scanner API is an alternative to the iterator.
package main
import (
"context"
"fmt"
"log"
"github.com/open-ships/n2k"
)
func main() {
ctx := context.Background()
scanner := n2k.NewScanner(ctx, n2k.File("testdata/sample.log"))
messages := 0
for scanner.Next() {
messages++
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded over 900 messages: %t\n", messages > 900)
}
Output: decoded over 900 messages: true
func (*Scanner) Close ¶ added in v0.3.0
Close stops the scanner and releases its source or live-client subscription. It waits for source cleanup, is safe concurrently with Next, and may be called more than once, including before the first Next.
type SerialDevice ¶ added in v1.1.0
type SerialDevice struct {
Name string
IsUSB bool
VID string
PID string
SerialNumber string
Product string
}
SerialDevice describes one OS serial port. USB identity fields are populated when the platform exposes them.
func SerialDevices ¶ added in v1.1.0
func SerialDevices() ([]SerialDevice, error)
SerialDevices enumerates serial ports using the host operating system.
type StreamFormat ¶
type StreamFormat int
StreamFormat identifies the wire format spoken by a network gateway.
const ( // FormatYDRaw is the Yacht Devices RAW ASCII line protocol (YDWG-02 and // compatible gateways). FormatYDRaw StreamFormat = iota // FormatActisense is the Actisense binary stream protocol (NGT-1 and // compatible gateways). BST-93 messages arrive fully assembled and retain // the gateway's source identity. This format is a gateway-owned message // session; prefer FormatActisenseRaw for a source-authoritative Client. FormatActisense // FormatActisenseRaw exchanges source-authoritative CAN frames using // BST-95. TCP and Serial sessions select and acknowledge operating mode 5; // UDP expects an upstream gateway already configured for BST-95. A writable // session that rejects or strips BEM setup fails rather than falling back. FormatActisenseRaw // FormatActisenseCANASCII selects acknowledged operating mode 6 and carries // source-authoritative CAN frames as human-readable lines. Binary BEM // control replies may be interleaved with the ASCII stream. FormatActisenseCANASCII // FormatActisenseN2KASCII reads gateway-assembled Type-A NMEA 2000 // messages. Like FormatActisense, it is not a source-authoritative Bus. FormatActisenseN2KASCII )
type WriteError ¶ added in v1.3.0
WriteError retains transmission uncertainty. CompletedRecords counts atomic transport records: CAN frames for a Bus, whole messages for MessageWriter. It does not imply application-level acceptance by a remote device. An error after any physical write attempt is conservative: callers must decide whether resending is appropriate.
func (*WriteError) Error ¶ added in v1.3.0
func (e *WriteError) Error() string
Error returns the underlying write failure text. Partial-transmission evidence is available in CompletedRecords and TransmissionUncertain.
func (*WriteError) Unwrap ¶ added in v1.3.0
func (e *WriteError) Unwrap() error
Unwrap exposes the underlying failure for errors.Is and errors.As.
type WriteResult ¶
type WriteResult struct {
// contains filtered or unexported fields
}
WriteResult represents the outcome of an asynchronous write operation. The zero value is safe to use and behaves as a completed, successful write.
func (*WriteResult) Done ¶
func (r *WriteResult) Done() <-chan struct{}
Done returns a channel that is closed when the write is complete. On a zero-value WriteResult, Done returns an already-closed channel.
func (*WriteResult) Wait ¶
func (r *WriteResult) Wait() error
Wait blocks until the write is complete, then returns the error (or nil). On a zero-value WriteResult, Wait returns nil immediately.
func (*WriteResult) WaitContext ¶ added in v0.3.0
func (r *WriteResult) WaitContext(ctx context.Context) error
WaitContext waits for completion or returns when ctx is done. Cancelling ctx does not cancel a write that has already reached the bus.
Source Files
¶
- actisense_ascii.go
- actisense_error.go
- actisense_gateway_remote.go
- actisense_remote.go
- actisense_send.go
- actisense_serial.go
- actisense_session.go
- actisense_types.go
- broadcast.go
- bus.go
- client.go
- devicename.go
- ebl_writer.go
- filter.go
- groupfunction.go
- heartbeat.go
- isorequest.go
- message_snapshot.go
- messagehub.go
- n2k.go
- network_session.go
- observation.go
- observationhub.go
- options.go
- pipeline.go
- productinfo.go
- protocoltx.go
- registry.go
- replay_capture.go
- request.go
- scanner.go
- source.go
- source_ebl.go
- source_file.go
- source_net.go
- source_serial.go
- status.go
- system.go
- transmission.go
- writeresult.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
conformance
command
Command conformance executes public software evidence.
|
Command conformance executes public software evidence. |
|
pgngen
command
|
|
|
roundtrip
command
Command roundtrip replays a candump log (candump -L / -l format) through the n2k decode pipeline and verifies that every decoded message re-encodes back to the bytes that were on the wire.
|
Command roundtrip replays a candump log (candump -L / -l format) through the n2k decode pipeline and verifies that every decoded message re-encodes back to the bytes that were on the wire. |
|
internal
|
|
|
actisense
Package actisense implements the bounded BDTP, BST, BEM, and EBL wire protocols used by Actisense-format gateways.
|
Package actisense implements the bounded BDTP, BST, BEM, and EBL wire protocols used by Actisense-format gateways. |
|
adapter
Package adapter implements the adapter for raw CAN bus frame endpoints.
|
Package adapter implements the adapter for raw CAN bus frame endpoints. |
|
canbus
Package canbus is built around the Channel structure, which represents a single canbus channel for sending/receiving CAN frames.
|
Package canbus is built around the Channel structure, which represents a single canbus channel for sending/receiving CAN frames. |
|
candump
Package candump parses candump -L / -l log lines into CAN frames.
|
Package candump parses candump -L / -l log lines into CAN frames. |
|
claiming
Package claiming implements the NMEA 2000 / ISO 11783 address claiming protocol (PGN 60928).
|
Package claiming implements the NMEA 2000 / ISO 11783 address claiming protocol (PGN 60928). |
|
conformance
Package conformance links public requirement claims to discoverable Go tests and records their executable outcomes.
|
Package conformance links public requirement claims to discoverable Go tests and records their executable outcomes. |
|
decoder
Package decoder converts input messages to an intermediate (Packet) form, and outputs equivalent golang structs.
|
Package decoder converts input messages to an intermediate (Packet) form, and outputs equivalent golang structs. |
|
ebl
Package ebl reads bounded Enhanced Binary Log capture streams.
|
Package ebl reads bounded Enhanced Binary Log capture streams. |
|
framer
Package framer builds CAN frames from encoded PGN payloads.
|
Package framer builds CAN frames from encoded PGN payloads. |
|
gateway
Package gateway parses the wire formats spoken by NMEA 2000 network gateways: the Yacht Devices RAW ASCII line protocol and the Actisense binary stream protocol.
|
Package gateway parses the wire formats spoken by NMEA 2000 network gateways: the Yacht Devices RAW ASCII line protocol and the Actisense binary stream protocol. |
|
serialio
Package serialio opens serial ports with interruptible reads and writes.
|
Package serialio opens serial ports with interruptible reads and writes. |
|
transport
Package transport implements ISO 11783 Transport Protocol for NMEA 2000 messages that exceed 8 bytes and cannot use fast-packet encoding.
|
Package transport implements ISO 11783 Transport Protocol for NMEA 2000 messages that exceed 8 bytes and cannot use fast-packet encoding. |
|
Package pgn converts NMEA 2000 messages to strongly typed Go data.
|
Package pgn converts NMEA 2000 messages to strongly typed Go data. |
|
Package raw defines owned observations from NMEA 2000 transport adapters.
|
Package raw defines owned observations from NMEA 2000 transport adapters. |
|
Package units provides type-safe unit conversion for physical quantities commonly encountered in marine (NMEA 2000) and general-purpose sensor systems.
|
Package units provides type-safe unit conversion for physical quantities commonly encountered in marine (NMEA 2000) and general-purpose sensor systems. |