connectionmgr

package
v0.0.0-...-bc887ed Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RespNone                   uint8 = iota // no response expected; do not read anything
	RespStatusOnly                          // after response header: int32 status
	RespStatusAndLPBytes                    // after response header: int32 status + uint32 len + len bytes
	RespStatusAndU32                        // after response header: int32 status + uint32 id/handle
	RespStatusAndU32AndLPBytes              // (rare) if you ever need it; keep available
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BinaryHeader

type BinaryHeader struct {
	ClientID uint16
	Opcode   uint8
	Dev      uint8
	Code     int32
}

======================= Binary protocol header =======================

Wire format (network / big-endian):

uint16 client_id
uint8  op
uint8  dev
int32  code

type ClientInfo_type

type ClientInfo_type struct {
	Version    string
	XMLcontext sdrxml.SDRContext
}

type Manager

type Manager struct {
	Address string
	Mode    Mode

	Timeout    time.Duration
	Logger     *log.Logger
	ClientInfo ClientInfo_type
	// contains filtered or unexported fields
}

func New

func New(addr string) *Manager

func (*Manager) Close

func (m *Manager) Close() error

func (*Manager) CloseBufferASCII

func (m *Manager) CloseBufferASCII(deviceID string) error

CloseBufferASCII issues the ASCII CLOSE command to release a buffer. It returns nil on success or an error when the manager is not in ASCII mode, the command fails, or the server replies with a negative errno.

func (*Manager) Connect

func (m *Manager) Connect() error

func (*Manager) DrainASCII

func (m *Manager) DrainASCII() error

The following helpers are expected to exist in your ascii.go. If you don't have them, implement them there (NOT duplicated elsewhere):

- func (m *Manager) ExecASCII(cmd string) (int, error) // write cmd + CRLF, read integer header - func (m *Manager) readInteger() (int, error) // reads one integer line - func (m *Manager) readLine(maxLen int) ([]byte, error) // reads one line (ending in \n) - func (m *Manager) writeLine(cmd string) error // writes cmd + "\r\n" - func (m *Manager) writeAll(b []byte) error // writes all bytes DrainASCII consumes any pending bytes from the ASCII connection using a short read deadline. It is intended to realign the stream after a protocol error. The method returns nil on timeout (meaning drained) or propagates socket errors otherwise.

func (*Manager) EnterBinaryMode

func (m *Manager) EnterBinaryMode() error

EnterBinaryMode sends the BINARY command and marks the Manager as binary-only. After a successful switch, ASCII helpers must not be used.

func (*Manager) EnterBinaryMode3

func (m *Manager) EnterBinaryMode3() error

func (*Manager) ExecASCII

func (m *Manager) ExecASCII(cmd string) (int, error)

ExecASCII forwards to ExecCommand; it exists for callers that still use the legacy ASCII helper name.

func (*Manager) ExecCommand

func (m *Manager) ExecCommand(cmd string) (int, error)

ExecCommand writes an ASCII command line (adding CRLF if missing), then reads the server's integer status line.

Parameters:

  • cmd: the ASCII command to send (for example TIMEOUT, PRINT, OPEN, CLOSE).

Behavior:

  • refuses to run when the manager is disconnected or already in binary mode, because ASCII bootstrap commands are not valid there.
  • sends the command verbatim (ensuring a trailing CRLF) and returns the integer parsed from the next line of the stream.

Returns:

  • the integer status/value reported by the device (0 for success or negative errno codes) or an error if the socket write/read fails.

func (*Manager) FetchXML

func (m *Manager) FetchXML() ([]byte, error)

FetchXML sends PRINT and returns the XML payload.

func (*Manager) GetBufAttr

func (m *Manager) GetBufAttr(dev uint8, name string) (string, error)

func (*Manager) GetChnAttrIdx

func (m *Manager) GetChnAttrIdx(dev uint8, chIdx int32, attr string) (string, error)

func (*Manager) GetContextXMLASCII

func (m *Manager) GetContextXMLASCII() ([]byte, error)

GetContextXMLASCII issues PRINT to fetch the XML context over ASCII. The protocol returns the byte length on the first line followed by the XML and a trailing newline delimiter, which this helper trims before returning.

