protocol

package module
v0.0.0-...-ddf2205 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 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 protocol is the wire format between an FTW box and its clients: the message names and shapes, the CBOR envelope, the names generated from contract/registry.yaml, the history tile geometry and the push catalogue.

It holds shapes and pure functions, and it imports nothing from the box. A program that only speaks the protocol, such as FTW Cloud, therefore links no control, planner or storage code; CI checks that with go list -deps. What a message means to the box — what a hello_ok says, when a command may be dispatched — stays in the box's go/internal/appproto. The bytes underneath — frame header, bucket padding and the Noise session — belong to package appwire, which this package reaches through the narrow FrameCodec interface below.

Every age is measured against the box's uptime, never its wall clock. A Pi has no RTC and reads 1970 until NTP answers, so a wall-clock age would be wrong by decades exactly when a user is looking at it after a power cut.

Index

Constants

View Source
const (
	MsgAgentInviteCreate          = "agent.invite.create"
	MsgAgentInviteList            = "agent.invite.list"
	MsgAgentInviteCancel          = "agent.invite.cancel"
	AgentInviteSecretBytes        = 32
	AgentInviteRowsMax            = 16
	AgentInviteClaimMaxMs   int64 = 24 * 60 * 60 * 1000
	AgentInviteHandshakeMax       = 8192
)
View Source
const (
	AgentAPIReadTimeout = 5 * time.Minute // Large exports may need more time than a status read.
	AgentAPIMaxBytes    = 1 << 20         // Complete JSON wire answer, including escaped text.
	AgentAPIPageBytes   = 128 << 10       // Source bytes per page; not a total data limit.
	AgentAPICatalogPath = "/api/diagnostics/catalog"
)
View Source
const (
	MsgApprovalKeySet = "approval.key.set"
	MsgAgentAdd       = "agent.add"
	MsgAgentWiden     = "agent.widen"
	MsgAgentRevoke    = "agent.revoke"
	MsgAgentList      = "agent.list"
	MsgAgentRequest   = "agent.request"
	MsgAgentConfirm   = "agent.confirm"
	MsgAgentOK        = "agent.ok"
	// MsgAgentDecided tells an agent's open session how its request ended.
	MsgAgentDecided = "agent.decided"
	MsgAuditGet     = "audit.get"

	MsgHealthGet = "health.get"
	MsgHealth    = "health"
	MsgEventsGet = "events.get"
	MsgEvents    = "events"
	MsgLogsGet   = "logs.get"
	MsgLogs      = "logs"
	MsgConfigGet = "config.get"
	MsgConfig    = "config"
	MsgDiagRun   = "diag.run"
	MsgDiag      = "diag"

	// The typed reads, whose answers name nothing. live, loadpoints and
	// cars carry FTW Cloud's class bodies (cloudwire.Live, LP and Cars)
	// with the box's agent ids in place of the copy's.
	MsgLiveGet       = "live.get"
	MsgLive          = "live"
	MsgLoadpointsGet = "loadpoints.get"
	MsgLoadpoints    = "loadpoints"
	MsgCarsGet       = "cars.get"
	MsgCars          = "cars"
	MsgDriversGet    = "drivers.get"
	MsgDrivers       = "drivers"
)

Agent message types. Each request gets MsgAgentOK or MsgError with its id.

View Source
const (
	RequestPending  = "pending"
	RequestApproved = "approved"
	RequestDeclined = "declined"
	RequestExpired  = "expired"
)

Request states.

View Source
const (
	// AgentMaxMs, SupportMaxMs and ReleaseMaxMs are the longest grants.
	// The box tells owners its own in agent.list, as LongestMs.
	AgentMaxMs   int64 = 365 * 24 * 60 * 60 * 1000
	SupportMaxMs int64 = 14 * 24 * 60 * 60 * 1000
	ReleaseMaxMs int64 = 90 * 24 * 60 * 60 * 1000

	// AgentRowsMax is how many agent rows one box holds.
	AgentRowsMax = 16

	HoldSMin  = 60
	HoldSMax  = 1800
	MaxWMin   = 1
	MaxWMax   = 100_000
	PerMinMin = 1
	PerMinMax = 60
	// PerMinDefault is the rate a grant that names none gets.
	PerMinDefault = 6
	// ReadsPerMin is the box's own limit on an agent's reads.
	ReadsPerMin = 60

	// PendingPerAgent and PendingPerBox bound the requests waiting for an
	// owner. A request lives RequestTTLMs and is kept RequestKeptMs after
	// it ends, so the agent can read how it ended.
	PendingPerAgent       = 4
	PendingPerBox         = 16
	RequestTTLMs    int64 = 12 * 60 * 60 * 1000
	RequestKeptMs   int64 = 24 * 60 * 60 * 1000
	RequestArgsMax        = 1024
	RequestWhyMax         = 280

	// ApprovalSkewMs is how far an approval's atMs may stray from the box's
	// wall clock, and ApprovalReplayMs how long the box remembers one it took.
	ApprovalSkewMs   int64 = 10 * 60 * 1000
	ApprovalReplayMs int64 = 20 * 60 * 1000

	// LogsLinesMax bounds logs.get; the answer also fits one bulk frame.
	LogsLinesMax  = 200
	EventsMax     = 50
	AuditPageMax  = 200
	AuditRowsKept = 10_000
	AuditDaysKept = 90
	// ByMax bounds the staff id a support call carries.
	ByMax = 64
	// ReqIDBytes is a request id's randomness: 128 bits.
	ReqIDBytes = 16
	// OfferTTLMs is the longest a signed offer may live.
	OfferTTLMs int64 = 10 * 60 * 1000
	// PrincipalFieldMax bounds each principal field.
	PrincipalFieldMax = 256
)

Limits the box enforces on every grant, whatever the grant says.

View Source
const (
	// OpCarGoalSet sets how and when a car charges. Args: id (the car) or
	// charger_id (a visitor's session); target, a fraction from 0 to 1, and
	// ready_by_min, with days and finish_at_limit, which together replace
	// the goal; clear, true to remove it; and surplus_only. The goal and
	// surplus_only are each optional: one that is absent stays as it was.
	OpCarGoalSet = "car.goal.set"
	// OpCarSoCSet sets a car's level by hand. Args: id or charger_id, and
	// soc, a fraction from 0 to 1.
	OpCarSoCSet = "car.soc.set"
	// OpSessionCarSet says which car is on a charger: the one tap. Args: id
	// (the charger), session (the plug-in's id) and car_id. An empty car_id
	// makes the session a visitor's.
	OpSessionCarSet = "session.car.set"
	// OpCarAdd adds a car. Args: id, which the owner's app mints, and the
	// car's own fields without the level. An id the box has is an update.
	OpCarAdd = "car.add"
	// OpCarUpdate changes a car. Args: id and the fields that change;
	// new_id re-keys a car the box minted to the id the owner's app holds.
	OpCarUpdate = "car.update"
	// OpCarRemove removes a car. Args: id. A session on it becomes a
	// visitor's, and the box keeps the id as removed.
	OpCarRemove = "car.remove"
)

Operations on cars. Their scopes are in contract/registry.yaml `ops`. Arguments follow the box's convention: snake_case, `id` for what the op acts on, a level as a fraction from 0 to 1.

View Source
const (
	CapStatusCore      = "status.core"
	CapStatusPhases    = "status.phases"
	CapStatusDrivers   = "status.drivers"
	CapHistory5m       = "history.5m"
	CapHistory1h       = "history.1h"
	CapHistoryEtag     = "history.etag"
	CapCmdLease        = "cmd.lease"
	CapCmdPrecondition = "cmd.precondition"
	CapCmdReadback     = "cmd.readback"
	CapDerBattery      = "der.battery"
	CapDerEv           = "der.ev"
	CapDerV2x          = "der.v2x"
	CapPlanDispatch    = "plan.dispatch"
	CapNetWebrtc       = "net.webrtc"
	CapPriceSpot       = "price.spot"
	CapApiPassthrough  = "api.passthrough"
	CapCloudLink       = "cloud.link"
	CapCloudTun        = "cloud.tun"
	CapCmdExchange     = "cmd.exchange"
	CapAccessAgents    = "access.agents"
	CapAccessInvites   = "access.invites"
	CapDerCar          = "der.car"
)

Capabilities are presence, not levels. An app hides what is absent and never compares versions.

View Source
const (
	// ScopeLiveRead — Current readings and freshness.
	ScopeLiveRead = "ftw.live.read"
	// ScopeHistoryRead — Stored history.
	ScopeHistoryRead = "ftw.history.read"
	// ScopePlanRead — Dispatch plan and its reasoning.
	ScopePlanRead = "ftw.plan.read"
	// ScopeHealthRead — Box and driver health.
	ScopeHealthRead = "ftw.health.read"
	// ScopeAssetsRead — Devices and their capabilities.
	ScopeAssetsRead = "ftw.assets.read"
	// ScopeEventsRead — Events behind notifications.
	ScopeEventsRead = "ftw.events.read"
	// ScopeDispatchWrite — Control energy assets.
	ScopeDispatchWrite = "ftw.dispatch.write"
	// ScopeModeWrite — Change site operating mode.
	ScopeModeWrite = "ftw.mode.write"
	// ScopeMembersRead — See who has access.
	ScopeMembersRead = "ftw.members.read"
	// ScopeMembersWrite — Invite and revoke.
	ScopeMembersWrite = "ftw.members.write"
	// ScopeLogsRead — Log excerpts the box redacts.
	ScopeLogsRead = "ftw.logs.read"
	// ScopeConfigRead — Configuration the box redacts.
	ScopeConfigRead = "ftw.config.read"
	// ScopeDiagRun — Full technical diagnostics and read API.
	ScopeDiagRun = "ftw.diag.run"
	// ScopeSetupWrite — Save confirmed system setup and restart to apply it after user confirmation.
	ScopeSetupWrite = "ftw.setup.write"
	// ScopeDispatchHold — Hold energy assets for a capped time.
	ScopeDispatchHold = "ftw.dispatch.hold"
	// ScopeGoalsRequest — Ask an owner to change a durable goal.
	ScopeGoalsRequest = "ftw.goals.request"
	// ScopeUpdateRequest — Ask an owner to install a version.
	ScopeUpdateRequest = "ftw.update.request"
	// ScopeCarsRead — See the owner's cars with their VINs and identifiers and sources.
	ScopeCarsRead = "ftw.cars.read"
	// ScopeCarsWrite — Keep the owner's list of cars.
	ScopeCarsWrite = "ftw.cars.write"
)

Scopes are an object and a verb. Roles are a projection over these, never a replacement for them.

View Source
const (
	// RoleAgent — Assistant.
	RoleAgent = "agent"
	// RoleOwner — Owner.
	RoleOwner = "owner"
	// RoleRelease — Release check.
	RoleRelease = "release"
	// RoleSupport — Sourceful support.
	RoleSupport = "support"
	// RoleViewer — Viewer.
	RoleViewer = "viewer"
	// RoleWatch — Watch.
	RoleWatch = "watch"
)

Roles, as the registry names them. apiauth holds what each carries.

View Source
const (
	CloudPurposeServe = "serve"
	CloudPurposeStats = "stats"
)

What an FTW Cloud grant lets the service use the data for.

View Source
const (
	CloudTransportQuic      = "quic"
	CloudTransportWebsocket = "websocket"
)

What a session with FTW Cloud travels over, under its carrier.

