device

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 17 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 talks to a CrossPoint e-reader over its HTTP and WebSocket interfaces.

The firmware runs on an ESP32-C3 with roughly 380 KB of usable RAM and accepts exactly one upload at a time. Every design choice here follows from that: transfers are serialized behind a mutex owned by the client rather than the caller, chunks are small, and retries are conservative.

Index

Constants

View Source
const (
	HTTPPort      = 80
	WebSocketPort = 81
	DiscoveryPort = 8134
)

Default ports, from the firmware's documented network surface.

View Source
const (
	// TestedVersion is the firmware shelf has been exercised against on real
	// hardware (an X4 reporting 1.4.1).
	TestedVersion = "1.4.1"

	// MinMajor and MaxMajor bound the accepted major version.
	MinMajor = 1
	MaxMajor = 1
)

Firmware compatibility.

CrossPoint is under heavy development. shelf pins the version it has been tested against and gates on the reported version string, failing loudly on an unknown major rather than guessing at a changed protocol. When a new major ships, re-verify the endpoints in docs/webserver-endpoints.md and bump MaxMajor here rather than removing the check.

View Source
const (
	ModelX3 = "X3"
	ModelX4 = "X4"
)

Known device models. The status API exposes no serial number or MAC, only this string, which is why shelf assigns its own identity in /shelf/device.json.

View Source
const (
	MinChunkSize     = 4 * 1024
	MaxChunkSize     = 15 * 1024
	DefaultChunkSize = 8 * 1024
)

Chunk size bounds.

These are lower than the spec's suggested 16 KB default and 64 KB ceiling, because the device rejects both. The firmware builds against links2004/WebSockets 2.7.3, whose WEBSOCKETS_MAX_DATA_SIZE defaults to 15 KB; a larger frame is refused with a StatusMessageTooBig close and the upload fails outright.

Measured on an X4 running 1.4.1: 12288 uploads cleanly, 16384 is rejected every time. The default is 8 KB rather than something nearer the limit because the ESP32-C3 has roughly 380 KB of usable heap and writes through a 4 KB buffer, so headroom matters more than frame count.

View Source
const ModeLocal = "SD"

ModeLocal is the Mode a filesystem-backed transport reports.

The firmware only ever reports "STA" or "AP", so this cannot collide with a real device. It is how CheckCompat tells "no firmware in play" apart from "firmware that failed to report a version".

View Source
const SettingsEndpointUnsafe = true

Known firmware hazards, observed on real hardware rather than in the docs.

GET /api/settings CRASHES an X4 running 1.4.1.

Observed directly: a single `curl http://<device>/api/settings` returned no bytes, hung until timeout, and rebooted the device out of File Transfer mode. The on-device crash report carried an EMPTY panic reason, a stack that was almost entirely zeros, and last-logs containing only post-reboot hardware detection -- the signature of a hard fault or watchdog reset rather than a caught error. The device had ~87 KB free heap and a -90 dBm link at the time, so low memory may be a contributing factor, but the endpoint streams its JSON response and is the prime suspect on its own.

Consequences for shelf:

  • Nothing in shelf calls /api/settings, and `shelf doctor` does not probe it.
  • The settings screen planned in the spec must not be built on this endpoint until the crash is understood and fixed upstream.
  • Any future caller should treat a settings fetch as able to take the device down mid-sync, which would also abort an in-flight upload.

Worth reporting to the firmware project with the crash dump.

Variables

View Source
var (
	// ErrUploadInProgress means another upload is already running. The device
	// accepts exactly one at a time, globally.
	ErrUploadInProgress = errors.New("device: upload already in progress")

	// ErrDiskFull aborts an entire sync run rather than just the current file.
	ErrDiskFull = errors.New("device: SD write failed, likely full")

	// ErrInvalidStart means a malformed START frame or an invalid size.
	ErrInvalidStart = errors.New("device: invalid START frame")

	// ErrCreateFailed means the device could not open the destination file.
	ErrCreateFailed = errors.New("device: could not create file")

	// ErrNoUpload means binary data arrived without a preceding START.
	ErrNoUpload = errors.New("device: no upload in progress")

	// ErrOverflow means more bytes were sent than the START frame declared.
	ErrOverflow = errors.New("device: upload overflow")

	// ErrChunkTooBig means an upload frame exceeded what the device accepts.
	//
	// The firmware closes the connection with StatusMessageTooBig rather than
	// sending an ERROR frame, so this is detected from the close status. It is
	// a configuration problem with an obvious fix, and worth saying so plainly
	// rather than surfacing as a generic lost connection.
	ErrChunkTooBig = errors.New("device: upload chunk too large")

	// ErrProtectedPath covers the paths shelf must never write to.
	ErrProtectedPath = errors.New("device: protected path")

	// ErrNotInTransfer is the single most common failure in practice: the
	// device is asleep or not in File Transfer mode. It is deliberately
	// distinct from a generic timeout so the UI can say something useful.
	ErrNotInTransfer = errors.New("device: not in file transfer mode (is it awake and in File Transfer or Calibre Wireless mode?)")

	// ErrNotFound is returned for a missing device path.
	ErrNotFound = errors.New("device: path not found")

	// ErrMkdirFailed is returned when the firmware refuses to create a folder.
	//
	// Observed on an X4 running 1.4.1: every /mkdir call answers
	// "Failed to create folder" while the SD card is unmounted, even though
	// /api/status reports the device as perfectly healthy. If this appears for
	// every path, suspect the card rather than the path.
	ErrMkdirFailed = errors.New("device: could not create folder")

	// ErrUnsupportedFirmware is returned when the firmware major version is
	// outside the range shelf has been tested against.
	ErrUnsupportedFirmware = errors.New("device: unsupported firmware version")
)