func (*Manager) GetContextXMLCompressedASCII

func (m *Manager) GetContextXMLCompressedASCII() ([]byte, error)

GetContextXMLCompressedASCII issues ZPRINT to fetch a zlib-compressed XML context. The method trims the newline delimiter, inflates the payload, and returns the decompressed XML bytes.

func (*Manager) GetGainControlMode

func (m *Manager) GetGainControlMode(dev uint8, idx uint8) (string, error)

func (*Manager) GetRFBandwidth

func (m *Manager) GetRFBandwidth(dev uint8, idx uint8) (int64, error)

func (*Manager) GetSamplingFrequency

func (m *Manager) GetSamplingFrequency(dev uint8, idx uint8) (int64, error)

func (*Manager) GetTriggerASCII

func (m *Manager) GetTriggerASCII(deviceID string) (string, error)

GetTriggerASCII fetches the active trigger name for a device using the ASCII GETTRIG command.

Protocol:

  • issues "GETTRIG <deviceID>\r\n".
  • reads the subsequent integer length using readInteger().
  • reads exactly length+1 bytes (payload plus trailing newline) using readLine, trimming trailing whitespace from the result.

Returns the trimmed trigger name or an error for validation failures, negative lengths, or IO errors.

func (*Manager) GetVersionASCII

func (m *Manager) GetVersionASCII() (string, error)

GetVersionASCII sends VERSION and returns the version string directly. Unlike other IIOD commands, VERSION returns the version string as-is, not as a length-prefixed payload.

func (*Manager) GetXML

func (m *Manager) GetXML(dev uint8) ([]byte, error)

func (*Manager) HelpASCII

func (m *Manager) HelpASCII() (string, error)

HelpASCII sends HELP and returns the help text directly. Unlike commands like PRINT, HELP returns the help text as-is, not as a length-prefixed payload.

func (*Manager) HelpfunctionASCII

func (m *Manager) HelpfunctionASCII() error

HelpfunctionASCII is retained for callers using the legacy name. It delegates to HelpASCII and drops the payload.

func (*Manager) OpenBufferASCII

func (m *Manager) OpenBufferASCII(
	deviceID string,
	samples uint64,
	maskHex string,
	cyclic bool,
) error

OpenBufferASCII sends the ASCII OPEN command to allocate a buffer.

Parameters:

  • deviceID: IIO device identifier (for example "cf-ad9361-lpc").
  • samples: number of samples per buffer.
  • maskHex: channel mask as a hex string (e.g. "ffffffff" or "00000003").
  • cyclic: whether to request a cyclic buffer.

Protocol:

  • issues "OPEN <deviceID> <samples> <maskHex>[ CYCLIC]\r\n" and expects an integer response.

Returns nil on success or an error when not in ASCII mode, the command fails to send, or the response is a negative errno code.

func (*Manager) PrimeCTX

func (m *Manager) PrimeCTX(dev uint8) ([]byte, error)

func (*Manager) Print

func (m *Manager) Print(dev uint8) ([]byte, error)

func (*Manager) PrintASCII

func (m *Manager) PrintASCII() ([]byte, error)

PrintASCII is retained for callers using the legacy name. It delegates to GetContextXMLASCII and returns the payload.

func (*Manager) ReadBufferASCII

func (m *Manager) ReadBufferASCII(deviceID string, dst []byte) (int, error)

ReadBufferASCII reads raw bytes from an open buffer using the READBUF command.

Parameters:

  • deviceID: IIO device identifier.
  • dst: caller-provided byte slice to fill.

Protocol (legacy ASCII):

READBUF <dev> <len>\r\n
-> integer N (chunk bytes)
   if N > 0: then N bytes of binary payload follow immediately
   if N == 0: end
   if N < 0: error (negative errno)

The method consumes the announced mask line, reads exactly N bytes into dst (erroring when dst is too small), and then drains the trailing newline to keep the stream aligned. It returns the number of bytes copied into dst or an error when the mode is incorrect, IO fails, or the server returns a negative errno.

func (*Manager) ReadBufferASCIIWithMask

func (m *Manager) ReadBufferASCIIWithMask(deviceID string, dst []byte) (int, string, error)

ReadBufferASCIIWithMask reads raw bytes from an open buffer using the READBUF command and returns the channel mask string announced by the server.