View Source
const (
	// ErrBooting — Box is starting up.
	ErrBooting = "E_BOOTING"
	// ErrUnknownOp — Message type not understood.
	ErrUnknownOp = "E_UNKNOWN_OP"
	// ErrCmdExpired — Command outlived not_valid_after_ms.
	ErrCmdExpired = "E_CMD_EXPIRED"
	// ErrPrecondition — Guard failed against fresh state.
	ErrPrecondition = "E_PRECONDITION"
	// ErrConflict — expect.rev did not match.
	ErrConflict = "E_CONFLICT"
	// ErrScopeDenied — Grant lacks the required scope.
	ErrScopeDenied = "E_SCOPE_DENIED"
	// ErrGrantRevoked — Access was withdrawn.
	ErrGrantRevoked = "E_GRANT_REVOKED"
	// ErrLastOwnerProtected — Cannot remove the only owner.
	ErrLastOwnerProtected = "E_LAST_OWNER_PROTECTED"
	// ErrRangeTooLarge — History window exceeds the limit.
	ErrRangeTooLarge = "E_RANGE_TOO_LARGE"
	// ErrUnavailable — Source or subsystem is down.
	ErrUnavailable = "E_UNAVAILABLE"
	// ErrNeedsStepUp — Request needs a fresh passkey ceremony.
	ErrNeedsStepUp = "E_NEEDS_STEP_UP"
	// ErrUseCmd — Route moves energy and belongs on cmd.
	ErrUseCmd = "E_USE_CMD"
	// ErrUnsupportedMedia — Answer is not a kind the session carries.
	ErrUnsupportedMedia = "E_UNSUPPORTED_MEDIA"
	// ErrWholeDocument — Route replaces a whole document rather than part of one.
	ErrWholeDocument = "E_WHOLE_DOCUMENT"
	// ErrLocalOnly — Route is served only on the box's own page.
	ErrLocalOnly = "E_LOCAL_ONLY"
	// ErrGrantExpired — Access ran out at its expiry.
	ErrGrantExpired = "E_GRANT_EXPIRED"
	// ErrOpNotGranted — The grant does not list this operation.
	ErrOpNotGranted = "E_OP_NOT_GRANTED"
	// ErrCapExceeded — An argument or a count is past its cap.
	ErrCapExceeded = "E_CAP_EXCEEDED"
	// ErrRateLimited — Too many commands for the grant's rate.
	ErrRateLimited = "E_RATE_LIMITED"
	// ErrNeedsOwner — A durable change waits for an owner as agent.request.
	ErrNeedsOwner = "E_NEEDS_OWNER"
	// ErrBadSignature — The approval signature is missing or does not verify.
	ErrBadSignature = "E_BAD_SIGNATURE"
	// ErrNoApprovalKey — This phone has no approval key on the box.
	ErrNoApprovalKey = "E_NO_APPROVAL_KEY"
	// ErrNotFound — Nothing by that id or name.
	ErrNotFound = "E_NOT_FOUND"
	// ErrClockSkew — The approval's time is too far from the box's.
	ErrClockSkew = "E_CLOCK_SKEW"
	// ErrDuplicate — Another car already has that VIN or identifier.
	ErrDuplicate = "E_DUPLICATE"
)

Error codes. The box sends the code and machine-readable args; the app owns every word of prose, in every language it ships.

View Source
const (
	CarSoCVehicle = "vehicle"
	CarSoCManual  = "manual"
	CarSoCAssumed = "assumed"
)

Where a car's level comes from: the registry's car_soc_sources.

View Source
const (
	CarIdentifiedByCharger = "charger"
	CarIdentifiedByCar     = "car"
	CarIdentifiedByOnly    = "only"
	CarIdentifiedByTap     = "tap"
	CarIdentifiedByAsking  = "asking"
	CarIdentifiedByNone    = "none"
)

How the box knows which car is on a charger: the registry's car_identified_by.

View Source
const (
	// ProtoMin is the oldest version this box will speak at all.
	ProtoMin = 0
	// ProtoMax is the newest.
	ProtoMax = 1
	// ProtoFloor is the frozen subset: fields 1-9 and nothing else. An app
	// too old for full mode still draws the core view here instead of
	// showing a white screen, which is what a hard version wall would give
	// anyone whose service worker pinned an old bundle.
	ProtoFloor = 0
)

Protocol versions. The client sends a range; the box picks min(box max, client max) and degrades rather than refusing.

View Source
const (
	LaneControl uint8 = 0
	LaneBulk    uint8 = 1
)

Lanes. Lane 0 is one fixed bucket for the life of a session, because a frame size that varies with what happened in the house leaks the household's load pattern through otherwise perfect encryption. Over the relay it also goes at a fixed cadence; through FTW Cloud each reading goes as it lands (docs/protocol-cloud.md, "Tunnel"). Anything whose size depends on what the box supports goes on lane 1.

View Source
const (
	MsgHello            = "hello"
	MsgHelloOK          = "hello_ok"
	MsgSub              = "sub"
	MsgSnap             = "snap"
	MsgDelta            = "delta"
	MsgTick             = "tick"
	MsgPlanGet          = "plan.get"
	MsgPlan             = "plan"
	MsgCmd              = "cmd"
	MsgCmdAck           = "cmd.ack"
	MsgCmdResult        = "cmd.result"
	MsgEvent            = "event"
	MsgError            = "error"
	MsgSessionTerminate = "session.terminate"
	MsgPriceGet         = "price.get"
	MsgPrice            = "price"
	MsgHistQuery        = "hist.query"
	MsgHistChunk        = "hist.chunk"
	MsgHistEnd          = "hist.end"
	MsgAPIReq           = "api.req"
	MsgAPIHead          = "api.head"
	MsgAPIChunk         = "api.chunk"
	MsgAPIEnd           = "api.end"
	// MsgNow is a watch's read of the home over the exchange, and the box's
	// answer to it (ADR 0009). The same type both ways, as tick is.
	MsgNow = "now"
)

Message type strings. Stable for the life of the protocol.

View Source
const (
	// OpSetMode changes the site operating mode. It goes through the same
	// mode validation the API and Home Assistant use — a second validator
	// here would be a second place for the two to disagree.
	OpSetMode = "site.mode.set"
	// OpPlannerPrefsSet stores the household safety factor and battery-export
	// permission. The box maps that permission onto a planner mode; the
	// caller does not name the mode.
	OpPlannerPrefsSet = "planner.prefs.set"
	// OpSiteTimeZonePropose offers the client's time zone as the household
	// clock. The box stores it only while it keeps no zone of its own, and
	// restarts to run on it; a box that keeps one answers E_PRECONDITION
	// with the zone it keeps in args.tz.
	OpSiteTimeZonePropose = "site.time_zone.propose"
	// OpLoadpointHold pins one EV loadpoint to a fixed charging power, or
	// releases it with `clear`. The same manual hold the HTTP route
	// installs, reached through this door's gates instead of a verb.
	OpLoadpointHold = "loadpoint.hold"
	// OpLoadpointBoost lets the house battery boost the car under a bounded
	// lease, or withdraws it with `cancel`. Same lease and same preflight
	// as the HTTP route.
	OpLoadpointBoost = "loadpoint.boost"
	// OpLoadpointSoCSet corrects the car's current state of charge, a
	// fraction in [0,1], the way POST /api/loadpoints/{id}/soc does: the
	// session's estimate is re-anchored and the plan remade from it.
	OpLoadpointSoCSet = "loadpoint.soc.set"
	// OpLoadpointSurplusOnlySet turns PV-only charging on or off for one
	// loadpoint — the `surplus_only` field of the HTTP target route, and
	// only that field: the target level and its deadline have no command.
	OpLoadpointSurplusOnlySet = "loadpoint.surplus_only.set"
)

Operations a client may ask for, from contract/registry.yaml `ops` — the scope each demands lives there too, and TestRegistryOpsMatchCommandTable reads the pair back against defaultOps().

View Source
const (
	BootPhaseVacuum  = "vacuum"
	BootPhaseMigrate = "migrate"
	BootPhaseDrivers = "drivers"
)

Boot phases.

View Source
const (
	GuardLT  = "lt"
	GuardLTE = "lte"
	GuardGT  = "gt"
	GuardGTE = "gte"
)

Guard comparison operators.

View Source
const (
	CmdApplied     = "applied"
	CmdRejected    = "rejected"
	CmdExpired     = "expired"
	CmdSuperseded  = "superseded"
	CmdUnconfirmed = "unconfirmed"
)

Command outcomes.

View Source
const (
	GapNoData  = "no_data"
	GapEvicted = "evicted"
	GapBoxDown = "box_down"
)

Gap reasons, as the app spells them.

View Source
const (
	APIGet    = "GET"
	APIHead   = "HEAD"
	APIPost   = "POST"
	APIPut    = "PUT"
	APIPatch  = "PATCH"
	APIDelete = "DELETE"
)

Methods the passthrough carries.

View Source
const (
	TerminateRevoked      = "revoked"
	TerminateEpochChanged = "epoch_changed"
	TerminateBoxShutdown  = "box_shutdown"
	TerminateSuperseded   = "superseded"
)

Termination reasons.

View Source
const (
	PushChargingConnected       = "charging.connected"
	PushChargingSessionComplete = "charging.session_complete"
	PushChargingGoalAtRisk      = "charging.goal_at_risk"
	PushChargingInterrupted     = "charging.interrupted"
	PushUpdateAvailable         = "update.available"
	PushUpdateInstalled         = "update.installed"
	PushDriverOffline           = "driver.offline"
	PushFuseOverLimit           = "fuse.over_limit"
	PushControlNotFollowing     = "control.not_following"
	PushBoxUnreachable          = "box.unreachable"
	PushCloudGranted            = "cloud.granted"
	PushCloudRevoked            = "cloud.revoked"
	PushAgentAdded              = "agent.added"
	PushAgentRequest            = "agent.request"
	PushAgentExpiring           = "agent.expiring"
	PushApprovalKeySet          = "approval.key.set"
	PushOwnerAdded              = "owner.added"
	PushCarWhich                = "car.which"
)

Push event kinds. Hand-writing one of these strings is what the catalogue exists to stop.

View Source
const ApprovalPubBytes = 65

ApprovalPubBytes is a SEC1 uncompressed P-256 point.

View Source
const ApprovalSigBytes = 64

ApprovalSigBytes is r ‖ s, 32 bytes each.

View Source
const ApprovalTag = "ftw.approval.v1"

ApprovalTag starts every signed array, so a signature for anything else is never one of these.

View Source
const CarEstimateAfterWh = 1000

CarEstimateAfterWh is how much energy may flow after a reading before the box counts the level as an estimate. It replaces a time limit: a reading with nothing delivered since is as true after nine minutes as after one.

View Source
const ContractVersion = 1

ContractVersion is the registry revision these names came from.

View Source
const FlagTrunc uint8 = 0x02

FlagTrunc says the delta did not fit its bucket. The rest follows on the next tick or as a fresh snapshot on the bulk lane; the bucket never grows.

View Source
const GrantOfferVersion = 1

GrantOfferVersion is GrantOffer.V.

View Source
const HintAppUpdate = "app_update"

HintAppUpdate tells the app it is behind. It is a hint, not an error: the session still works, on the frozen subset.

View Source
const MissingSample = math.MinInt32

MissingSample marks a hole on the wire. Distinct from zero, which is a real reading. Same value as the app's MISSING_SAMPLE.

View Source
const MsgAPIRead = "api.read"
View Source
const MsgSetupCommit = "setup.commit"
View Source
const MsgSetupEdit = "setup.edit"
View Source
const MsgSetupReset = "setup.reset"
View Source
const MsgSetupRestart = "setup.restart"
View Source
const MsgSetupSchema = "setup.schema"
View Source
const MsgSetupStatus = "setup.status"
View Source
const MsgSetupValidate = "setup.validate"
View Source
const ObservedSrcCore = "core"

ObservedSrcCore names the box itself as the source of a read-back value, for state the box holds rather than a device reports.

View Source
const OfferTag = "ftw.offer.v1"

OfferTag starts what an offer key signs.

View Source
const PushCatalogueVersion = 1

PushCatalogueVersion is the catalogue revision these sentences came from.

View Source
const SetupRequestBytes = 10 << 10

A patch fits one padded bulk envelope. JSON Patch operations edit a list entry without resending siblings; the box holds the complete draft.

View Source
const SupportClientID = "https://cloud.ftw.energy/clients/sourceful-support"

SupportClientID is the one client a support offer may come from: the support tooling's client at FTW Cloud.

View Source
const TerminateExpired = "expired"

TerminateExpired ends an agent's session when its grant runs out.

Variables

View Source
var (
	ErrOfferSignature = errors.New("protocol: the offer is not signed by a pinned offer key")
	ErrOfferExpired   = errors.New("protocol: the offer has expired")
	ErrOfferShape     = errors.New("protocol: the offer is malformed")
)

Errors from reading a signed offer.

View Source
var (
	ErrApprovalUnsorted  = errors.New("protocol: a signed list must be sorted with no repeats")
	ErrApprovalPub       = errors.New("protocol: approval key is not an uncompressed P-256 point")
	ErrApprovalSignature = errors.New("protocol: approval signature does not verify")
)

Errors from checking a signed body's shape. A signature that does not verify is ErrApprovalSignature.

AllCapabilities is every capability name the registry defines.

View Source
var BulkBuckets = []int{1024, 4096, 16384}

Bulk bucket sizes, smallest first.

View Source
var CarFields = []string{
	"id",
	"boxMinted",
	"ownerId",
	"name",
	"make",
	"vin",
	"capacityWh",
	"maxW",
	"phases",
	"socPermille",
	"socSource",
	"socAgeS",
	"energySinceWh",
	"socEstimate",
	"chargeLimitPermille",
	"goal",
	"goal.targetPermille",
	"goal.readyByMin",
	"goal.days",
	"goal.finishAtLimit",
	"surplusOnly",
	"identifiers",
	"sources",
}

CarFields is every name in the registry's car_fields. A dotted name is a field of the object before the dot.

View Source
var ChargerCarFields = []string{
	"session",
	"carId",
	"carIdentifiedBy",
	"carCorrected",
	"carCorrectedFrom",
	"choose",
}

