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
- Variables
- func CheckCompat(s *Status) error
- func CompatWarning(s *Status) string
- func IsFatal(err error) bool
- func IsHidden(p Path) bool
- func IsProtected(p Path) bool
- func IsRetryable(err error) bool
- func KnownModel(model string) bool
- func ParseDeviceError(msg string) error
- type Client
- func (c *Client) CachedStatus() *Status
- func (c *Client) Delete(ctx context.Context, p Path) error
- func (c *Client) DeleteMany(ctx context.Context, paths []Path) error
- func (c *Client) Download(ctx context.Context, p Path) (io.ReadCloser, error)
- func (c *Client) Host() string
- func (c *Client) List(ctx context.Context, p Path) ([]FileEntry, error)
- func (c *Client) ListRecursive(ctx context.Context, root Path) (map[Path]FileEntry, error)
- func (c *Client) Mkdir(ctx context.Context, p Path) error
- func (c *Client) MkdirAll(ctx context.Context, p Path) error
- func (c *Client) Move(ctx context.Context, from, to Path) error
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) Rename(ctx context.Context, p Path, newName string) error
- func (c *Client) Stat(ctx context.Context, p Path) (FileEntry, error)
- func (c *Client) Status(ctx context.Context) (*Status, error)
- func (c *Client) Upload(ctx context.Context, dest Path, r io.Reader, size int64, opts UploadOptions) error
- type Discovered
- type FileEntry
- type Option
- type Path
- type Progress
- type Status
- type UploadOptions
- type Version
Constants ¶
const ( HTTPPort = 80 WebSocketPort = 81 DiscoveryPort = 8134 )
Default ports, from the firmware's documented network surface.
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.
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.
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.
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".
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 ¶
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 ¶
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 ¶
CompatWarning returns a non-fatal note when the firmware differs from the pinned version within a supported major, or "" when it matches.
func IsFatal ¶
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 ¶
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 ¶
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 ¶
IsRetryable reports whether an operation is worth attempting again.
func KnownModel ¶
KnownModel reports whether the model string is one shelf has a profile for.
func ParseDeviceError ¶
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 ¶
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 ¶
Resolve turns a configured host into a reachable client, discovering the device when no host is set.
func (*Client) CachedStatus ¶
CachedStatus returns the most recent status poll, if any.
func (*Client) DeleteMany ¶
DeleteMany removes several paths in one request.
func (*Client) List ¶
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 ¶
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) Rename ¶
Rename renames a file. The firmware supports this for files only, not folders.
func (*Client) Status ¶
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 ¶
Discovered is a device found on the network.
func Discover ¶
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 ¶
WithHTTPClient overrides the underlying HTTP client, for tests.
func WithTimeout ¶
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 (Path) Ancestors ¶
Ancestors returns every parent directory from shallowest to deepest, excluding the root and the path itself.
func (Path) Depth ¶
Depth counts path components, used to order mkdir operations so that parents are created before their children.
func (Path) Fold ¶
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.
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 ¶
Version is a parsed semantic firmware version.
func ParseVersion ¶
ParseVersion parses a firmware version string, tolerating a leading "v" and a missing patch component.