func (*Manager) ReadBufferAttrASCII

func (m *Manager) ReadBufferAttrASCII(devID, attr string) (string, error)

ReadBufferAttrASCII reads a buffer attribute through the ASCII protocol.

Parameters:

  • devID: device identifier string.
  • attr: buffer attribute name to read.

Protocol:

  • issues "READ <devID> BUFFER <attr>\r\n" and expects the next line to contain the attribute value.

Returns the trimmed attribute string or an error if validation, write, or read fails.

func (*Manager) ReadByte

func (m *Manager) ReadByte() error

func (*Manager) ReadChannelAttrASCII

func (m *Manager) ReadChannelAttrASCII(devID string, isOutput bool, chanID, attr string) (string, error)

ReadChannelAttrASCII reads a channel attribute through the ASCII protocol.

Parameters:

  • devID: device identifier string.
  • isOutput: whether the channel direction is OUTPUT (INPUT otherwise).
  • chanID: channel identifier (for example "voltage0").
  • attr: attribute name to read.

Protocol:

  • issues "READ <devID> INPUT|OUTPUT <chanID> <attr>\r\n" and reads one payload line containing the value.

Returns the trimmed attribute string or an error if validation, write, or read fails.

func (*Manager) ReadChannelAttrASCII2

func (m *Manager) ReadChannelAttrASCII2(
	dev string,
	isOutput bool,
	channel string,
	attr string,
) (string, int, error)

ReadChannelAttrASCII2 mirrors ReadChannelAttrASCII but also returns the raw status code. This helper is retained for callers that need to differentiate transport errors from device-side errno returns until they migrate to the newer API.

func (*Manager) ReadDeviceAttrASCII

func (m *Manager) ReadDeviceAttrASCII(devID, attr string) (string, error)

ReadDeviceAttrASCII sends a legacy ASCII READ for a device-level attribute.

Parameters:

  • devID: device identifier string (for example "ad9361-phy").
  • attr: attribute name to read.

Protocol:

  • issues "READ <devID> <attr>\r\n" and expects the next line to contain the attribute value.

Returns the trimmed attribute string or an error if the manager is not connected, parameters are missing, or the server returns an invalid payload.

func (*Manager) SetBufAttr

func (m *Manager) SetBufAttr(dev uint8, name, value string) error

func (*Manager) SetChannelEnabledASCII

func (m *Manager) SetChannelEnabledASCII(devID string, isOutput bool, chanID, attrName string, enabled bool) error

SetChannelEnabledASCII toggles a channel-enable style attribute via ASCII WRITE. The caller specifies attrName explicitly because attribute naming conventions vary (for example "en", "enabled", or scan_elements "<chan>_en"). Non-zero statuses are reported as errors.

func (*Manager) SetClientID

func (m *Manager) SetClientID(id uint16)

SetClientID overrides the libiio client identifier used in binary headers.

func (*Manager) SetConn

func (m *Manager) SetConn(conn net.Conn)

Safe reinjection (tests, SSH tunnels, etc.)

func (*Manager) SetHardwareGainDBASCII

func (m *Manager) SetHardwareGainDBASCII(devID string, isOutput bool, chanID string, gainDB float64) error

SetHardwareGainDBASCII writes a gain value using ASCII WRITE. The attribute is often named "hardwaregain" and may exist on RX or TX channels depending on the device. The helper formats the float without trailing zeros and reports non-zero statuses as errors.

func (*Manager) SetKernelBuffersCountASCII

func (m *Manager) SetKernelBuffersCountASCII(deviceID string, count int) error

SetKernelBuffersCountASCII configures the number of kernel buffers for a device using the ASCII SET command.

Protocol:

  • issues "SET <deviceID> BUFFERS_COUNT <count>\r\n" via ExecASCII.
  • non-negative return codes indicate success; negative errno values are surfaced as errors.

Parameters:

  • deviceID: IIO device identifier (for example "cf-ad9361-lpc").
  • count: desired number of kernel buffers; must be zero or positive.

Returns nil on success or an error for validation failures, transport errors, or negative device responses.

func (*Manager) SetLOFrequencyHzASCII