ChargerCarFields is every name in the registry's charger_car_fields. A dotted name is a field of the object before the dot.

CloudPurposes is every purpose an FTW Cloud grant may name.

CloudScopes are the scopes an FTW Cloud grant may name.

CloudTransports lists them in the registry's order.

View Source
var ErrAgentInvite = errors.New("protocol: invalid agent invitation")

ErrorRetryable reports whether the app should offer a retry for a code.

View Source
var FieldNames = map[Fid]string{
	FidMode:       "mode",
	FidGridW:      "grid_w",
	FidPvW:        "pv_w",
	FidBatteryW:   "battery_w",
	FidBatterySoc: "battery_soc",
	FidLoadW:      "load_w",
	FidSrcGrid:    "src_grid",
	FidSrcPv:      "src_pv",
	FidSrcBattery: "src_battery",
	FidEvW:        "ev_w",
	FidGridL1Da:   "grid_l1_da",
	FidGridL2Da:   "grid_l2_da",
	FidGridL3Da:   "grid_l3_da",
	FidGridFuseDa: "grid_fuse_da",
}

FieldNames maps every field id, frozen or extra, to its registry name.

View Source
var FieldUnits = map[Fid]string{
	FidMode:       "",
	FidGridW:      "W",
	FidPvW:        "W",
	FidBatteryW:   "W",
	FidBatterySoc: "permille",
	FidLoadW:      "W",
	FidSrcGrid:    "",
	FidSrcPv:      "",
	FidSrcBattery: "",
	FidEvW:        "W",
	FidGridL1Da:   "dA",
	FidGridL2Da:   "dA",
	FidGridL3Da:   "dA",
	FidGridFuseDa: "dA",
}

FieldUnits maps every field id, frozen or extra, to its unit, empty when it has none.

View Source
var FrozenFieldNames = map[Fid]string{
	FidMode:       "mode",
	FidGridW:      "grid_w",
	FidPvW:        "pv_w",
	FidBatteryW:   "battery_w",
	FidBatterySoc: "battery_soc",
	FidLoadW:      "load_w",
	FidSrcGrid:    "src_grid",
	FidSrcPv:      "src_pv",
	FidSrcBattery: "src_battery",
	FidEvW:        "ev_w",
}

FrozenFieldNames maps a frozen field id to its registry name.

View Source
var FrozenFieldUnits = map[Fid]string{
	FidMode:       "",
	FidGridW:      "W",
	FidPvW:        "W",
	FidBatteryW:   "W",
	FidBatterySoc: "permille",
	FidLoadW:      "W",
	FidSrcGrid:    "",
	FidSrcPv:      "",
	FidSrcBattery: "",
	FidEvW:        "W",
}

FrozenFieldUnits maps a frozen field id to its unit, empty when it has none.

View Source
var PushSentences = map[string]PushSentence{
	PushChargingConnected:       {Title: "Car plugged in", Body: "Open to see charging status, check the battery level and set a ready time."},
	PushChargingSessionComplete: {Title: "Car charged", Body: "{kwh} kWh delivered — ready to go."},
	PushChargingGoalAtRisk:      {Title: "The car may not be ready", Body: "It will not reach {target} % by {by} at this pace."},
	PushChargingInterrupted:     {Title: "Charging stopped early", Body: "The car stopped charging before it was done."},
	PushUpdateAvailable:         {Title: "A newer FTW is ready", Body: "{version} is ready for your box. Open FTW to see what is new and update."},
	PushUpdateInstalled:         {Title: "FTW is updated", Body: "Your box now runs {version}. Everything came back after the restart."},
	PushDriverOffline:           {Title: "A device went quiet", Body: "{name} stopped answering."},
	PushFuseOverLimit:           {Title: "The house is drawing too much", Body: "{phase} is over the fuse rating."},
	PushControlNotFollowing:     {Title: "A device is not following FTW", Body: "{name} does not do what FTW asks. Open FTW to see why."},
	PushBoxUnreachable:          {Title: "Your box is out of reach", Body: "It stopped answering. Power cut, or the internet at home is down."},
	PushCloudGranted:            {Title: "FTW Cloud is on", Body: "Your box now shares a copy of its readings with FTW Cloud. You can turn it off in the app or on the box."},
	PushCloudRevoked:            {Title: "FTW Cloud is off", Body: "Your box stopped sharing with FTW Cloud and asked it to delete its copy."},
	PushAgentAdded:              {Title: "New access to your box", Body: "An assistant or Sourceful was given access to your box. See who has access in the app."},
	PushAgentRequest:            {Title: "Waiting for your answer", Body: "An assistant asks to change a setting. Open FTW to confirm or decline."},
	PushAgentExpiring:           {Title: "Access ends tomorrow", Body: "An assistant's or Sourceful's access to your box runs out in a day. Renew it in the app if it should go on."},
	PushApprovalKeySet:          {Title: "A phone can now approve access", Body: "A phone set up the key it uses to approve access to your box. If that was not you, remove the phone in the app."},
	PushOwnerAdded:              {Title: "A new owner", Body: "A phone was paired as an owner of your box. If that was not you, remove it in the app."},
	PushCarWhich:                {Title: "Which car is plugged in?", Body: "Tap the car so the box plans for its level and goal."},
}

PushSentences is every sentence a push may carry, keyed by kind.

View Source
var RegistryAgentArgs = map[string][]AgentArg{
	"car.goal.set": {
		{Name: "id", Kind: "car", Unit: "", Required: false, Cap: "", Label: "Car"},
		{Name: "charger_id", Kind: "loadpoint", Unit: "", Required: false, Cap: "", Label: "Charger"},
		{Name: "target", Kind: "ratio", Unit: "", Min: bound(0), Max: bound(1), Required: false, Cap: "", Label: "The level to reach"},
		{Name: "ready_by_min", Kind: "number", Unit: "", Min: bound(0), Max: bound(1439), Required: false, Cap: "", Label: "Ready by"},
		{Name: "days", Kind: "number", Unit: "", Min: bound(0), Max: bound(127), Required: false, Cap: "", Label: "Weekdays"},
		{Name: "finish_at_limit", Kind: "bool", Unit: "", Required: false, Cap: "", Label: "Charge on to the car's own limit"},
		{Name: "clear", Kind: "bool", Unit: "", Required: false, Cap: "", Label: "Remove the goal"},
		{Name: "surplus_only", Kind: "bool", Unit: "", Required: false, Cap: "", Label: "Charge from solar only"},
	},
	"car.soc.set": {
		{Name: "id", Kind: "car", Unit: "", Required: false, Cap: "", Label: "Car"},
		{Name: "charger_id", Kind: "loadpoint", Unit: "", Required: false, Cap: "", Label: "Charger"},
		{Name: "soc", Kind: "ratio", Unit: "", Min: bound(0), Max: bound(1), Required: true, Cap: "", Label: "The car's charge level"},
	},
	"loadpoint.hold": {
		{Name: "id", Kind: "loadpoint", Unit: "", Required: true, Cap: "", Label: "Charger"},
		{Name: "power_w", Kind: "power", Unit: "W", Min: bound(0), Required: false, Cap: "maxW", Label: "Charging power"},
		{Name: "hold_s", Kind: "duration", Unit: "s", Min: bound(1), Required: false, Cap: "holdS", Label: "For how long"},
		{Name: "phase_mode", Kind: "enum", Unit: "", Values: []string{"auto", "1p", "3p"}, Required: false, Cap: "", Label: "Phases"},
		{Name: "clear", Kind: "bool", Unit: "", Required: false, Cap: "", Label: "Stop the agent's own hold"},
	},
	"loadpoint.soc.set": {
		{Name: "id", Kind: "loadpoint", Unit: "", Required: true, Cap: "", Label: "Charger"},
		{Name: "soc", Kind: "ratio", Unit: "", Min: bound(0), Max: bound(1), Required: true, Cap: "", Label: "The car's charge level"},
	},
	"loadpoint.surplus_only.set": {
		{Name: "id", Kind: "loadpoint", Unit: "", Required: true, Cap: "", Label: "Charger"},
		{Name: "surplus_only", Kind: "bool", Unit: "", Required: true, Cap: "", Label: "Charge from solar only"},
	},
	"planner.prefs.set": {
		{Name: "safety_k", Kind: "number", Unit: "", Min: bound(0), Max: bound(2), Required: false, Cap: "", Label: "How cautious the plan is"},
		{Name: "battery_export", Kind: "enum", Unit: "", Values: []string{"unknown", "not_allowed", "allowed"}, Required: false, Cap: "", Label: "Whether the battery may sell to the grid"},
	},
	"site.mode.set": {
		{Name: "mode", Kind: "mode", Unit: "", Required: true, Cap: "", Label: "Operating mode"},
	},
}

RegistryAgentArgs is what an agent may put in each op it can name. The box refuses any other key, kind or range, in a cmd and in an agent.request, as it arrives.

View Source
var RegistryAgentCalls = map[string]string{

	"setup.schema": "ftw.diag.run",

	"setup.status": "ftw.diag.run",

	"setup.edit": "ftw.setup.write",

	"setup.reset": "ftw.setup.write",

	"setup.validate": "ftw.setup.write",

	"setup.commit": "ftw.setup.write",

	"setup.restart": "ftw.setup.write",
}

RegistryAgentCalls maps typed setup calls to their required grants.

View Source
var RegistryAgentOps = map[string]string{
	"site.mode.set":              "ftw.goals.request",
	"planner.prefs.set":          "ftw.goals.request",
	"loadpoint.hold":             "ftw.dispatch.hold",
	"loadpoint.soc.set":          "ftw.goals.request",
	"loadpoint.surplus_only.set": "ftw.goals.request",
	"car.goal.set":               "ftw.goals.request",
	"car.soc.set":                "ftw.goals.request",
}

RegistryAgentOps maps each op an agent may name to the scope that opens it. ftw.dispatch.hold runs as a cmd within the grant's caps; ftw.goals.request waits as an agent.request for an owner. An op not listed is never open to an agent.

View Source
var RegistryModeTiers = map[string]string{
	"planner_passive_arbitrage": "primary",
	"planner_arbitrage":         "primary",
	"idle":                      "advanced",
	"self_consumption":          "advanced",
	"peak_shaving":              "advanced",
	"charge":                    "advanced",
	"planner_self":              "hidden",
	"planner_cheap":             "hidden",
}

RegistryModeTiers is the app's copy of this repository's mode tiers. control.ModeCatalog() remains the authority — this exists only so TestRegistryModesMatchCatalog can catch the two drifting apart.

View Source
var RegistryOps = map[string]string{

	"site.mode.set": "ftw.mode.write",

	"planner.prefs.set": "ftw.mode.write",

	"site.time_zone.propose": "ftw.setup.write",

	"battery.hold": "ftw.dispatch.write",

	"loadpoint.hold": "ftw.dispatch.write",

	"loadpoint.boost": "ftw.dispatch.write",

	"loadpoint.soc.set": "ftw.dispatch.write",

	"loadpoint.surplus_only.set": "ftw.dispatch.write",

	"car.goal.set": "ftw.dispatch.write",

	"car.soc.set": "ftw.dispatch.write",

	"session.car.set": "ftw.dispatch.write",

	"car.add": "ftw.cars.write",

	"car.update": "ftw.cars.write",

	"car.remove": "ftw.cars.write",
}

RegistryOps is the app's copy of the operations a cmd frame may name, each mapped to the scope its grant must carry. defaultOps() in command.go remains the authority on what this box accepts — this exists only so TestRegistryOpsMatchCommandTable can catch the two drifting apart.

View Source
var RegistryReads = map[string]string{

	"live.get": "ftw.live.read",

	"loadpoints.get": "ftw.live.read",

	"cars.get": "ftw.live.read",

	"plan.get": "ftw.plan.read",

	"price.get": "ftw.plan.read",

	"hist.query": "ftw.history.read",

	"health.get": "ftw.health.read",

	"drivers.get": "ftw.health.read",

	"events.get": "ftw.events.read",

	"logs.get": "ftw.logs.read",

	"config.get": "ftw.config.read",

	"diag.run": "ftw.diag.run",

	"api.read": "ftw.diag.run",
}

RegistryReads maps each read an agent may send to the scope it needs.

View Source
var ResolutionRetentionDays = map[Resolution]int{
	ResN1h: 730,
	ResN5m: 30,
}

ResolutionRetentionDays is how far back the box keeps a resolution.

View Source
var ResolutionStepMs = map[Resolution]int64{
	ResN5m: 300_000,
	ResN1h: 3_600_000,
}

ResolutionStepMs is the stored bucket width per resolution. This is the meaning of the resolution's name; the registry carries spans and retention.

View Source
var ResolutionTileSpanMs = map[Resolution]int64{
	ResN1h: 604800000,
	ResN5m: 43200000,
}

