device

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package device tracks transports discovered by the local operating system.

A Registry records discovery independently from terminal Sessions. Discovering an endpoint never opens it or creates a Session; callers must make that separate, explicit decision.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilScanner is returned when a Registry cannot enumerate local devices.
	ErrNilScanner = errors.New("device scanner must not be nil")
	// ErrRegistryStarted is returned when Start is called more than once.
	ErrRegistryStarted = errors.New("device registry is already started")
	// ErrRegistryClosed is returned when Start is called after Close.
	ErrRegistryClosed = errors.New("device registry is closed")
	// ErrInvalidReadLimit is returned when an event read requests no events.
	ErrInvalidReadLimit = errors.New("device event read limit must be positive")
)
View Source
var (
	// ErrUnsupportedStateVersion is returned when a state file requires a
	// migration that this Core does not implement. The file is left unchanged.
	ErrUnsupportedStateVersion = errors.New("unsupported state version")
)

Functions

This section is empty.

Types

type Cursor

type Cursor uint64

Cursor identifies the next device event expected by a consumer.

type Device

type Device struct {
	DeviceID       string
	IdentityMethod IdentityMethod
	Persistent     bool
	Transport      string
	Endpoint       string
	State          State
	Metadata       SerialMetadata
	FirstSeen      time.Time
	LastSeen       time.Time
}

Device is the Registry record for an endpoint discovered during this process.

FirstSeen is retained for the process lifetime. LastSeen is refreshed by each successful scan that reports the endpoint. Current listings contain only StatePresent devices; disappeared records are retained internally so a later reappearance can produce a new EventAppeared transition.

type Endpoint

type Endpoint struct {
	Transport string
	Endpoint  string
	Metadata  SerialMetadata
}

Endpoint is the minimal, runtime-only identity produced by a Scanner.

Transport names the transport family, such as "serial". Endpoint is the platform endpoint accepted by that transport, such as "COM8" or "/dev/ttyUSB0". Neither field identifies a physical device across runs.

type Event

type Event struct {
	Timestamp time.Time
	Type      EventType
	Transport string
	Endpoint  string
}

Event records one device-presence transition after Registry initialization.

type EventChunk

type EventChunk struct {
	Events  []Event
	Next    Cursor
	Dropped bool
}

EventChunk is a bounded, caller-owned event snapshot.

type EventType

type EventType string

EventType identifies a discovery state transition.

const (
	// EventAppeared records an endpoint first seen after Registry initialization,
	// or seen again after it disappeared.
	EventAppeared EventType = "appeared"
	// EventDisappeared records an endpoint absent from a successful later scan.
	EventDisappeared EventType = "disappeared"
)

type Identity

type Identity struct {
	DeviceID   string
	Method     IdentityMethod
	Persistent bool
}

Identity is the identity result exposed by the Device Registry.

type IdentityMethod

type IdentityMethod string

IdentityMethod explains the evidence used to assign a DeviceID.

USBSerial is device-level when the adapter supplies a serial number. USBPath is only location-level: it identifies a class of device at one physical USB position. Runtime has no durable matching evidence and is process-local.

const (
	// IdentityUSBSerial identifies an adapter using transport, VID, PID, and a
	// non-empty USB serial number.
	IdentityUSBSerial IdentityMethod = "usb_serial"
	// IdentityUSBPath identifies an adapter location using transport, VID, PID,
	// and USB path only when the adapter has no USB serial number.
	IdentityUSBPath IdentityMethod = "usb_path"
	// IdentityRuntime identifies an endpoint that lacks enough metadata for a
	// durable identity. Its DeviceID is deliberately not written to state.json.
	IdentityRuntime IdentityMethod = "runtime"
)

type Registry

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

Registry stores local device presence and a bounded event stream.

Start establishes its initial scan as a baseline: endpoints present at startup are listed but deliberately do not produce appeared events. Every later successful scan emits only state transitions. Registry has no dependency on Session, Transport opening, or connection configuration.

func NewRegistry

func NewRegistry(scanner Scanner) (*Registry, error)

NewRegistry creates an unstarted Registry with the normal low-cost scan interval.

func NewRegistryWithStateStore

func NewRegistryWithStateStore(scanner Scanner, store *StateStore) (*Registry, error)

NewRegistryWithStateStore creates an unstarted Registry that assigns device identities through store. The Store must already have loaded valid state; failure to persist a newly discovered stable identity makes that scan fail so callers do not observe an identity that cannot survive a Core restart.