func (m *Manager) SetLOFrequencyHzASCII(devID string, isOutput bool, chanID string, hz int64) error

SetLOFrequencyHzASCII writes the LO frequency attribute using ASCII WRITE.

The caller supplies the exact device/channel/attribute triplet expected by the target XML (for example dev="ad9361-phy", chan="altvoltage0", attr="frequency"). A non-zero response status is surfaced as an error so callers see device-side errno codes.

func (*Manager) SetLogger

func (m *Manager) SetLogger(l *log.Logger)

func (*Manager) SetSampleRateHzASCII

func (m *Manager) SetSampleRateHzASCII(devID string, isOutput bool, chanID string, hz int64) error

SetSampleRateHzASCII writes the sampling rate via ASCII WRITE. Attribute names depend on the backend (commonly "sampling_frequency"). Non-zero device responses are returned as errors.

func (*Manager) SetTimeout

func (m *Manager) SetTimeout(d time.Duration)

func (*Manager) SetTimeoutASCII

func (m *Manager) SetTimeoutASCII(timeoutMs int) error

SetTimeoutASCII configures the server-side socket timeout using the ASCII TIMEOUT command.

Protocol:

  • issues "TIMEOUT <timeoutMs>\r\n" and reads the following integer status.
  • a zero or positive status indicates success; negative values mirror errno codes and are treated as errors.

Parameters:

  • timeoutMs: timeout in milliseconds. Negative values are rejected before issuing the command.

Returns nil on success or an error for validation failures, transport errors, or negative device statuses.

func (*Manager) SetTriggerASCII

func (m *Manager) SetTriggerASCII(deviceID, triggerName string) error

SetTriggerASCII selects a trigger using the ASCII SETTRIG command. An empty triggerName clears the trigger configuration when supported by the device. Negative device responses are returned as errors.

func (*Manager) StartStreamASCII

func (m *Manager) StartStreamASCII(parent context.Context, cfg StreamASCIIConfig) (*StreamASCIIHandle, error)

StartStreamASCII runs a continuous READBUF loop on an already-open Manager connection.

Parameters:

  • parent: context to cancel streaming.
  • cfg: StreamASCIIConfig describing device ID, READBUF length, backpressure behavior, and optional per-chunk deadline overrides.

Protocol:

  • repeatedly issues READBUF <deviceID> <len>\r\n and consumes the integer size plus payload for each iteration.

Returns a handle that can stop the goroutine and expose the first error encountered (transport failures or a negative errno surfaced by ReadBufferASCII). The caller must have completed ASCII bootstrap steps (e.g. TIMEOUT, PRINT/XML, OPEN) before starting.

func (*Manager) SwitchToBinary

func (m *Manager) SwitchToBinary() error

SwitchToBinary attempts the ASCII "BINARY" mode switch and drains the response stream. Modern servers start in ASCII mode automatically; callers should transition to binary helpers after this call succeeds. Any socket error is returned.

func (*Manager) TryUpgradeToBinary

func (m *Manager) TryUpgradeToBinary() (bool, error)

TryUpgradeToBinary sends BINARY and switches mode on success.

func (*Manager) VersionASCII

func (m *Manager) VersionASCII() error

VersionASCII is retained for callers using the legacy name. It delegates to GetVersionASCII and drops the payload.

func (*Manager) WriteBufferASCII

func (m *Manager) WriteBufferASCII(deviceID string, payload []byte) (int, error)

WriteBufferASCII writes raw bytes to an open buffer using the WRITEBUF command.

Parameters:

  • deviceID: IIO device identifier.
  • payload: raw bytes to stream to the device.

Protocol (legacy ASCII):

WRITEBUF <dev> <bytes>\r\n
<- integer N (bytes accepted)

The method streams the payload via writeAll, then parses the returned integer status. Negative statuses are surfaced as errors. If the server reports a positive byte count that does not match the payload length, the partial write count is returned alongside an error to keep the stream aligned for the next command.

func (*Manager) WriteBufferAttrASCII

func (m *Manager) WriteBufferAttrASCII(devID, attr string, payload []byte) (int, error)

WriteBufferAttrASCII writes a buffer attribute via the ASCII protocol.