ResolutionTileSpanMs is how much time one transfer tile covers.

WriteScopes is every scope that changes something, now or once an owner confirms it.

Functions

func AddBytes

func AddBytes(f SignedFor, m AgentAdd) ([]byte, error)

AddBytes is what agent.add signs.

func AgentInviteHash

func AgentInviteHash(home string, secret []byte) []byte

func ApprovalBytes

func ApprovalBytes(what string, f SignedFor, atMs int64, fields ...any) ([]byte, error)

ApprovalBytes is the deterministic CBOR array a phone signs: the tag, what it approves, the box, the phone, its clock, then the fields.

func ArgsHash

func ArgsHash(args map[string]any) ([]byte, error)

ArgsHash is SHA-256 over the deterministic CBOR of a request's args.

func BulkBucketFor

func BulkBucketFor(payloadBytes int) int

BulkBucketFor is the smallest bulk bucket a payload fits in, or 0 when it fits none. Sizing by the encoded body rather than by a guess keeps a large mode catalogue from silently overrunning a bucket.

func ClampSample

func ClampSample(v float64) int32

ClampSample rounds a mean to the int32 the wire carries.

func ConfirmBytes

func ConfirmBytes(f SignedFor, m AgentConfirm, req Request) ([]byte, error)

ConfirmBytes is what agent.confirm signs to approve: the request, the agent that asked, the op and the hash of its args, as the phone showed them.

func EncodeEnvelope

func EncodeEnvelope(e Envelope) ([]byte, error)

EncodeEnvelope renders one envelope to CBOR.

func EtagOf

func EtagOf(data []byte) string

EtagOf is FNV-1a over the packed block, eight hex digits — the same hash the app computes, because the whole point of an etag is that both ends agree on it.

func InviteCreateBytes

func InviteCreateBytes(f SignedFor, m AgentInviteCreate) ([]byte, error)

func IsAgentInvitePayload

func IsAgentInvitePayload(b []byte) bool

func KeySetBytes

func KeySetBytes(f SignedFor, m ApprovalKeySet) ([]byte, error)

KeySetBytes is what approval.key.set signs: the key itself, as proof the phone holds its private half.

func LongestMs

func LongestMs() map[string]int64

LongestMs is the longest grant for each agent role, as agent.list tells owners. A box whose answer leaves it out takes at most 30 days for an agent (docs/agents.md, Mixed versions).

func Marshal

func Marshal(v any) (cbor.RawMessage, error)

Marshal encodes a body deterministically.

func OfferBytes

func OfferBytes(o []byte) ([]byte, error)

OfferBytes is what an offer key signs: ["ftw.offer.v1", o].

func OfferKid

func OfferKid(pub []byte) string

OfferKid names an offer key: the first 16 characters of base64url, without padding, of SHA-256 over its SEC1 point. FTW Cloud publishes kid and key at /.well-known/ftw-offer-key; the box and the apps pin a list of them.

func ParseApprovalKey

func ParseApprovalKey(pub []byte) (*ecdsa.PublicKey, error)

ParseApprovalKey reads a SEC1 uncompressed P-256 public key.

func PointsPerTile

func PointsPerTile(res Resolution) int64

PointsPerTile is how many stored buckets one tile spans at stride 1.

func RenderPush

func RenderPush(kind string, args map[string]string) (title, body string, err error)

RenderPush fills a catalogue sentence's {arg} placeholders from the event's own facts. It refuses to render a sentence it cannot finish: a lock screen showing a literal "{kwh}" is a promise the catalogue made that the event broke, and silence is better than gibberish.

func TileIDFor

func TileIDFor(res Resolution, stride, startMs int64) string

TileIDFor matches the app's tileId(): res/stride/tileIndex.

func TileStartFor

func TileStartFor(res Resolution, atMs int64) int64

TileStartFor is the start of the epoch-aligned tile that contains atMs.

func Unmarshal

func Unmarshal(raw cbor.RawMessage, v any) error

Unmarshal decodes a body. Unknown keys are dropped without complaint.

func UnmarshalSigned

func UnmarshalSigned(raw []byte, v any) error

UnmarshalSigned decodes a body the box checks a signature on: a key it does not know, or a key twice, is refused.

func ValidAgentAPIPath

func ValidAgentAPIPath(value string) bool

ValidAgentAPIPath validates syntax only. Core's router decides whether the path is a read; Cloud does not keep a second list of the box's API.

func ValidBy

func ValidBy(by string) bool

ValidBy says whether a support call's by is well formed: staff:<id> for a person or bot:<name> for Sourceful's own tooling.

func VerifyApproval

func VerifyApproval(pub []byte, msg, sig []byte) error

VerifyApproval checks sig, r ‖ s, over SHA-256 of msg.

func WidenBytes

func WidenBytes(f SignedFor, m AgentWiden, key []byte) ([]byte, error)

WidenBytes is what agent.widen signs. key is the row's whole key, which the phone read from agent.list: an id and an epoch alone could name another row that took the same id.

Types

type APIChunk

type APIChunk struct {
	Seq  uint32 `cbor:"seq"`
	Data []byte `cbor:"data"`
}

APIChunk is one piece of the answer, in order.

type APIEnd

type APIEnd struct {
	Bytes int64 `cbor:"bytes"`
	// Truncated means the answer ran past the ceiling and stops here. The
	// app treats it as a failure rather than showing a partial answer as a
	// whole one.
	Truncated bool `cbor:"truncated"`
}

APIEnd closes an answer.

type APIHeadMsg

type APIHeadMsg struct {
	Status int `cbor:"status"`
	// Headers is a short allowlist, not the handler's full set. Everything
	// the app needs to read an answer and nothing that describes the box's
	// LAN.
	Headers map[string]string `cbor:"headers"`
	// Len is the declared length, absent when the handler did not declare
	// one — which is the usual case in process. A guessed number here would
	// be a progress bar that lies.
	Len *int64 `cbor:"len"`
}

APIHeadMsg is the answer's status line.

Its arrival is what tells the two error kinds apart, and it needs no body inspection: if api.head arrived, the box's HTTP layer answered and Status is the answer — a 403 or a 500 from a box handler is a status, never an E_ code. If an error arrived on that id instead, the passthrough refused and no handler ran.

type APIRead

type APIRead struct {
	Path          string            `cbor:"path"`
	Query         map[string]string `cbor:"query,omitempty"`
	MaxBytes      int64             `cbor:"maxBytes,omitempty"`
	Offset        int64             `cbor:"offset,omitempty"`
	IfSHA256      string            `cbor:"ifSHA256,omitempty"`
	ArchiveMember string            `cbor:"archiveMember,omitempty"`
}

APIRead is a diagnostic GET, with no method, body, headers or write path. Offset and MaxBytes select a byte page. IfSHA256 prevents joining pages from different answers. The answer uses api.head/chunk/end, carrying JSON.

func DecodeAPIRead

func DecodeAPIRead(body []byte) (APIRead, error)

type APIReq

type APIReq struct {
	// Method is one of the six the passthrough accepts. Anything else is
	// refused before a handler runs.
	Method string `cbor:"method"`
	// Path must start "/api/". The box's static handler is unreachable on
	// purpose: serving HTML through the session would be a second origin
	// under another name, which docs/architecture.md rejected.
	Path string `cbor:"path"`
	// Query is parsed, not a raw string. Two reasons: the tier gate keys on
	// the path, and a tier decided over a string that can carry "?" is a
	// parser bug that becomes a privilege bug — and this way the app never
	// handles encoding, because the box rebuilds the URL itself.
	Query map[string]string `cbor:"query,omitempty"`
	// Body is opaque. The box sets Content-Type: application/json when one
	// is present, and sets nothing else.
	Body []byte `cbor:"body,omitempty"`
	// MaxBytes is the app's own ceiling, clamped by the box's APIMaxBytes.
	// The app learns the real figure from APIEnd.
	MaxBytes int64 `cbor:"maxBytes,omitempty"`
	// StepUp says the app ran a passkey ceremony for this request. Read the
	// note above the check in passthrough.go before believing it means more
	// than it does.
	StepUp bool `cbor:"stepUp,omitempty"`
}

APIReq asks the box to run one request against its own HTTP API.

All four api.* messages ride the bulk lane and carry the request id. Never lane 0: every field here varies in length with what was asked and answered, and lane 0's constant size is a privacy control rather than a budget.

type AgentAPIRoute

type AgentAPIRoute struct {
	Path        string            `json:"path"`
	Scope       string            `json:"scope"`
	Description string            `json:"description"`
	Query       map[string]string `json:"query,omitempty"`
}

AgentAPIRoute describes a route registered by the connected Core version. Query is guidance; the existing HTTP handler owns parameter validation.

type AgentAdd

type AgentAdd struct {
	Key         []byte    `cbor:"key"`
	Role        string    `cbor:"role"`
	Scopes      []string  `cbor:"scopes"`
	Ops         []string  `cbor:"ops"`
	Caps        Caps      `cbor:"caps"`
	ExpiresAtMs int64     `cbor:"expiresAtMs"`
	Principal   Principal `cbor:"principal"`
	AtMs        int64     `cbor:"atMs"`
	Sig         []byte    `cbor:"sig"`
}

AgentAdd grants access.

type AgentArg

type AgentArg struct {
	Name     string
	Kind     string
	Unit     string
	Min      *float64
	Max      *float64
	Values   []string
	Required bool
	Cap      string
	Label    string
}

AgentArg is one argument an agent may put in an op, from the registry's agent_args. Min and Max bound a number; Cap names the grant's cap that bounds it as well.

type AgentConfirm

type AgentConfirm struct {
	ReqID   string `cbor:"reqId"`
	Approve bool   `cbor:"approve"`
	AtMs    int64  `cbor:"atMs,omitempty"`
	Sig     []byte `cbor:"sig,omitempty"`
}

AgentConfirm answers a request. Approving is signed; declining is not.

type AgentDecided

type AgentDecided struct {
	ReqID  string     `cbor:"reqId"`
	State  string     `cbor:"state"`
	CmdID  string     `cbor:"cmdId,omitempty"`
	Result *CmdResult `cbor:"result,omitempty"`
}

AgentDecided is how a request ended, sent to the agent's open session. Result is the command's outcome when the request ran.

type AgentInvite

type AgentInvite struct {
	CancelledAtMs    int64    `cbor:"cancelledAtMs,omitempty" json:"cancelledAtMs,omitempty"`
	ClockUnavailable bool     `cbor:"clockUnavailable,omitempty" json:"clockUnavailable,omitempty"`
	Home             string   `cbor:"home" json:"home"`
	Box              []byte   `cbor:"box" json:"box"`
	ID               string   `cbor:"id" json:"id"`
	Label            string   `cbor:"label" json:"label"`
	Scopes           []string `cbor:"scopes" json:"scopes"`
	Ops              []string `cbor:"ops" json:"ops"`
	Caps             Caps     `cbor:"caps" json:"caps"`
	CreatedAtMs      int64    `cbor:"createdAtMs" json:"createdAtMs"`
	ClaimUntilMs     int64    `cbor:"claimUntilMs" json:"claimUntilMs"`
	ExpiresAtMs      int64    `cbor:"expiresAtMs" json:"expiresAtMs"`
	State            string   `cbor:"state" json:"state"`
	AgentID          string   `cbor:"agentId,omitempty" json:"agentId,omitempty"`
	ClaimedAtMs      int64    `cbor:"claimedAtMs,omitempty" json:"claimedAtMs,omitempty"`
	Client           string   `cbor:"client,omitempty" json:"client,omitempty"`
}

AgentInvite contains no secret or verifier. A claimed invitation points to the ordinary agent row; revoking that row never revives its invitation.

type AgentInviteCancel

type AgentInviteCancel struct {
	ID string `cbor:"id" json:"id"`
}

type AgentInviteClaim

type AgentInviteClaim struct {
	Secret []byte      `cbor:"secret"`
	Offer  SignedOffer `cbor:"offer"`
}

AgentInviteClaim is encrypted inside Noise message 1. The signed offer binds the recipient's own pending key to the OAuth request.

func ParseAgentInviteClaim

func ParseAgentInviteClaim(b []byte) (AgentInviteClaim, error)

func (AgentInviteClaim) Payload

func (c AgentInviteClaim) Payload() ([]byte, error)

type AgentInviteCode

type AgentInviteCode struct {
	V      uint64 `cbor:"v"`
	Home   string `cbor:"home"`
	Box    []byte `cbor:"box"`
	Secret []byte `cbor:"secret"`
}

AgentInviteCode is copied to the person receiving access. It contains a 256-bit bearer secret; never put it in logs, a query string or a roster.

func ParseAgentInviteCode

func ParseAgentInviteCode(raw string) (AgentInviteCode, error)