Typed errors, mapped from the firmware's exact response strings.

The strings below are copied verbatim from the CrossPoint firmware's docs/webserver-endpoints.md. They are matched as substrings because the device prefixes WebSocket failures with "ERROR:" and returns bare text over HTTP, and because a future firmware may add punctuation. Any change to these literals is a compatibility break and belongs in compat.go.

Functions

func CheckCompat

func CheckCompat(s *Status) error

CheckCompat validates a device's reported status against what shelf supports.

An unknown major is an error rather than a warning: the endpoints, the WebSocket framing, and the on-device cache layout could all have changed, and guessing risks writing garbage onto someone's library.

func CompatWarning

func CompatWarning(s *Status) string

CompatWarning returns a non-fatal note when the firmware differs from the pinned version within a supported major, or "" when it matches.

func IsFatal

func IsFatal(err error) bool

IsFatal reports whether an error should abort an entire sync run rather than just the current file. A full SD card will not fix itself by moving to the next book, so continuing would produce a long run of identical failures.

func IsHidden

func IsHidden(p Path) bool

IsHidden reports whether the final component is a dotfile. The firmware omits these from listings unless showHiddenFiles is enabled, which is why shelf keeps its own state in a visible /shelf directory.

func IsProtected

func IsProtected(p Path) bool

IsProtected reports whether a path lies inside a reserved area.

This is checked at the lowest layer, immediately before a request is built, so that no caller anywhere in shelf can reach a protected path by constructing one itself.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether an operation is worth attempting again.

func KnownModel

func KnownModel(model string) bool

KnownModel reports whether the model string is one shelf has a profile for.

func ParseDeviceError

func ParseDeviceError(msg string) error

ParseDeviceError maps a device message to a typed error.

The original message is preserved in the wrapped error so that an unrecognized failure is still reported verbatim rather than swallowed.

Types

type Client

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

Client talks to one device.

func New

func New(host string, opts ...Option) *Client

New creates a client for a device reachable at host, which may be a bare hostname, an IP, or either with a port.

func Resolve

func Resolve(ctx context.Context, host string, opts ...Option) (*Client, error)

Resolve turns a configured host into a reachable client, discovering the device when no host is set.

func (*Client) CachedStatus

func (c *Client) CachedStatus() *Status

CachedStatus returns the most recent status poll, if any.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, p Path) error

Delete removes a file. The firmware refuses non-empty directories.

func (*Client) DeleteMany

func (c *Client) DeleteMany(ctx context.Context, paths []Path) error

DeleteMany removes several paths in one request.

func (*Client) Download

func (c *Client) Download(ctx context.Context, p Path) (io.ReadCloser, error)

Download fetches a file's contents. The caller closes the reader.

func (*Client) Host

func (c *Client) Host() string

Host returns the configured host.

func (*Client) List

func (c *Client) List(ctx context.Context, p Path) ([]FileEntry, error)

List returns the contents of a device directory.

A missing directory is not an error on real hardware: firmware 1.4.1 answers 200 with an empty array rather than 404. The 404 branch below is kept for other firmware revisions, but callers must not rely on ErrNotFound to detect a missing directory -- use Stat against the parent instead.

func (*Client) ListRecursive

func (c *Client) ListRecursive(ctx context.Context, root Path) (map[Path]FileEntry, error)

ListRecursive walks a device directory tree, returning every file with its full path. Directories that cannot be read are skipped rather than aborting the walk.

func (*Client) Mkdir

func (c *Client) Mkdir(ctx context.Context, p Path) error

Mkdir creates a directory on the device.

func (*Client) MkdirAll

func (c *Client) MkdirAll(ctx context.Context, p Path) error

MkdirAll creates a directory and any missing parents, shallowest first.

func (*Client) Move

func (c *Client) Move(ctx context.Context, from, to Path) error

Move moves a file to a new path.

func (*Client) Ping

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

Ping reports whether the device is reachable and in transfer mode.