Parameters:

  • devID: device identifier string (for example "cf-ad9361-lpc").
  • attr: buffer attribute name to write.
  • payload: raw bytes to send verbatim (no implicit newline).

Protocol:

  • issues "WRITE <devID> BUFFER <attr> <len>\r\n" then streams <len> raw payload bytes using writeAll.
  • reads the integer status line via readInteger; negative statuses are surfaced as errors while still returning the raw status value.

Returns the integer status (0 or positive) or an error if validation, socket IO, or a negative status occurs.

func (*Manager) WriteChannelAttrASCII

func (m *Manager) WriteChannelAttrASCII(devID string, isOutput bool, chanID, attr, value string) (int, error)

WriteChannelAttrASCII writes a channel attribute (INPUT or OUTPUT) via ASCII WRITE.

Parameters mirror WriteDeviceAttrASCII but include the channel identifier and direction flag.

Protocol:

  • issues "WRITE <devID> INPUT|OUTPUT <chanID> <attr> <len>\r\n" then sends <len> raw bytes, and finally reads the integer status line.

Returns the integer status or an error if validation or socket IO fails.

func (*Manager) WriteDebugAttrASCII

func (m *Manager) WriteDebugAttrASCII(devID, attr string, payload []byte) (int, error)

WriteDebugAttrASCII writes a debug attribute using the ASCII protocol.

Parameters:

  • devID: device identifier string.
  • attr: debug attribute name to write.
  • payload: raw bytes to write (no automatic newline is appended).

Protocol:

  • issues "WRITE <devID> DEBUG <attr> <len>\r\n" and immediately streams <len> raw payload bytes via writeAll.
  • parses the following integer status line and surfaces negative statuses as errors.

Returns the integer status (zero or positive) or an error if validation, IO, or a negative status occurs.

func (*Manager) WriteDeviceAttrASCII

func (m *Manager) WriteDeviceAttrASCII(devID, attr, value string) (int, error)

WriteDeviceAttrASCII writes a device attribute using the ASCII protocol.

Parameters:

  • devID: device identifier string.
  • attr: attribute name to write.
  • value: raw payload written without an automatic newline.

Protocol:

  • issues "WRITE <devID> <attr> <len>\r\n" followed by <len> raw bytes.
  • reads the following integer status (0 for success, negative errno on failure).

Returns the integer status or an error if validation or socket IO fails.

func (*Manager) ZPrintASCII

func (m *Manager) ZPrintASCII() error

ZPrintASCII is retained for callers using the legacy name. It delegates to GetContextXMLCompressedASCII and drops the payload.

type Mode

type Mode int
const (
	ModeASCII Mode = iota
	ModeBinary
)

type ResponsePlan

type ResponsePlan struct {
	ExpectHeader bool
	Opcode       uint8
	Shape        uint8
}

ResponsePlan describes what (if anything) should be read after the 8-byte response header.

type StreamASCIIConfig

type StreamASCIIConfig struct {
	DeviceID string

	// BytesPerRead is the READBUF length argument. Example: 65536.
	// Keep this reasonably sized (64KiB..1MiB) to avoid latency spikes.
	BytesPerRead int

	// Out is where raw payload chunks are delivered.
	// Backpressure: if the channel is full, streaming blocks unless DropIfFull is true.
	Out chan<- []byte

	// DropIfFull: if true, drop a frame when Out is full (instead of blocking).
	DropIfFull bool

	// CopyOut: if true, each delivered chunk is copied to a fresh slice
	// so the caller can retain it. If false, delivered slices may be reused.
	// In practice, keep this true unless you implement a pool in the consumer.
	CopyOut bool

	// ReadTimeoutPerChunk overrides socket read deadline per READBUF transaction (optional).
	// If zero, Manager.Timeout is used.
	ReadTimeoutPerChunk time.Duration

	// LogPrefix is included in logs for correlation.
	LogPrefix string
}

StreamASCIIConfig controls continuous streaming via legacy ASCII READBUF.

type StreamASCIIHandle

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

StreamASCIIHandle controls a running stream.

func (*StreamASCIIHandle) Err

func (h *StreamASCIIHandle) Err() error

func (*StreamASCIIHandle) Stop

func (h *StreamASCIIHandle) Stop()

Jump to

Keyboard shortcuts

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