func (AgentInviteCode) Encode

func (c AgentInviteCode) Encode() (string, error)

type AgentInviteCreate

type AgentInviteCreate struct {
	Home         string   `cbor:"home" json:"home"`
	ID           string   `cbor:"id" json:"id"`
	Hash         []byte   `cbor:"hash" json:"hash"`
	Label        string   `cbor:"label" json:"label"`
	Scopes       []string `cbor:"scopes" json:"scopes"`
	Ops          []string `cbor:"ops" json:"ops"`
	Caps         Caps     `cbor:"caps" json:"caps"`
	ClaimUntilMs int64    `cbor:"claimUntilMs" json:"claimUntilMs"`
	ExpiresAtMs  int64    `cbor:"expiresAtMs" json:"expiresAtMs"`
	AtMs         int64    `cbor:"atMs" json:"atMs"`
	Sig          []byte   `cbor:"sig" json:"sig"`
}

AgentInviteCreate approves one future agent. The owner draws Secret locally and sends only its verifier. ID makes a lost create reply safe to retry.

type AgentList

type AgentList struct {
	Agents   []AgentRow        `cbor:"agents" json:"agents"`
	Requests []Request         `cbor:"requests" json:"requests"`
	Keys     []ApprovalKeyInfo `cbor:"keys" json:"keys"`
	// LongestMs is the longest grant the box takes for each role, so a
	// client offers no length the box would refuse. Owners only.
	LongestMs map[string]int64 `cbor:"longestMs,omitempty" json:"longestMs,omitempty"`
}

AgentList is agent.ok's body for agent.list. An agent sees its own row.

type AgentRequest

type AgentRequest struct {
	Op   string         `cbor:"op"`
	Args map[string]any `cbor:"args"`
	Why  string         `cbor:"why"`
}

AgentRequest is an agent asking for a durable change.

type AgentRevoke

type AgentRevoke struct {
	ID string `cbor:"id"`
}

AgentRevoke removes a grant. No signature.

type AgentRow

type AgentRow struct {
	ID          string    `cbor:"id" json:"id"`
	Key         []byte    `cbor:"key" json:"key"`
	Role        string    `cbor:"role" json:"role"`
	Scopes      []string  `cbor:"scopes" json:"scopes"`
	Ops         []string  `cbor:"ops" json:"ops"`
	Caps        Caps      `cbor:"caps" json:"caps"`
	ExpiresAtMs int64     `cbor:"expiresAtMs" json:"expiresAtMs"`
	Principal   Principal `cbor:"principal" json:"principal"`
	ApprovedBy  string    `cbor:"approvedBy" json:"approvedBy"`
	AddedAtMs   int64     `cbor:"addedAtMs" json:"addedAtMs"`
	LastSeenMs  int64     `cbor:"lastSeenMs" json:"lastSeenMs"`
	Epoch       uint64    `cbor:"epoch" json:"epoch"`
}

AgentRow is one agent grant as the box holds it.

type AgentWiden

type AgentWiden struct {
	ID          string   `cbor:"id"`
	Epoch       uint64   `cbor:"epoch"`
	Scopes      []string `cbor:"scopes"`
	Ops         []string `cbor:"ops"`
	Caps        Caps     `cbor:"caps"`
	ExpiresAtMs int64    `cbor:"expiresAtMs"`
	AtMs        int64    `cbor:"atMs"`
	Sig         []byte   `cbor:"sig"`
}

AgentWiden replaces a grant's rights. Any change but a revoke is signed.

type AppInfo

type AppInfo struct {
	Build string `cbor:"build"`
	UA    string `cbor:"ua"`
}

type ApprovalKeyInfo

type ApprovalKeyInfo struct {
	DeviceID string `cbor:"deviceId" json:"deviceId"`
	SetAtMs  int64  `cbor:"setAtMs" json:"setAtMs"`
}

ApprovalKeyInfo is one owner phone's registered approval key.

type ApprovalKeySet

type ApprovalKeySet struct {
	Pub  []byte `cbor:"pub"`
	AtMs int64  `cbor:"atMs"`
	Sig  []byte `cbor:"sig"`
	// PrevSig is the phone's current key's signature over the same bytes.
	// Replacing a key needs it.
	PrevSig []byte `cbor:"prevSig,omitempty"`
}

ApprovalKeySet registers an owner phone's approval key.

type AuditGet

type AuditGet struct {
	BeforeSeq uint64 `cbor:"beforeSeq,omitempty"`
	N         uint64 `cbor:"n,omitempty"`
}

AuditGet pages through the audit log, newest first.

type AuditPage

type AuditPage struct {
	Rows []AuditRow `cbor:"rows" json:"rows"`
	More bool       `cbor:"more" json:"more"`
}

AuditPage is agent.ok's body for audit.get.

type AuditRow

type AuditRow struct {
	Seq       uint64 `cbor:"seq" json:"seq"`
	AtMs      int64  `cbor:"atMs" json:"atMs"`
	Actor     string `cbor:"actor" json:"actor"`
	Role      string `cbor:"role" json:"role"`
	Principal string `cbor:"principal" json:"principal"`
	By        string `cbor:"by" json:"by"`
	What      string `cbor:"what" json:"what"`
	Target    string `cbor:"target" json:"target"`
	Result    string `cbor:"result" json:"result"`
	// Count folds an agent's reads: how many of what in that minute.
	Count uint64 `cbor:"count" json:"count"`
}

AuditRow is one line of the box's audit log.

type BootProgress

type BootProgress struct {
	Phase string `cbor:"phase"`
	Pct   int    `cbor:"pct"`
	// EtaMs is nil when the box genuinely cannot estimate. A made-up number
	// here is worse than none.
	EtaMs *int64 `cbor:"etaMs"`
}

BootProgress is what the box is busy with before it can serve telemetry.

type BoxInfo

type BoxInfo struct {
	ID    string `cbor:"id"`
	Build string `cbor:"build"`
	TZ    string `cbor:"tz"`
}

type BoxMode

type BoxMode string

BoxMode is what the box is able to offer this session.

const (
	// BoxModeFull — everything the box supports.
	BoxModeFull BoxMode = "full"
	// BoxModeFloor — the frozen subset, because the app is too old.
	BoxModeFloor BoxMode = "floor"
	// BoxModeBooting — still starting; no subscription yet.
	BoxModeBooting BoxMode = "booting"
	// BoxModeReadonly — the grant carries no write scope.
	BoxModeReadonly BoxMode = "readonly"
)

type Caps

type Caps struct {
	// HoldS is the longest hold, in seconds.
	HoldS uint64 `cbor:"holdS" json:"holdS"`
	// MaxW is the largest power a hold may set, in W.
	MaxW uint64 `cbor:"maxW" json:"maxW"`
	// PerMin is cmd and agent.request per rolling minute.
	PerMin uint64 `cbor:"perMin" json:"perMin"`
}

Caps bound what one grant may do.

type Car

type Car struct {
	// ID is 128 bits as 32 lowercase hex digits. The owner's app mints it,
	// and it is the same on every box the owner has.
	ID string `cbor:"id" json:"id"`
	// BoxMinted marks a car the box made from its old settings, with an id
	// of its own. The owner's app adopts it with car.update new_id, or by
	// adding a car with the same VIN.
	BoxMinted bool `cbor:"boxMinted,omitempty" json:"box_minted,omitempty"`
	// OwnerID is reserved for the owner the car belongs to. Until owners
	// are principals, every phone with the owner role shares one list.
	OwnerID string `cbor:"ownerId,omitempty" json:"owner_id,omitempty"`
	Name    string `cbor:"name" json:"name"`
	Make    string `cbor:"make,omitempty" json:"make,omitempty"`
	// VIN binds a vehicle driver that reports the same VIN to this car.
	VIN        string `cbor:"vin,omitempty" json:"vin,omitempty"`
	CapacityWh int64  `cbor:"capacityWh" json:"capacity_wh"`
	// MaxW and Phases are the car's own charger. Zero means unknown, and a
	// session then takes the charger's limits alone.
	MaxW   int64 `cbor:"maxW,omitempty" json:"max_w,omitempty"`
	Phases int64 `cbor:"phases,omitempty" json:"phases,omitempty"`

	// SocPermille is the level. While SocEstimate is false it is the
	// number the car or a person gave; after, it is that number plus the
	// energy delivered to the car since, × efficiency / capacity. Absent
	// when the box has none.
	SocPermille *int64 `cbor:"socPermille,omitempty" json:"soc_permille,omitempty"`
	// SocSource is where that reading came from, one of CarSoC*.
	SocSource string `cbor:"socSource,omitempty" json:"soc_source,omitempty"`
	// SocAgeS is the seconds since the car reported the level or someone set
	// it, at send. Never the box's wall clock, which may be wrong.
	SocAgeS *int64 `cbor:"socAgeS,omitempty" json:"soc_age_s,omitempty"`
	// EnergySinceWh is the energy delivered to this car since then;
	// negative when a V2X session took energy out.
	EnergySinceWh int64 `cbor:"energySinceWh" json:"energy_since_wh"`
	// SocEstimate is true once more than the box's limit of energy has
	// flowed since the reading, for a level read before the car last left
	// a charger, and always for an assumed level. A reading with nothing
	// delivered since stays exact for as long as that holds.
	SocEstimate         bool   `cbor:"socEstimate" json:"soc_estimate"`
	ChargeLimitPermille *int64 `cbor:"chargeLimitPermille,omitempty" json:"charge_limit_permille,omitempty"`

	// Goal is one per car, used wherever the car is plugged in.
	Goal *CarGoal `cbor:"goal,omitempty" json:"goal,omitempty"`
	// SurplusOnly is the car's preference: it charges from surplus PV only.
	SurplusOnly bool `cbor:"surplusOnly" json:"surplus_only"`

	// Identifiers are the RFID tags, MAC addresses and eMAIDs a charger may
	// name the car by.
	Identifiers []string `cbor:"identifiers,omitempty" json:"identifiers,omitempty"`
	// Sources are the vehicle drivers on this box that report the car's
	// level. They are the box's own and never copied to another box: Home
	// Assistant at home, the maker's service anywhere.
	Sources []string `cbor:"sources,omitempty" json:"sources,omitempty"`
}

Car is one car as the box keeps it.

type CarGoal

type CarGoal struct {
	TargetPermille int64 `cbor:"targetPermille" json:"target_permille"`
	// ReadyByMin is minutes after midnight in the box's time zone.
	ReadyByMin int64 `cbor:"readyByMin" json:"ready_by_min"`
	// Days is an ISO weekday mask, Monday in bit 0. Zero is once, at the
	// next ready time, and 127 every day. A loadpoint schedule's days reads
	// 0 as every day when recurring; docs/cars.md maps the two.
	Days uint8 `cbor:"days" json:"days"`
	// FinishAtLimit charges on until the car stops at its own limit.
	FinishAtLimit bool `cbor:"finishAtLimit" json:"finish_at_limit"`
}

CarGoal is what a car should reach and when.

type ChargerCar

type ChargerCar struct {
	// Session is this plug-in's id. session.car.set names it, and the box
	// refuses a tap for a plug-in that has ended.
	Session string `cbor:"session,omitempty" json:"session,omitempty"`
	// CarID is the session's car, empty when the box does not know which.
	CarID string `cbor:"carId,omitempty" json:"car_id,omitempty"`
	// CarIdentifiedBy is one of CarIdentifiedBy*.
	CarIdentifiedBy string `cbor:"carIdentifiedBy,omitempty" json:"car_identified_by,omitempty"`
	// CarCorrected is set when a better rule replaced the car the box named
	// first, and CarCorrectedFrom is that car, for the rest of the session,
	// so the correction is shown rather than silent.
	CarCorrected     bool   `cbor:"carCorrected,omitempty" json:"car_corrected,omitempty"`
	CarCorrectedFrom string `cbor:"carCorrectedFrom,omitempty" json:"car_corrected_from,omitempty"`
	// Choose is, while the box asks, the cars a tap may pick: at most four,
	// none of them on another charger.
	Choose []string `cbor:"choose,omitempty" json:"choose,omitempty"`
}

ChargerCar is what a charger carries about the car on it, beside its own fields: on GET /api/loadpoints and, with opaque ids, in FTW Cloud's lp class. The watch's NowLoadpoint carries all but CarCorrectedFrom. Empty while nothing is plugged in.

type Clock

type Clock struct {
	Source     string `cbor:"source"`
	SyncedAtMs int64  `cbor:"syncedAtMs"`
	UptimeMs   int64  `cbor:"uptimeMs"`
}

Clock is how the app anchors every age it renders.

SyncedAtMs is wall clock and may be nonsense before NTP answers; UptimeMs never is, which is why it and not the wall clock is what ages are measured against.

type CloudSession