func (*Registry) Close

func (r *Registry) Close()

Close stops periodic scanning and releases pending event readers.

func (*Registry) List

func (r *Registry) List() []Device

List returns currently present devices in stable transport and endpoint order.

func (*Registry) Read

func (r *Registry) Read(ctx context.Context, next Cursor, limit int) (EventChunk, error)

Read waits for device events from next, returning at most limit events.

ctx cancellation or deadline ends the wait promptly. Dropped is true when next predates the bounded event retention window; callers should resume from Next without assuming they observed every older transition.

func (*Registry) ReadRecent

func (r *Registry) ReadRecent(limit int) (EventChunk, error)

ReadRecent returns the newest retained device events without waiting.

func (*Registry) Start

func (r *Registry) Start(ctx context.Context) error

Start establishes the initial presence baseline and starts periodic scans.

ctx controls Registry lifetime. Its cancellation stops background scans and wakes pending Read calls with io.EOF after retained events are consumed. A failed initial scan is returned and leaves the Registry unstarted, so callers never mistake an incomplete baseline for confirmed device presence.

type Scanner

type Scanner interface {
	Scan(ctx context.Context) ([]Endpoint, error)
}

Scanner enumerates endpoints without opening them.

ctx cancellation or deadline must stop the scan where the platform API makes that possible. A failed scan does not change Registry presence state, avoiding false disappearance events from temporary enumeration failures.

type ScannerFunc

type ScannerFunc func(context.Context) ([]Endpoint, error)

ScannerFunc adapts a function to Scanner.

func (ScannerFunc) Scan

func (f ScannerFunc) Scan(ctx context.Context) ([]Endpoint, error)

Scan enumerates endpoints through f.

type SerialMetadata

type SerialMetadata struct {
	VID          string
	PID          string
	USBSerial    string
	Manufacturer string
	Product      string
	USBPath      string
}

SerialMetadata is best-effort USB and hardware information for a serial endpoint. Empty fields are normal for non-USB controllers and devices that omit optional descriptors. VID and PID use four lowercase hexadecimal digits when present; this metadata is not a stable device identity.

type State

type State string

State describes whether an endpoint is present in the most recent successful scan.

const (
	// StatePresent identifies an endpoint reported by the most recent scan.
	StatePresent State = "present"
	// StateDisappeared identifies an endpoint removed by a later successful scan.
	StateDisappeared State = "disappeared"
)

type StateDevice

type StateDevice struct {
	DeviceID     string        `json:"device_id"`
	Transport    string        `json:"transport"`
	Identity     StateIdentity `json:"identity"`
	LastEndpoint string        `json:"last_endpoint"`
	CreatedAt    time.Time     `json:"created_at"`
	UpdatedAt    time.Time     `json:"updated_at"`
}

StateDevice is one ChannelTerm-managed durable device identity.

LastEndpoint is an observation for display and diagnostics. It never takes part in matching, because COM and tty names may be reassigned by the OS.

type StateFile

type StateFile struct {
	Version int           `json:"version"`
	Devices []StateDevice `json:"devices"`
}

StateFile is the versioned JSON schema stored in state.json.

type StateIdentity

type StateIdentity struct {
	VID          string `json:"vid"`
	PID          string `json:"pid"`
	USBSerial    string `json:"usb_serial"`
	USBPath      string `json:"usb_path"`
	Manufacturer string `json:"manufacturer,omitempty"`
	Product      string `json:"product,omitempty"`
}

StateIdentity is the matching evidence persisted for one managed device. Manufacturer and Product are diagnostic snapshots only; neither participates in matching because descriptions are not reliable unique identifiers.

type StateStore

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

StateStore owns ChannelTerm's local durable device identity mapping.

Its mutex protects matching and the subsequent atomic replacement so two concurrent scans cannot create duplicate records. One Core instance owns the file; v0.1 intentionally does not implement a cross-process file lock.

func LoadStateStore

func LoadStateStore(path string) (*StateStore, error)

LoadStateStore opens path, or creates an empty version-1 state file when it does not exist. Invalid JSON and unsupported versions are returned as clear errors without changing the original file.

func (*StateStore) Resolve

func (s *StateStore) Resolve(endpoints []Endpoint, observedAt time.Time) (map[string]Identity, error)

Resolve assigns identities for one successful scan. Persistent state is written once only if a durable record is created or its snapshot changes; unchanged periodic scans perform no disk writes.

Jump to

Keyboard shortcuts

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