func (*Client) Rename

func (c *Client) Rename(ctx context.Context, p Path, newName string) error

Rename renames a file. The firmware supports this for files only, not folders.

func (*Client) Stat

func (c *Client) Stat(ctx context.Context, p Path) (FileEntry, error)

Stat returns the entry for a single device path.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (*Status, error)

Status polls the device.

A connection failure here is reported as ErrNotInTransfer rather than a raw network error, because that is nearly always what it means: the device is asleep or not in File Transfer mode.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, dest Path, r io.Reader, size int64, opts UploadOptions) error

Upload transfers a file to the device.

Uploads are serialized here rather than in the caller. The firmware accepts exactly one at a time and rejects a second with "Upload already in progress", so holding the lock in the client means no caller anywhere can violate that invariant, including a future concurrent sync planner.

type Discovered

type Discovered struct {
	Hostname string
	Addr     string // IP address that answered
	WSPort   int
}

Discovered is a device found on the network.

func Discover

func Discover(ctx context.Context, timeout time.Duration) ([]Discovered, error)

Discover broadcasts a discovery request on every suitable interface and collects replies until the context expires or timeout elapses.

Every interface is enumerated rather than sending a single datagram to 255.255.255.255, because a global broadcast is silently dropped on macOS when the route is ambiguous, which is exactly the multi-interface case a laptop is usually in.

func (Discovered) Host

func (d Discovered) Host() string

Host returns the address to build a client from.

type FileEntry

type FileEntry struct {
	Name        string `json:"name"`
	Size        int64  `json:"size"`
	IsDirectory bool   `json:"isDirectory"`
	IsEpub      bool   `json:"isEpub"`
}

FileEntry is one item from GET /api/files.

Note what is absent: no modification time and no checksum. Change detection must never depend on either.

type Option

type Option func(*Client)

Option configures a Client.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient overrides the underlying HTTP client, for tests.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the overall request timeout.

type Path

type Path string

Path is a path on the device.

It is a distinct type from a local filesystem path on purpose. Device paths are always forward-slash separated regardless of the host OS, so joining one with filepath.Join would silently produce backslashes on some platforms and corrupt the request. The type makes that a compile error instead.

func NewPath

func NewPath(p string) Path

NewPath normalizes a device path: absolute, forward-slash, no trailing slash.

func (Path) Ancestors

func (p Path) Ancestors() []Path

Ancestors returns every parent directory from shallowest to deepest, excluding the root and the path itself.

func (Path) Base

func (p Path) Base() string

Base returns the final element.

func (Path) Depth

func (p Path) Depth() int

Depth counts path components, used to order mkdir operations so that parents are created before their children.

func (Path) Dir

func (p Path) Dir() Path

Dir returns the parent directory.

func (Path) Fold

func (p Path) Fold() string

Fold returns a case-folded, NFC-normalized form for collision detection.

The device's SD card is FAT32, which is case-insensitive regardless of the host, so "Moby-Dick.epub" and "moby-dick.epub" are one file there even on a Linux workstation where they coexist happily. NFC is applied for the same reason paths are normalized everywhere else: APFS hands back NFD, and two spellings of the same name must fold together.

This matches library.FoldPath deliberately. The two run on opposite ends of the pipeline -- import decides what a local file is named, the planner decides where it lands -- and they have to agree on what a collision is.

func (Path) Join

func (p Path) Join(elems ...string) Path

Join appends elements to a device path.

func (Path) String

func (p Path) String() string

String renders the path.

type Progress

type Progress struct {
	Path  Path
	Sent  int64
	Total int64
}

Progress reports upload advancement.

func (Progress) Percent

func (p Progress) Percent() float64

Percent returns completion as a percentage, or 0 for an unknown total.

type Status

type Status struct {
	Version  string `json:"version"`
	IP       string `json:"ip"`
	Mode     string `json:"mode"` // STA or AP
	RSSI     int    `json:"rssi"` // dBm; 0 in AP mode
	FreeHeap int64  `json:"freeHeap"`
	Uptime   int64  `json:"uptime"`
	Device   string `json:"device"` // X3 or X4
}

Status is the response from GET /api/status.

type UploadOptions

type UploadOptions struct {
	// ChunkSize is clamped to [MinChunkSize, MaxChunkSize].
	ChunkSize int
	// Progress, when set, is called as the device acknowledges bytes.
	Progress func(Progress)
	// ForceHTTP skips the WebSocket path entirely.
	ForceHTTP bool
}

UploadOptions tunes a single transfer.

type Version

type Version struct {
	Major, Minor, Patch int
	Raw                 string
}

Version is a parsed semantic firmware version.

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion parses a firmware version string, tolerating a leading "v" and a missing patch component.

func (Version) String

func (v Version) String() string

String renders the version.

Jump to

Keyboard shortcuts

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