type CloudSession struct {
	// PK is the box's FTW Cloud public key, the 65-byte uncompressed P-256
	// point. Every box envelope from the service verifies with it.
	PK []byte `cbor:"pk"`
	// Home is the home id at the service, cut from PK.
	Home string `cbor:"home"`
	// Boot is the uplink's current 16-byte boot id. With hello_ok's
	// clock.uptimeMs it anchors the times in box envelopes: both count from
	// the same process start.
	Boot []byte `cbor:"boot"`
	// Sources maps each opaque source id to its source id in this protocol,
	// the driver name.
	Sources map[string]string `cbor:"sources"`
	// Loadpoints maps each opaque loadpoint id to the loadpoint id.
	Loadpoints map[string]string `cbor:"loadpoints"`
	// Cars maps each opaque car id to the car's id. Absent from a box
	// without cars.
	Cars map[string]string `cbor:"cars,omitempty"`
}

CloudSession lets a phone check and read what FTW Cloud serves it. It comes from the box over Noise and never from the service, so the service cannot sign for the box, swap its key or rename a source.

type Cmd

type Cmd struct {
	// CmdID is a UUIDv7 idempotency key. The box keeps it 24 h so a retry
	// cannot act twice.
	CmdID string         `cbor:"cmdId"`
	Op    string         `cbor:"op"`
	Args  map[string]any `cbor:"args"`
	// NotValidAfterMs is mandatory, in box uptime. A command queued offline
	// must never execute blindly later: "charge at 10 kW" arriving three
	// hours late is a different instruction than the one the user gave.
	NotValidAfterMs int64  `cbor:"notValidAfterMs"`
	Expect          Expect `cbor:"expect"`
}

Cmd is an intent, not an instruction to hardware.

type CmdAck

type CmdAck struct {
	CmdID   string `cbor:"cmdId"`
	LeaseID string `cbor:"leaseId"`
	// ExpiresAtMs is absolute box uptime.
	ExpiresAtMs int64 `cbor:"expiresAtMs"`
}

CmdAck says the dispatcher accepted the intent. It is not proof the hardware moved.

type CmdResult

type CmdResult struct {
	CmdID    string     `cbor:"cmdId"`
	State    string     `cbor:"state"`
	Observed *Observed  `cbor:"observed,omitempty"`
	Error    *ErrorBody `cbor:"error,omitempty"`
	// Car is the car as the box holds it after a car op, and Charger the
	// charger's car after session.car.set (docs/cars.md): read back, never
	// the request's echo.
	Car     *Car        `cbor:"car,omitempty"`
	Charger *ChargerCar `cbor:"charger,omitempty"`
}

CmdResult is what actually happened.

Observed is present only when the driver read the value back. The echo of a requested value is never sent as confirmation — that is the whole difference between knowing a command was heard and knowing it happened.

type Delta

type Delta struct {
	Seq      uint64           `cbor:"seq"`
	UptimeMs int64            `cbor:"uptimeMs"`
	Fields   map[string]int64 `cbor:"fields"`
	// Sources is usually absent, because source state changes rarely. But
	// when a device goes quiet mid-session this is the only way the client
	// hears about it, so "rarely" must never become "only in the snapshot".
	Sources map[string]SourceWire `cbor:"sources,omitempty"`
	// DispatchBlockedBy travels with Sources; the two always move together.
	DispatchBlockedBy []string `cbor:"dispatchBlockedBy,omitempty"`
}

Delta carries only what moved.

type DriverState

type DriverState struct {
	Src   string `cbor:"src"`
	Kind  string `cbor:"kind"`
	State string `cbor:"state"`
	// AgeMs is the time since its last good reading, or -1 for never.
	AgeMs int64 `cbor:"ageMs"`
}

DriverState is one driver in drivers.get, by its opaque source id.

type Drivers

type Drivers struct {
	Drivers []DriverState `cbor:"drivers"`
}

Drivers is the answer to drivers.get.

type Envelope

type Envelope struct {
	// T is the message type, a stable string.
	T string `cbor:"t"`
	// ID is a request id, u32. Replies echo it. Nil on unsolicited messages.
	ID *uint32 `cbor:"id,omitempty"`
	// B is the body, left encoded so the handler can unmarshal it into the
	// type the message name implies.
	B cbor.RawMessage `cbor:"b,omitempty"`
	// By names the person behind a call from a Sourceful support session:
	// the staff member's id, at most ByMax bytes. FTW Cloud asserts it and
	// the box writes it to its audit log. Absent on every other session.
	By string `cbor:"by,omitempty"`
}

Envelope is one message. Deterministic CBOR with text keys.

Unknown keys are ignored on decode and unknown message types are ignored on dispatch, in both directions. That is the single rule that lets a newer app talk to an older box and the reverse.

func DecodeEnvelope

func DecodeEnvelope(b []byte) (Envelope, error)

DecodeEnvelope parses one envelope, leaving the body encoded.

func NewEnvelope

func NewEnvelope(t string, id *uint32, body any) (Envelope, error)

NewEnvelope builds an outgoing envelope around a body.

type ErrorBody

type ErrorBody struct {
	Code         string         `cbor:"code"`
	Retryable    bool           `cbor:"retryable"`
	RetryAfterMs *int64         `cbor:"retryAfterMs,omitempty"`
	Args         map[string]any `cbor:"args,omitempty"`
}

ErrorBody is a stable code with machine-readable args. No prose: the app owns all of it, in every language it ships.

type Event

type Event struct {
	EventID  string         `cbor:"eventId"`
	Kind     string         `cbor:"kind"`
	Severity string         `cbor:"severity"`
	UptimeMs int64          `cbor:"uptimeMs"`
	Args     map[string]any `cbor:"args,omitempty"`
}

Event is something worth surfacing.

type EventNotice

type EventNotice struct {
	Ts       int64  `cbor:"ts"`
	Type     string `cbor:"type"`
	Src      string `cbor:"src,omitempty"`
	Status   string `cbor:"status"`
	Priority int    `cbor:"priority,omitempty"`
}

EventNotice is one notification the box sent or tried to send.

type EventSpan

type EventSpan struct {
	Kind     string `cbor:"kind"`
	Src      string `cbor:"src,omitempty"`
	Status   string `cbor:"status"`
	Reason   string `cbor:"reason,omitempty"`
	Severity string `cbor:"severity,omitempty"`
	Mode     string `cbor:"mode,omitempty"`
	StartMs  int64  `cbor:"startMs"`
	// EndMs is 0 while the verdict still holds.
	EndMs   int64 `cbor:"endMs"`
	Samples int64 `cbor:"samples"`
	// RequestedW and ActualW summarise the power Core asked for and the
	// power measured over the span; absent when never known.
	RequestedW *PowerRange `cbor:"requestedW,omitempty"`
	ActualW    *PowerRange `cbor:"actualW,omitempty"`
	// Last holds the numbers of the latest sample by field name, such as
	// sent_w, readback_w, offered_a, battery_soc or planned_wh.
	Last map[string]float64 `cbor:"last,omitempty"`
}

EventSpan is one stretch in which a subject held one control verdict. Kind is battery, ev, pv, v2x_charger or device for a controlled function, source for a driver's freshness, dispatch for whether the site may act, mode for the operating mode, or slot for a scored plan slot. Status, reason and severity are Core's own words, as in control_feedback.

type Events

type Events struct {
	Events  []cbor.RawMessage `cbor:"events"`
	Spans   []EventSpan       `cbor:"spans,omitempty"`
	Notices []EventNotice     `cbor:"notices,omitempty"`
	More    bool              `cbor:"more"`
}

Events is the answer to events.get: spans newest first, the notices in the same window, and More when either was cut. Events is kept for readers built before spans; the box leaves it empty.

type EventsGet

type EventsGet struct {
	N           uint64 `cbor:"n,omitempty"`
	BeforeMs    int64  `cbor:"beforeMs,omitempty"`
	AfterMs     int64  `cbor:"afterMs,omitempty"`
	Src         string `cbor:"src,omitempty"`
	MinSeverity string `cbor:"minSeverity,omitempty"`
}

EventsGet asks what the box recorded about control between AfterMs and BeforeMs, the last 24 hours when both are 0: each stretch in which a device function, a source, the site's dispatch or the mode held one verdict, each scored plan slot, and the notifications the box sent. Src keeps one source by its agent id; MinSeverity "warning" keeps warnings and alarms, "alarm" alarms only. N bounds the spans, newest first.

type ExchangeHelloOK

type ExchangeHelloOK struct {
	Proto  int      `cbor:"proto"`
	Mode   BoxMode  `cbor:"mode"`
	Clock  Clock    `cbor:"clock"`
	Role   string   `cbor:"role"`
	Scopes []string `cbor:"scopes"`
	// Rev is the site's controlRev. A command carries the rev it expects, and
	// the exchange has no snapshot to learn it from.
	Rev uint64 `cbor:"rev"`
	// Cloud is what the watch needs to read FTW Cloud on its own, while an
	// owner has FTW Cloud on. Absent means off.
	Cloud *CloudSession `cbor:"cloud,omitempty"`
}

ExchangeHelloOK answers a watch's hello on the exchange, in handshake message 2 (ADR 0009, decision 2).

It carries what a watch needs and nothing more. The capability list and the mode catalogue stay on the stream: a watch sends cmd and now, and nothing it shows needs them. The smallest bulk bucket it fits, normally 1 KiB; its size follows the house's equipment, never what happens in the house.

type Expect

type Expect struct {
	Rev    uint64  `cbor:"rev"`
	Guards []Guard `cbor:"guards"`
}

type Fid

type Fid uint32

Fid is a telemetry field id. 1-9 are frozen permanently as of v1, so an app of any age can draw the core view from them alone. Ids after the frozen set are depth for a node's own view.

const (
	// FidMode — enum, unit none.
	FidMode Fid = 1
	// FidGridW — power, unit W.
	FidGridW Fid = 2
	// FidPvW — power, unit W.
	FidPvW Fid = 3
	// FidBatteryW — power, unit W.
	FidBatteryW Fid = 4
	// FidBatterySoc — ratio, unit permille.
	FidBatterySoc Fid = 5
	// FidLoadW — power, unit W.
	FidLoadW Fid = 6
	// FidSrcGrid — source_ref, unit none.
	FidSrcGrid Fid = 7
	// FidSrcPv — source_ref, unit none.
	FidSrcPv Fid = 8
	// FidSrcBattery — source_ref, unit none.
	FidSrcBattery Fid = 9
	// FidEvW — power, unit W.
	FidEvW Fid = 10
	// FidGridL1Da — current, unit dA.
	FidGridL1Da Fid = 11
	// FidGridL2Da — current, unit dA.
	FidGridL2Da Fid = 12
	// FidGridL3Da — current, unit dA.
	FidGridL3Da Fid = 13
	// FidGridFuseDa — current, unit dA.
	FidGridFuseDa Fid = 14
)

type FieldDef

type FieldDef struct {
	Name string  `cbor:"name"`
	Unit *string `cbor:"unit"`
	// SrcID is the source this field's freshness comes from. Null for
	// fields the box computes itself, such as the mode.
	SrcID *string `cbor:"srcId"`
}

FieldDef is one entry of the field dictionary. The client caches it across sessions, which is why deltas can be bare id-to-value pairs. Unit and SrcID are pointers so that "this field has none" reaches the app as CBOR null rather than an empty string. The app's type says `string | null`, and a field whose source is the empty string would look like a source id nobody can resolve.

type Frame

type Frame struct {
	Lane  uint8
	Flags uint8
	// Bucket is the padded size the frame must be encoded to.
	Bucket   int
	Envelope Envelope
}

Frame is one envelope on one lane. Package appwire owns the byte layout, the padding and the Noise session; this package only decides what goes in a frame and which lane carries it.

type FrameCodec

type FrameCodec interface {
	EncodeFrame(f Frame) ([]byte, error)
	DecodeFrame(b []byte) (Frame, error)
}

FrameCodec is the whole of package appwire that this package needs. It is declared here rather than imported so the message layer builds, tests and reviews on its own.

type GrantOffer

type GrantOffer struct {
	V uint64 `cbor:"v"`
	// Home is empty: the owner picks the home in the app or on the box page.
	// A box takes an offer whose home is empty or its own.
	Home string `cbor:"home"`
	Key  []byte `cbor:"key"`
	Role string `cbor:"role"`
	// Client is the name the client gives itself. ClientHost is the host of
	// its metadata document or redirect URI, and Verified says FTW Cloud
	// knows the client by its own list. The app shows all three.
	Client     string   `cbor:"client"`
	ClientID   string   `cbor:"clientId"`
	ClientHost string   `cbor:"clientHost"`
	Verified   bool     `cbor:"verified"`
	Scopes     []string `cbor:"scopes"`
	Ops        []string `cbor:"ops"`
	Caps       Caps     `cbor:"caps"`
	TTLS       uint64   `cbor:"ttlS"`
	Ticket     string   `cbor:"ticket"`
	// Code is what the consent page shows, for the owner to type or compare.
	Code string `cbor:"code"`
	// ExpMs is when the offer stops being good, wall clock, at most
	// OfferTTLMs after FTW Cloud made it.
	ExpMs int64 `cbor:"exp"`
}

