Operations API Draft
Draft bidirectional OpenAPI contract for operational data entering and leaving BetterFleet, including duties, blocks, assignments, vehicle availability, yard positions, charging, dispatch status, recommendations, authentication, change feeds, and webhooks.
Integration direction
The configured provider is authoritative for duties, blocks, assignments, vehicle operational state, and yard positions. It pushes changes to BetterFleet through domain-specific ingress endpoints with a shared source envelope. Provider-hosted snapshots and a cursor-based change feed support initialisation, reconciliation, and recovery after a delivery gap.
BetterFleet exposes current operational state through resource reads, its ordered change feed, and outbound webhooks. Receipt through an ingress endpoint confirms transport and data validation. BetterFleet's internal business logic decides whether and when accepted source data changes active operational state. Manual schedule and dispatch-sheet uploads remain complementary inputs to the same reconciliation process.
Current state: this is a pre-release design contract. Individual operations require implementation and integration validation before production use.
GTFS Schedule and TODS input
Use the GTFS Schedule reference for general service data and the TODS reference for operational supplements, including non-revenue trips and runs. The schedule-datasets ingress accepts the paired standard archives. Provider operational updates refer to that dataset using its source identities and service date.
Blocks link to trips, trips to routes and shapes, and shapes to ordered points in shapes.txt. This supplies planned paths for later block-energy estimation, including pull-out, pull-in and deadhead travel. Missing geometry remains an explicit gap. Vehicle and environmental inputs are needed for energy modelling; ingestion preserves the schedule and its distance provenance. TODS runs describe personnel work and must not cause the same vehicle trip to be counted twice.
Dispatch status contract
dispatch_status reports one public result:
ready, at_risk, not_ready,
no_active_requirement, or unknown. A
no_active_requirement result requires complete, current, authoritative
evidence that no requirement is active under the depot mode and source-authority rules.
Missing, partial or stale evidence cannot establish absence. Reason codes distinguish unresolved requirement context from
insufficient readiness evidence when the result is unknown.
BetterFleet evaluates six evidence areas: requirement context, timing,
operational availability, energy sufficiency, yard access, and charging feasibility.
These areas guide calculation completeness, precedence, diagnostics, and testing.
The API exposes requirement_context; calculation dimensions remain internal.
- Requirement context: one active duty or direct Ready-by target for the vehicle, or explicit confirmed absence or unresolved context. Duty context retains its assignment and service date; a direct target needs no duty or block and uses its depot-local Ready-by calendar date.
- Timing: prior work, turnover, travel, and departure timing leave the vehicle available by the requirement deadline.
- Operational availability: no out-of-service condition or operational hold prevents the vehicle from meeting the requirement.
- Energy sufficiency: predicted usable departure energy meets the requirement, including reserve.
- Yard access: the vehicle is at the applicable depot and can reach pull-out in time, considering position, occupancy, obstructions, and movement constraints.
- Charging feasibility: charging is unnecessary or can be completed before departure within vehicle, charger, connector, site, time, and control constraints.
The public API exposes the overall decision, stable reason codes, relevant evidence,
source and freshness information, and assessment timestamps. Prediction confidence,
when present, applies only to predicted values and does not qualify
dispatch_status.
This draft revision replaces no_next_duty with no_active_requirement
and duty-context reason codes with REQUIREMENT_CONTEXT_MISSING and
REQUIREMENT_CONTEXT_CONFLICT. Draft consumers must update enum handling
and read the required context in responses and events. It adds no target-write endpoint
or charging-control authority.
A structured factor breakdown may be added later if a consumer needs it, using stable
public categories rather than internal rules, weights, or model nodes.
Sources and time
SoC has two real sources: chargepoint and
telematics, plus unknown when the source is
not known. Charger readings received through OCPP or a charging session
use chargepoint. Older stored charge_point
values map to that spelling. These source names apply across telemetry,
SoC, dispatch evidence and range-scenario inputs. Keep the upstream system
name in source_system where available. Modelled and projected
describe how a value was calculated, not a separate measured source.
| Time field | Meaning |
|---|---|
observed_at | When the source measured the value. |
received_at | When BetterFleet received the request or observation. BetterFleet sets this time. |
last_updated on provider records | When the provider last changed its source record. |
last_updated on BetterFleet records | When BetterFleet last changed its returned record or read model. |
snapshot_at | The fixed read cut shared by all pages or batch items. |
generated_at in provider snapshot context | When the provider built its source snapshot, including provider-hosted recovery responses. |
generated_at in BetterFleet responses | When BetterFleet built its response. Does not itself change last_updated. |
assessment_time / prediction_time | The operational time being assessed or predicted. |
service_date / dispatch_date | The depot-local operating day, including applicable work after midnight. |
published_at | When the webhook event was published. |
occurred_at | When the operational event happened; publication can be later. |
A depot snapshot shows the latest-known values at
page.snapshot_at. It has no fixed lookback window and is
not an average. A SoC reading measured at 08:55 can appear beside a
location measured at 08:59 in a 09:00 snapshot. Use each field's
freshness.observed_at and is_stale to judge it.
Freshness limits come from the field's configured policy; there is no
single API-wide duration. Keep a valid latest-known reading when it is
stale and return is_stale: true. Age alone does not hide it.
A null value means unavailable or excluded by a filter,
never zero. A stale displayed value does not establish readiness or
make it usable for a prediction.
For telemetry history, use
GET /pre/vehicles/{vehicle_id}/telemetry-snapshots?from=...&to=....
It selects stored snapshots by last_updated, from inclusive
to exclusive, up to 90 days per request. Each field still has its own
observation time. A prediction time is the time to assess, not a history window.
Vehicle model override units
| Override | Unit or scale |
|---|---|
| Battery health and relative humidity | Percent, 0 through 100 inclusive. A value of 95 means 95 percent. |
| Efficiencies, fresh-air ratio and energy recovery factor | Dimensionless fraction, 0 through 1 inclusive. A value of 0.95 means 95 percent. |
| Mass / power / battery capacity / speed | kg / kW / kWh / km/h, as named on each field. |
| Passenger values | Whole-number counts of passengers. |
| Heater and chiller types | Text identifiers, with no numeric unit. |
For example, use battery_state_of_health: 95 and battery_efficiency_one_way: 0.95. Null or omission means no override; zero is a supplied value where allowed. Values are not rescaled or clamped.
| Result | Response | Next action |
|---|---|---|
| Invalid supplied input | 422 ProblemDetails, with a field pointer and reason in errors. | Correct the listed fields before retrying. For example, efficiency 95 is invalid; use 0.95 for 95 percent. |
| Insufficient vehicle data | 200 with predicted_range_km: null and a warning explaining the missing data. | Resolve the data gap before relying on a prediction. Null does not mean zero range. |
| Unknown or inaccessible reference | 404 ProblemDetails. | Check the vehicle/block reference and permitted scope. |
| Rate limit or service failure | 429 or 503 with retry guidance. | Retry after the indicated delay. |
Outgoing change payloads
An upsert must carry a resource body matching its declared resource_type. A delete must carry a tombstone with the same resource type and no resource body. The inactive field can be omitted or null. Mixed or unknown outer body fields are invalid; shared fields do not decide the resource type.
Recovery and history use the same rules. The server must also check canonical IDs and depot/tenant ownership before publishing a change. If an internal malformed entry reaches a read, return an error instead of skipping it or advancing the recovery cursor. The client keeps its last fully processed cursor. ID matching and access checks still need runtime validation.
Webhook replay status
Creating a replay returns 202, a replay record and a Location for GET /pre/webhook-subscriptions/{subscription_id}/replays/{replay_id}. Read that record to check whether it is queued, running, completed or failed. Job acceptance does not mean delivery completed.
completed means all selected events received a successful HTTP acknowledgement, including a replay with zero matches. It does not prove the receiving system applied them. Temporary delivery failures remain under the retry policy. failed means the job aborted or a delivery permanently failed.
The record shows total, delivered and permanently failed event counts, lifecycle times and failure details. A total of null means enumeration is incomplete; retries do not increase event counts. A failed job still has a readable status record. Inspect attempts using the subscription delivery log with ?replay_id=.... All reads remain scoped to the subscription and caller. Record retention remains to be agreed; an absent record does not prove success.
Webhook input validation
Creating or changing a subscription requires an absolute HTTPS callback URL with a host and no fragment. Updates must contain at least one supported field: target_url, event_types, filter or active. Reject unknown fields, including filter typos, before applying any update. Omitted fields keep their current values.
For replay, supply either a non-empty after cursor or both from_time and to_time. Do not mix them or use null, blank or missing values. The time range includes its start, excludes its end, must end after it starts and spans at most 90 days. Replay still follows journal order.
Invalid input returns 422 with field errors. An invalid or mismatched cursor returns 400; an expired cursor returns 410. URL parsing, time-range comparison and cursor checks require runtime validation. No replay is queued until validation passes.
Numeric limits
Latitude must be between -90 and 90, and longitude between -180 and 180, in decimal degrees. A supplied rated battery capacity override must be greater than zero kWh; null or omission means no override. Predicted range must be zero or greater, or null with a warning when unavailable. Reject invalid submitted values under the request, page or item rules; do not clamp them into range.
Both charging target SoC values use 0 to 100 percent, and the minimum must not exceed the maximum. Equal targets are valid. The server must compare the pair before returning a queue page. If internal data breaks this rule, return an error instead of publishing, swapping, clamping or silently dropping the invalid item. The schema checks individual bounds; the comparison still needs runtime validation.
Timestamp ownership
Provider duties, blocks, assignments and availability records carry the provider's last_updated. Provider snapshot generated_at says when the provider built that snapshot, whether pushed to BetterFleet or fetched for recovery. BetterFleet preserves these source times on ingestion.
BetterFleet sets received_at when it receives a request or observation. Its returned records use last_updated for changes to the BetterFleet read model, and generated_at for response generation. Polling does not itself update the record. Receipt does not prove application or approval.
For example, the provider changes an assignment at 08:55, BetterFleet receives it at 08:57 and updates its read model at 08:58. A response built at 09:00 has those distinct source, receipt, record-update and response times. For measured values, use observed_at to judge age; receipt or processing does not make an old observation fresh. Recovery still follows journal order.
Assignment records
An assignment links a vehicle to a duty or block of work on an operating day, from its effective time. assigned requires a named vehicle and at least one valid duty or block. If both are supplied, the block must belong to that duty in the same source, depot and operating day. A bad reference rejects the snapshot page or the individual change item, according to the submission rules.
assigned means allocated to work. It does not mean ready, charged, plugged in or already doing the work. Use dispatch_status for readiness. unassigned means no current vehicle allocation; cancelled means the allocation has been withdrawn.
Journal order and event time
For an event timeline, use GET /pre/depots/{depot_id}/change-history?from=...&to=...&order_by=occurred_at. Omit order_by for journal order. sort_order accepts asc or desc, defaulting to asc. Both keys use change_id to break ties.
History requires explicit event-time bounds of at most 90 days per query. It browses entries retained for 90 days from journal commit, including late events with older occurrence times. Pages keep a fixed read cut; start a fresh query to see later arrivals. History cursors expire after one hour and end at null. Use the journal recovery feed for ongoing sync; it does not accept history sort or time controls.
The depot change feed and retained webhook replay follow journal_sequence, assigned when BetterFleet commits each journal entry. occurred_at says when the source event happened. It does not set recovery order. An 08:00 observation received after a 09:00 event gets a later journal sequence, so it remains after a cursor already saved by a consumer.
Each feed traversal fixes an upper journal position. Pages scan to that position; the next poll includes later entries. Keep the returned opaque cursor after processing the page, including an empty or final page. Filtered sequences can have gaps. Do not build cursors from timestamps or sequence numbers.
A snapshot and its recovery cursor must share one committed read cut. State changes and journal entries must commit together. Retries and replay keep the original event identity and sequence. Live webhooks may arrive out of order; a higher sequence does not prove earlier entries were processed. Provider recovery uses the provider's own journal order and cursors. These concurrency and recovery guarantees still need runtime validation.
Snapshot pages and independent change batches
A submitted snapshot page passes or fails as a whole. Validate every record, scope and page context first. Reject a bad page with 422 and field errors; accept none of its records. Keep earlier accepted pages staged for retry. A final-page marker cannot establish absence until every page from 1 through the final page passes validation in the same source scope and revision.
Only a complete, fully validated snapshot can establish source absence. Partial, unavailable, missing-page and rejected-page snapshots never imply deletions. Identical page retries return duplicate; conflicting retries fail validation. The receipt reports whether pages are still collecting or the snapshot is complete, partial or unavailable. Internal application remains a separate decision.
Independent change and position-observation batches first validate the receipt envelope: the correct array, 1 to 1000 items and a non-empty event ID on each item. A malformed envelope rejects the request before accepting items. After that, validate each item separately. Return one result per input item in order, with its index, event ID, status and rejection problem or null. A bad payload does not discard valid siblings. HTTP 202 reports receipt results, even if all items are rejected; it does not confirm application. These batches do not provide an atomic group of dependent changes.
Single, collection and batch rules
Single and multi-resource forms use the same fields, enums, filters and per-resource payloads. Collections list resources with cursor pagination. Batches perform a bounded calculation or update and return one result per input item, in input order. Each operation states its limits and request/item failure rules.
| Task | Single vehicle | Multiple vehicles |
|---|---|---|
| Latest telemetry | Zero or one snapshot in a collection. | Paginated depot collection; all vehicles or 1 to 100 distinct IDs. Vehicles without records contribute no items. |
| Telemetry history | Paginated stored snapshots; explicit bounds, at most 90 days per request. | Read each vehicle's history. Depot history is outside this draft. |
| Standard range prediction | One prediction payload. | 1 to 100 distinct depot vehicles; one success, unavailable or error result per input item. |
| Advanced range scenario | One calculation with explicit modelling overrides, using the shared prediction response. | No batch scenario operation in this draft. |
soc_source works on single-vehicle current/history reads and depot current reads. A mismatch returns soc: null without dropping the snapshot. Keep matching valid stale SoC with its flag. History preserves source selection and freshness as of the stored record update; the query read cut stays fixed across pages.
Single and bulk predictions always return predicted_range_km: a non-negative number, or null with a warning when unavailable. Both include the input cut, evaluation time and response time. Bulk items share those times and the depot, and keep input order. Item failures preserve successes; a shared execution failure returns 503 with retry guidance. Batch compute limits still need load validation.
Independent state dimensions and date defaults
vehicle_state separates location (at_depot, away_from_depot, unknown), movement (stationary, moving, unknown), and availability (available, unavailable, unknown). Maintenance and operational holds are availability reasons. Read charging from session/connector evidence and readiness against a duty or direct target from dispatch_status.
A bus can be at the depot, stationary, unavailable for maintenance, and charging at the same time. Yard space state likewise separates physical occupancy, availability, and reservations with start and end times. An occupied space can also be reserved or unavailable. Occupancy does not prove vehicle identity. The former yard ready/parked/waiting field is removed.
For read queries, omit service_date or dispatch_date to use the current operating day in the depot timezone and operating-day rules. For Lite vehicle dispatch-status reads, direct targets use their Ready-by calendar date; omission resolves the current depot-local calendar date. The response returns the resolved date and keeps it across pages. Omitted assessment or prediction time means now. Empty strings are invalid; only nullable prediction time also accepts null. History bounds stay explicit.
Submitted duty and assignment snapshots require context.service_date, even when empty, so delayed receipt or replay cannot change their day. Current availability and yard snapshots use observation/effective times instead.
New in 0.9.0-pre
On GET /pre/depots/{depot_id}/vehicle-telemetry-snapshots,
choose which SoC source to expose:
| Request | SoC result |
|---|---|
No soc_source filter | The combined source-of-truth model selects one current SoC using both sources and the shared selection rules. It does not average readings. |
?soc_source=chargepoint | Expose the selected SoC only when it is charger-derived. |
?soc_source=telematics | Expose the selected SoC only when it is telematics-derived. |
With a source filter, return the matching latest-known measured SoC
with its observation time and freshness.is_stale, even
when stale. For example, a 75% reading from 08:40 remains 75% in a
09:00 snapshot, with is_stale: true if its age limit is
10 minutes. Return soc: null when the selected reading
has another source, is missing, invalid, not actual or superseded.
Keep the vehicle and its other fields. The filter does not select a
different reading, revive an older value or prove a current plug-in.
POST /pre/depots/{depot_id}/range-predictions accepts
1 to 100 explicit vehicle IDs, a shared optional prediction time and
an optional block per vehicle. It returns one result per vehicle:
success, unavailable or error.
All items use the same input snapshot and evaluation time. A failed
item does not discard successful results. The existing single-vehicle
prediction endpoint remains available. Batch size and execution limits
need runtime load validation before release.
Migration from 0.8.0-pre: map SoC/telemetry sources
charging_session and ocpp to
chargepoint; map vehicle-side bms and
oem_api to telematics. A calculated value
with no known measured source uses unknown, not
derived. This is a draft contract; no runtime change or
connected feed is claimed.