GrantOffer is what FTW Cloud's consent page offers the owner: the agent's key and the rights its client asks for (docs/agents.md, The grant offer). It travels signed, as SignedOffer. The owner may grant less than it asks.

func OpenOffer

func OpenOffer(keys map[string][]byte, so SignedOffer, nowMs int64) (GrantOffer, error)

OpenOffer checks a signed offer against pinned offer keys (kid → SEC1 P-256 point) and the wall clock, and returns the offer. A support offer must come from SupportClientID.

type Guard

type Guard struct {
	Fid   Fid     `cbor:"fid"`
	Op    string  `cbor:"op"`
	Value float64 `cbor:"value"`
}

Guard is a precondition re-evaluated against fresh state at the dispatch boundary, not against the state the user was looking at.

type Hello

type Hello struct {
	// Proto is a range, never an equality demand. That is what avoids a
	// version wall.
	Proto   ProtoRange `cbor:"proto"`
	App     AppInfo    `cbor:"app"`
	Locales []string   `cbor:"locales"`
	// Sub folds the first telemetry subscription into the hello. Older boxes
	// ignore this additive field; subscribed in hello_ok tells a newer app whether
	// it still needs to send the ordinary sub message.
	Sub *Sub `cbor:"sub,omitempty"`
	// Code is a watch's pairing code, sent once, in the hello that rides in
	// the exchange's handshake message 1. A phone's code travels as the
	// whole of its message 1 payload instead, and a paired watch sends none.
	Code []byte `cbor:"code,omitempty"`
}

Hello is the client's opening message.

type HelloOK

type HelloOK struct {
	// Proto is the negotiated version. ProtoFloor means the app is too old
	// for full mode and should degrade to the frozen subset.
	Proto int     `cbor:"proto"`
	Mode  BoxMode `cbor:"mode"`
	Box   BoxInfo `cbor:"box"`
	Clock Clock   `cbor:"clock"`
	// Caps is presence, not levels. Absent means hide the feature.
	Caps     []string `cbor:"caps"`
	CapsHash string   `cbor:"capsHash"`
	// Modes is every mode this box accepts, in its own presentation order,
	// straight from the box's mode catalogue. Field 1 in the telemetry stream
	// carries an index into this list, which is what keeps lane 0 numeric
	// and its frames a fixed size.
	Modes []ModeInfo `cbor:"modes"`
	// Boot is present only while the box is still starting. A VACUUM can
	// take minutes; saying so beats a spinner that looks hung.
	Boot *BootProgress `cbor:"boot,omitempty"`
	Hint string        `cbor:"hint,omitempty"`
	// Role and Scopes are what this enrolment holds. The app uses them for
	// one thing: deciding what to draw. The app hiding a button is
	// presentation — if the app is wrong and shows it, the box refuses it.
	//
	// Both are sent, and the redundancy is deliberate. Role alone would make
	// the app read a role table it has no reason to hold; the expanded list
	// alone would leave the app unable to say "viewer" in a sentence.
	Role   string   `cbor:"role"`
	Scopes []string `cbor:"scopes"`
	// Subscribed says the optional subscription carried by Hello was accepted.
	// False also covers an older box, where this additive field is absent.
	Subscribed bool `cbor:"subscribed,omitempty"`
	// Cloud is what the phone needs to read this home from FTW Cloud. Every
	// role gets it, and only while an owner has FTW Cloud on. Absent means
	// off, or an older box.
	Cloud *CloudSession `cbor:"cloud,omitempty"`
}

HelloOK answers it.

Sent on the bulk lane, not lane 0. It carries the capability list and the mode catalogue, both of which vary in size with what the box supports, and lane 0 exists precisely so that its frames do not vary in size with anything. A handshake already announces itself by happening, so a variable length here leaks nothing that was not already visible.

type HistChunk

type HistChunk struct {
	TileID  string     `cbor:"tileId"`
	Etag    string     `cbor:"etag"`
	Res     Resolution `cbor:"res"`
	StartMs int64      `cbor:"startMs"`
	// StepMs is the point spacing after aggregation. Res says which store the
	// data came from; the two answer different questions.
	StepMs int64 `cbor:"stepMs"`
	// Series names the columns, in Data order.
	Series []string `cbor:"series"`
	// Data is int32 LE, one contiguous block per series. MISSING is
	// math.MinInt32 — distinct from zero, which is a real reading.
	Data []byte `cbor:"data"`
	// Partial marks the trailing tile that is still filling. Never cached.
	Partial bool `cbor:"partial"`
}

HistChunk is one tile of column-packed samples.

func PackTile

func PackTile(
	res Resolution,
	stride, startMs int64,
	series []string,
	windows map[string][]HistorySample,
	nowMs int64,
) HistChunk

PackTile packs one tile from stored buckets: int32 LE columns, one block per series, MissingSample where the store has no bucket. windows holds each series' buckets at the resolution's stored width; buckets outside the tile are ignored. stride must divide PointsPerTile(res). The tile is partial, and never cached, while it ends after nowMs.

type HistEnd

type HistEnd struct {
	ResActual Resolution `cbor:"resActual"`
	// Gaps are ranges the box knows it cannot serve, and why. The app says
	// "evicted" or "no data" instead of drawing a hole and guessing.
	Gaps []HistGap `cbor:"gaps"`
}

HistEnd closes a query.

type HistGap

type HistGap struct {
	FromMs int64  `cbor:"fromMs"`
	ToMs   int64  `cbor:"toMs"`
	Reason string `cbor:"reason"`
}

HistGap is one such range.

type HistQuery

type HistQuery struct {
	// Series are frozen field names — grid_w, pv_w, battery_w, load_w.
	Series []string `cbor:"series"`
	// Res is the resolution asked for. The box may serve coarser and says so
	// in HistEnd.ResActual.
	Res Resolution `cbor:"res"`
	// FromMs and ToMs are wall clock: history is a question about days people
	// remember, not about box uptime.
	FromMs int64 `cbor:"fromMs"`
	ToMs   int64 `cbor:"toMs"`
	// Have names tiles the app already caches, so an unchanged tile is never
	// resent. That is the entire transfer model on a metered connection.
	Have []HistTileRef `cbor:"have,omitempty"`
	// MaxPoints caps the answer; the box widens the step to stay under it.
	MaxPoints *int64 `cbor:"maxPoints,omitempty"`
}

HistQuery asks for stored series over a window.

type HistTileRef

type HistTileRef struct {
	TileID string `cbor:"tileId"`
	Etag   string `cbor:"etag"`
}

HistTileRef names a cached tile.

type HistorySample

type HistorySample struct {
	// StartMs is the bucket start, wall clock.
	StartMs int64
	// W is the mean power over the bucket, site-signed.
	W float64
}

HistorySample is one stored bucket of one series, in mean watts.

type LogLine

type LogLine struct {
	Ts    int64  `cbor:"ts"`
	Level string `cbor:"level"`
	Src   string `cbor:"src,omitempty"`
	Msg   string `cbor:"msg"`
}

LogLine is one redacted line. Src is an opaque source id for a driver's line, empty for the box's own.

type Logs

type Logs struct {
	Lines   []LogLine `cbor:"lines"`
	Dropped uint64    `cbor:"dropped"`
	More    bool      `cbor:"more"`
}

Logs is the answer to logs.get, oldest first. Dropped counts lines left out to fit one frame; More says older lines remain.

type LogsGet

type LogsGet struct {
	N        uint64 `cbor:"n,omitempty"`
	Level    string `cbor:"level,omitempty"`
	BeforeMs int64  `cbor:"beforeMs,omitempty"`
	AfterMs  int64  `cbor:"afterMs,omitempty"`
}

LogsGet asks for a redacted log excerpt: lines older than BeforeMs, or newer than AfterMs, newest first up to N.

type ModeInfo

type ModeInfo struct {
	Key     string `cbor:"key"`
	Label   string `cbor:"label"`
	Tooltip string `cbor:"tooltip"`
	Tier    string `cbor:"tier"`
}

ModeInfo is one mode as the box presents it. The wire shape of the box's control.ModeInfo.

type Now

type Now struct {
	UptimeMs int64 `cbor:"uptimeMs"`
	// ControlRev is the site's controlRev, which a command expects.
	ControlRev uint64 `cbor:"controlRev"`
	// Fields are the frozen fields, as a snapshot carries them.
	Fields map[string]int64 `cbor:"fields"`
	// Sources are keyed by the frozen source fields, 7 for the grid, 8 for
	// PV and 9 for the battery, so a watch with no field dictionary can still
	// age each reading.
	Sources map[string]NowSource `cbor:"sources"`
	// DispatchBlockedBy names the sources stopping dispatch, as a snapshot
	// does. A watch that sees it knows a charge will be refused.
	DispatchBlockedBy []string `cbor:"dispatchBlockedBy"`
	// Loadpoints are the box's chargers, in its configured order.
	Loadpoints []NowLoadpoint `cbor:"loadpoints"`
}

Now is the home as the Now screen shows it, answered on the exchange in one lane 0 frame (ADR 0009, decision 2). A watch reads it when FTW Cloud is off.

The request is a now with an empty body. What does not fit the frame is left out and the frame flagged TRUNC, as a delta is.

type NowLoadpoint

type NowLoadpoint struct {
	ID      string `cbor:"id"`
	Plugged bool   `cbor:"plugged"`
	// SocPermille is the car's level, absent when the box does not know it.
	SocPermille *int64 `cbor:"socPermille,omitempty"`
	// PowerW is the charger's draw, positive while charging.
	PowerW int64 `cbor:"powerW"`
	// The car on the charger (docs/cars.md): SocPermille is its level, and
	// these say where the level came from and how the box knows the car.
	// While the box asks, Session names the plug-in a tap answers and Choose
	// lists the cars a tap may pick. To fit lane 0, car ids travel here as
	// their 16 bytes, the 32 hex digits decoded: an asking charger with four
	// cars takes about 180 B of the 512 B frame.
	SocSource       string   `cbor:"socSource,omitempty"`
	SocAgeS         *int64   `cbor:"socAgeS,omitempty"`
	SocEstimate     bool     `cbor:"socEstimate,omitempty"`
	Session         string   `cbor:"session,omitempty"`
	CarID           []byte   `cbor:"carId,omitempty"`
	CarIdentifiedBy string   `cbor:"carIdentifiedBy,omitempty"`
	CarCorrected    bool     `cbor:"carCorrected,omitempty"`
	Choose          [][]byte `cbor:"choose,omitempty"`
}

NowLoadpoint is one charger as a watch draws it.

type NowSource

type NowSource struct {
	State SourceState `cbor:"state"`
	// AgeMs is box uptime since the last good reading, or -1 for none.
	AgeMs int64 `cbor:"ageMs"`
}

NowSource is one source's freshness, without its name.

type Observed

type Observed struct {
	Value float64 `cbor:"value"`
	Src   string  `cbor:"src"`
	// UptimeMs is when the value was read back.
	UptimeMs int64 `cbor:"uptimeMs"`
}

type Plan

type Plan struct {
	Rev uint64 `cbor:"rev"`
	// UptimeMs is box uptime when the plan was made.
	UptimeMs int64      `cbor:"uptimeMs"`
	Slots    []PlanSlot `cbor:"slots"`
	// Stale is set when the planner could not run and the box fell back.
	// "Nothing is scheduled" and "we do not know what is scheduled" are
	// different sentences and only one of them would be honest here.
	Stale bool `cbor:"stale"`
	// CeilingW is the import ceiling being defended, nil when there is none.
	CeilingW *int64 `cbor:"ceilingW"`
	// Chargers is each charger's share of this plan, as GET /api/loadpoints
	// reports it, so a plan the box pushes redraws the charger without a
	// read. Absent on a box with no chargers or no planner. An older app
	// ignores it.
	Chargers []PlanCharger `cbor:"chargers,omitempty"`
	// CautionOff is set when the household's planning style asks for
	// forecast caution and this plan uses the point forecast instead,
	// because the caution inputs were invalid or a cautious plan could not
	// keep the plan's limits and departure goals. The box sets it again on
	// every replan and clears it once caution works. An older app ignores it.
	CautionOff bool `cbor:"cautionOff,omitempty"`
}

Plan is what the box intends to do.

Intent, not prophecy. The box revalidates against fresh state every tick, so a plan is what it currently means to do.

type PlanCharger

type PlanCharger struct {
	// ID is the charger's loadpoint id.
	ID string `cbor:"id"`
	// CarID is the session's car, empty while the box does not know which
	// one is plugged in. Always empty until Core keeps cars. A change of
	// it is a plan input: whatever applies session.car.set requests a
	// replan, and the plan reaches the phone as every replan does.
	CarID     string `cbor:"carId,omitempty"`
	PluggedIn bool   `cbor:"pluggedIn"`
	// Pending is set while a newer plan is being made; the windows are then
	// the plan the box goes on acting on until the new one lands. Outdated
	// is set with it, and alone when the plan is not one the box acts on;
	// without Pending the windows are then empty.
	Pending  bool `cbor:"pending"`
	Outdated bool `cbor:"outdated"`
	// GridDeferred says grid-funded charging waits for prices that reach
	// the deadline, as grid_deferred on the HTTP route.
	GridDeferred bool `cbor:"gridDeferred"`
	// GoalRev changes when the charger's goal, ready time, schedule or
	// solar-only choice changes, wherever that was done.
	GoalRev uint32 `cbor:"goalRev"`
	// Windows are the charging windows still ahead, the next one first.
	Windows []PlanChargerWindow `cbor:"windows"`
	// TotalWh is what the plan still means to deliver across its horizon.
	TotalWh int64 `cbor:"totalWh"`
	// ShortfallWh is how far short of the goal the plan leaves the car, in
	// battery watt-hours. Absent when the plan has no goal for it.
	ShortfallWh *int64 `cbor:"shortfallWh,omitempty"`
}

PlanCharger is one charger's share of the plan. Keyed by the charger, never by a car: a car visits chargers (docs/cars.md, srcfl/ftw#1647).

type PlanChargerWindow

type PlanChargerWindow struct {
	StartMs int64 `cbor:"startMs"`
	EndMs   int64 `cbor:"endMs"`
	Wh      int64 `cbor:"wh"`
}

PlanChargerWindow is one stretch the plan charges on a charger. Wall clock.

type PlanReason

type PlanReason string

PlanReason is why a slot looks the way it does.

A stable code, never prose: the box has no idea what language anyone reads, and the app owns every word the user sees.

const (
	ReasonCheapImport     PlanReason = "cheap_import"
	ReasonExpensiveImport PlanReason = "expensive_import"
	ReasonSolarSurplus    PlanReason = "solar_surplus"
	ReasonPeakShaving     PlanReason = "peak_shaving"
	ReasonReserveHeld     PlanReason = "reserve_held"
	ReasonExportPaid      PlanReason = "export_paid"
	ReasonIdle            PlanReason = "idle"
)

type PlanSlot

type PlanSlot struct {
	// StartMs is wall clock, because these are future times a person reads.
	StartMs int64 `cbor:"startMs"`
	// DurationMs is 15 minutes on the box today. Do not assume it.
	DurationMs int64 `cbor:"durationMs"`
	// BatteryW and GridW follow the site convention: positive is power into
	// the site, so a positive BatteryW charges and a negative GridW exports.
	BatteryW int64 `cbor:"batteryW"`
	GridW    int64 `cbor:"gridW"`
	// PriceMinor is the import price in minor units per kWh, nil when the
	// slot's price is not known.
	PriceMinor *int64     `cbor:"priceMinor"`
	Reason     PlanReason `cbor:"reason"`
	// SocPermille is the battery's planned level at the end of the slot, in
	// thousandths, absent when the planner gave none. The same name and unit
	// as the FTW Cloud plan class. An older app ignores it.
	SocPermille *int64 `cbor:"socPermille,omitempty"`
}

PlanSlot is one settlement slot of intent.

type PowerRange

type PowerRange struct {
	Min  float64 `cbor:"min"`
	Max  float64 `cbor:"max"`
	Mean float64 `cbor:"mean"`
}

PowerRange is the least, most and mean watts over a span.

type Price

type Price struct {
	// Zone and Currency label the numbers. Without them the app would have to
	// guess whether 45 is öre or cents.
	Zone     string      `cbor:"zone"`
	Currency string      `cbor:"currency"`
	Slots    []PriceSlot `cbor:"slots"`
	// Stale means these slots do not cover the window that was asked for:
	// they begin after its start, stop short of its end, or there is a hole
	// in the middle. Nothing in this path knows whether a refresh failed,
	// only whether the window came back whole. Tomorrow's rates arrive in the
	// afternoon, so a window asked for at breakfast genuinely ends early, and
	// saying so beats drawing a cliff the market did not have.
	Stale bool `cbor:"stale"`
	// VATPermille is the VAT rate the box applies to TotalMinor, in permille:
	// 250 is 25 %, 255 is 25.5 %. It is the rate after the box's default, so
	// 0 means no VAT. A box that predates the field leaves it out, and a
	// client reads absent as unknown. It lets an app show spot with VAT at
	// the box's own rate instead of a guess. The box applies a rate when it
	// stores a slot and rewrites today and tomorrow every hour, so after a
	// change older slots keep the rate they were stored with.
	VATPermille int64 `cbor:"vatPermille"`
}

Price is the answer to PriceGet.

type PriceGet

type PriceGet struct {
	// FromMs and ToMs are wall clock: prices are about hours a person plans
	// around, not about box uptime.
	FromMs int64 `cbor:"fromMs"`
	ToMs   int64 `cbor:"toMs"`
}

PriceGet asks for the price slots covering a window.

type PriceSlot

type PriceSlot struct {
	StartMs    int64 `cbor:"startMs"`
	DurationMs int64 `cbor:"durationMs"`
	SpotMinor  int64 `cbor:"spotMinor"`
	TotalMinor int64 `cbor:"totalMinor"`
}

PriceSlot is one settlement slot's price.

Minor units per kWh (öre, cents) as integers, because a price is money and money in a float is a rounding argument waiting to happen. Spot is the raw market price; Total is what the household actually pays, tariff and tax included — the box computes it because the box holds the configuration.

type Principal

type Principal struct {
	Client   string `cbor:"client" json:"client"`
	ClientID string `cbor:"clientId" json:"clientId"`
	Ticket   string `cbor:"ticket" json:"ticket"`
}

Principal says who an agent row is for. Display and audit only: the role decides what it may do.

type ProtoRange

type ProtoRange struct {
	Min int `cbor:"min"`
	Max int `cbor:"max"`
}

type PushSentence

type PushSentence struct {
	Title string
	Body  string
}

PushSentence is one lock-screen sentence, exactly as the app wrote it. {arg} placeholders are filled from the event's own facts and nothing else.

type Refusal

type Refusal struct {
	Code string
	Args map[string]any
}

Refusal is a refusal on its way to the wire: a registry code and its machine-readable args. The box's layers return it so the one that answers the caller need not translate.

func Refuse

func Refuse(code string, args map[string]any) *Refusal

Refuse builds a Refusal.

func (*Refusal) Error

func (r *Refusal) Error() string

type Request

type Request struct {
	ReqID       string         `cbor:"reqId" json:"reqId"`
	Agent       string         `cbor:"agent" json:"agent"`
	Op          string         `cbor:"op" json:"op"`
	Args        map[string]any `cbor:"args" json:"args"`
	Why         string         `cbor:"why" json:"why"`
	AtMs        int64          `cbor:"atMs" json:"atMs"`
	ExpiresAtMs int64          `cbor:"expiresAtMs" json:"expiresAtMs"`
	State       string         `cbor:"state" json:"state"`
}

Request is one durable change an agent asked for.

type Resolution

type Resolution string

Resolution is a history resolution the box actually stores.

const (
	// ResN1h comes from the power_history.
	ResN1h Resolution = "1h"
	// ResN5m comes from the power_history.
	ResN5m Resolution = "5m"
)

type SessionTerminate

type SessionTerminate struct {
	Reason string `cbor:"reason"`
}

SessionTerminate ends the session from the box's side.

type SetupCall

type SetupCall struct {
	JSON []byte `cbor:"json,omitempty"`
}

SetupCall carries a bounded JSON request to a named setup operation. It cannot choose an HTTP route, method, headers or another user's identity.

func DecodeSetupCall

func DecodeSetupCall(raw []byte) (SetupCall, error)

type SignedFor

type SignedFor struct {
	// BoxKey is the box's X25519 static key, as in the pairing QR code.
	BoxKey []byte
	// DeviceID is the signing phone's device id.
	DeviceID string
}

SignedFor names the box and the phone an approval belongs to.

type SignedOffer

type SignedOffer struct {
	O   []byte `cbor:"o"`
	Kid string `cbor:"kid"`
	Sig []byte `cbor:"sig"`
}

SignedOffer is an offer as it travels: O is the offer's deterministic CBOR, Sig FTW Cloud's offer key's signature over OfferBytes(O), and Kid names that key. It goes base64url, without padding, in a link's fragment.

type Snap

type Snap struct {
	UptimeMs int64 `cbor:"uptimeMs"`
	// ControlRev is monotonic per site, bumped by every mutation of
	// controllable state. A command carries the rev it expected.
	ControlRev uint64                `cbor:"controlRev"`
	Dict       map[string]FieldDef   `cbor:"dict"`
	Fields     map[string]int64      `cbor:"fields"`
	Sources    map[string]SourceWire `cbor:"sources"`
	// DispatchBlockedBy names the sources currently stopping dispatch. It
	// connects to the box's own invariant that stale meter data stops
	// dispatch, so the app can say why nothing is happening rather than
	// looking broken.
	DispatchBlockedBy []string `cbor:"dispatchBlockedBy"`
}

Snap is a full site snapshot. Bulk lane: it carries the dictionary and every source, so its size depends on how many devices the site has.

type SourceState

type SourceState string

SourceState says whether a device is answering. It is orthogonal to the carrier state: "connected, but the inverter went quiet" needs both.

const (
	SourceLive    SourceState = "live"
	SourceLagging SourceState = "lagging"
	SourceStale   SourceState = "stale"
	SourceDown    SourceState = "down"
	SourceNever   SourceState = "never"
)

type SourceWire

type SourceWire struct {
	Kind string `cbor:"kind"`
	Name string `cbor:"name"`
	// LastOkMs is box uptime at the last good reading, not wall clock.
	LastOkMs     int64       `cbor:"lastOkMs"`
	StaleAfterMs int64       `cbor:"staleAfterMs"`
	State        SourceState `cbor:"state"`
}

SourceWire is one device's freshness.

Readings point at a source rather than carrying their own timestamp. That keeps a delta at tens of bytes while still answering the question people actually have: the box is fine, but the inverter went quiet 40 seconds ago.

type Sub

type Sub struct {
	// Bucket is the lane 0 frame size, fixed by the first subscription: 256 or
	// 512. A later sub may change only Hz.
	Bucket int `cbor:"bucket"`
	// Hz is the cadence: 1 in the foreground, 0.2 when the document is hidden.
	// The app sends another sub when its visibility changes.
	Hz float64 `cbor:"hz"`
}

Sub starts the telemetry stream.

type Tick

type Tick struct {
	Seq      uint64 `cbor:"seq"`
	UptimeMs int64  `cbor:"uptimeMs"`
}

Tick says nothing changed.

Sent anyway, in the same bucket. Over the relay it goes on every pulse: silence would tell the relay operator that nothing happened in the house that second. Through FTW Cloud it is the beat that goes when nothing has moved for the subscribed period, so the phone can tell a quiet house from a lost session.

Directories

Path Synopsis
Package appwire is the box's half of the wire the FTW app speaks: the frame codec and the Noise session that carries it.
Package appwire is the box's half of the wire the FTW app speaks: the frame codec and the Noise session that carries it.
Package cloudwire is the wire format between an FTW box and FTW Cloud: the unpadded frame, the signed envelope, the ids, the message bodies and the scope each class belongs to.
Package cloudwire is the wire format between an FTW box and FTW Cloud: the unpadded frame, the signed envelope, the ids, the message bodies and the scope each class belongs to.
Package energywire names the daily energy report: one closed UTC day of one home as six whole-kWh sums, and nothing that says whose.
Package energywire names the daily energy report: one closed UTC day of one home as six whole-kWh sums, and nothing that says whose.
Package fleetwire names the anonymous daily report, without a home id.
Package fleetwire names the anonymous daily report, without a home id.
Package ohttp is Oblivious HTTP (RFC 9458) for one suite: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 and AES-128-GCM, with the known-length Binary HTTP messages (RFC 9292) it carries.
Package ohttp is Oblivious HTTP (RFC 9458) for one suite: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 and AES-128-GCM, with the known-length Binary HTTP messages (RFC 9292) it carries.
Package reportwire is how the box's daily reports reach FTW Cloud: each report alone, as one padded inner request (a Binary HTTP message, package ohttp).
Package reportwire is how the box's daily reports reach FTW Cloud: each report alone, as one padded inner request (a Binary HTTP message, package ohttp).

Jump to

Keyboard shortcuts

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