# fit-encoder
Writes FIT activity files, the binary format that sports watches and bike computers record
activities in and that training services import. `no_std`, no allocation, no panics on the write
path, and no seeking: the header goes out first, the CRC last, so a file can be streamed to a
serial port, a radio link or append-only flash.
An activity is written as it happened, as timed calls: it starts, a session starts for each
sport (a triathlon has five, with its transitions), records arrive, laps end, the timer pauses
and resumes, and it ends; in a pool swim lengths end, in a strength session sets end, rests
start and end, and heartbeats arrive. The encoder writes the rest: timer events, each lap,
session and activity message with its times, timer totals and what its records, lengths and
sets add up to, and their numbering and counts. A call out of order, or a time before one
already written, is refused, and a refused call writes nothing. An activity that has started
can always be ended, even at FIT's 4 GiB limit.
```rust
use fit_encoder::*;
// A swim, a transition and a run, from a stored log of heart rates at 1 Hz per leg.
fn triathlon(w: &mut Writer, start: Timestamp, legs: &[(Sport, SubSport, &[u8])]) -> Result<(), Error> {
let at = |s: u32| start.checked_add(s).unwrap();
w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1).product_name("My watch"))?;
let mut t = 0;
for &(sport, sub_sport, hr) in legs {
w.session(at(t), sport, sub_sport)?;
for &bpm in hr {
w.record(&Record::new(at(t)).heart_rate(bpm))?;
t += 1;
}
}
w.end(at(t))
}
let start = Timestamp::from_unix(1_764_590_400).unwrap();
let legs: [(Sport, SubSport, &[u8]); 3] = [
(Sport::SWIMMING, SubSport::OPEN_WATER, &[120, 131, 140]),
(Sport::TRANSITION, SubSport::SWIM_TO_BIKE_TRANSITION, &[142]),
(Sport::RUNNING, SubSport::STREET, &[150, 155]),
];
let mut buf = [0u8; 2048];
```
A pool swim is its lengths, and a strength session its sets; a rest is bracketed by two calls.
```rust
use fit_encoder::*;
let start = Timestamp::from_unix(1_764_590_400).unwrap();
let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
let mut w = file.writer();
w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
w.pool_swim(start, Pool::meters(25.0)).unwrap();
w.length(at(24), &Length::swum(SwimStroke::FREESTYLE, 17)).unwrap();
w.length(at(49), &Length::swum(SwimStroke::FREESTYLE, 18)).unwrap();
w.rest(at(49)).unwrap(); // the lap of two lengths, 50 m, ends here
w.end_rest(at(79)).unwrap(); // the rest, an idle length in a lap of its own
w.length(at(110), &Length::drill()).unwrap();
w.session(at(200), Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
w.beat_intervals_ms(&[812, 790, 805]).unwrap(); // from a chest strap, as they arrive
let squat = Exercise::new(ExerciseCategory::SQUAT);
w.set(at(240), &Set::new().exercise(squat).repetitions(10).weight_kilograms(60.0)).unwrap();
w.rest(at(240)).unwrap();
w.end_rest(at(330)).unwrap();
w.set(at(370), &Set::new().exercise(squat).repetitions(8).weight_pounds(135.0)).unwrap();
w.end(at(370)).unwrap();
assert_eq!(&file.finish().unwrap().written()[8..12], b".FIT");
```
The header holds the length of the messages after it, so `write` runs the source twice: once
to size the file, then to write it. It must make the same calls both times, as one reading a
stored log does; the second pass checks that it did.
A sink that can go back over what it wrote, such as a file or memory, takes a file in one pass
instead, as its calls arrive: a live recording, or a conversion read once. The bytes are the
same.
```rust
use fit_encoder::*;
let start = Timestamp::from_unix(1_764_590_400).unwrap();
let mut buf = [0u8; 2048];
let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
let mut w = file.writer();
w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
w.session(start, Sport::WALKING, SubSport::GENERIC).unwrap();
for (s, bpm) in (0..).zip([118, 120, 121]) {
w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(bpm)).unwrap();
}
w.end(start.checked_add(3).unwrap()).unwrap();
let sink = file.finish().unwrap();
assert_eq!(&sink.written()[8..12], b".FIT");
```
A field the FIT profile does not define is a developer field: the application that adds it
declares itself and the field, and the file carries both, so readers show it by its name and
units. Each field belongs to records, laps or sessions, and its handle takes values of its type.
```rust
use fit_encoder::*;
const APP: [u8; 16] = *b"my-app-uuid-0001";
let start = Timestamp::from_unix(1_764_590_400).unwrap();
let file = write(SliceSink::new(&mut buf), Options::new(), |w| -> Result<(), Error> {
w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1))?;
let app = w.developer(&Developer::new(APP).application_version(100))?;
let smo2: RecordField<u8> = w.declare(&app.field(0, "SmO2").units("%"))?;
let feel: LapField<u8> = w.declare(&app.field(1, "Feel").units("1-10"))?;
w.session(start, Sport::RUNNING, SubSport::TRAIL)?;
for (s, (bpm, oxygen)) in (0..).zip([(140, 64), (144, 61), (149, 58)]) {
w.record_with(&Record::new(at(s)).heart_rate(bpm), &[smo2.value(oxygen)])?;
}
w.developer_value(&feel, 7)?;
w.end(at(3))
})
.unwrap();
assert_eq!(&file.written()[8..12], b".FIT");
```
A message or field of the profile the crate does not model goes in raw, by its number, base
type and bytes: `Writer::raw_message` writes a whole message, such as a gear change, and
`RawField`s in `Writer::record_with` add to a record. They go through the same layouts and
checks as the rest, but their meaning is the caller's.
An async sink, such as flash or a radio link under an async executor, is awaited between
calls, never during one, so writing a file never blocks the executor for longer than a call
takes to encode. `write_async` and `AsyncOnePass` write the same bytes as `write` and `OnePass`.
```rust,ignore
use fit_encoder::*;
async fn log(sink: impl AsyncPatchSink, start: Timestamp, hr: &[u8]) -> Result<(), Error> {
let mut file = AsyncOnePass::new(sink, Options::new());
let mut w = file.writer();
w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
w.session(start, Sport::WALKING, SubSport::GENERIC).await?;
for (s, &bpm) in (0..).zip(hr) {
w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(bpm)).await?;
}
w.end(start.checked_add(60).unwrap()).await?;
file.finish().await.map_err(|_| Error::Sink)?;
Ok(())
}
```
Without features it is `no_std` and allocates nothing. `alloc` adds `to_vec` and `VecSink`;
`std` adds `IoSink`, for any `std::io::Write` and, with `Seek`, one pass, and
`Timestamp::from_system_time`. `async` adds the async sinks and drivers, and `embedded-io` and
`embedded-io-async` add `EmbeddedIo`, which makes a sink of either crate's `Write` and, with
`Seek`, a patch sink; its errors are `EmbeddedIoError`, the writer's or a patch past the end,
and are `embedded_io` errors themselves.
On a target without atomic compare-and-swap, such as `thumbv6m-none-eabi` or
`riscv32i-unknown-none-elf`, the crate depends on
[`critical-section`](https://crates.io/crates/critical-section), and the application must
provide its implementation.
## What it writes
- Messages: `file_id`, `device_info` (the creator and any sensors), `event` (timer start, stop
and stop-all), `sport`, `record`, `length`, `set`, `hrv`, `lap`, `session` and `activity`;
`developer_data_id` and `field_description` for developer fields; and any other message,
given raw.
- Records with any of position, altitude, heart rate, cadence, distance, speed, power and
temperature, each set in its unit (`distance_advanced_meters`, `speed_meters_per_second`,
`Altitude::barometric_meters`, ...).
- Laps and sessions with their times, timer totals, sport, and what their records add up to:
distance, average speed, average and maximum heart rate, cadence and power, maximum speed,
ascent and descent, average and maximum temperature, start and end positions and bounding
box; and the lap and session counts.
- Pool swims: the pool's length and unit on the session, and each length with its times,
stroke, stroke count, speed and stroke rate, or as idle for a rest; and, from the lengths,
each lap's and session's distance, length counts, first length, strokes, distance per stroke,
stroke (mixed if it changed), stroke rate and fastest length.
- Strength sets, active and rest, with their times, exercise category and name, repetitions
and weight with the unit to show it in; the session's total repetitions.
- Heartbeat intervals for heart rate variability, in `hrv` messages.
- Developer fields of any number type or a string on records, laps and sessions, with their
names, units, scale and offset, and the profile field each stands in for, if any. A record
takes its values as it is written; a lap or session takes the last value given while it was
open.
- Raw fields the crate does not model, on records or in raw messages.
- The header with its CRC, protocol 2.0, and the file CRC.
- Normal record headers, or compressed timestamp headers for records within 31 s of the
previous timestamp. The protocol allows them, and `fitdecode`, `fitparse` and `muktihari/fit`
read them, but Garmin's Python and JavaScript SDKs (21.223) refuse them, so they are off
unless asked for.
- Only the fields a message has values for: its layout is those fields, and each layout's
definition is written before its first message, and again when another layout has taken its
local message type. A value that means "none", such as a heart rate of 255, is refused
rather than written, as is a string holding a NUL, which readers would cut short there.
Developer fields are part of a layout too.
The sink is a one-method trait, `Sink`, so a UART or a flash writer takes a few lines; it can
also be told the file's length before the first byte. `PatchSink` adds the one method one pass
needs, and `AsyncSink` and `AsyncPatchSink` are the same, awaited. `SliceSink` and `FnSink`
come with the crate, and `size` gives a file's length without writing it.
It does not read FIT files: [`fitparser`](https://crates.io/crates/fitparser) and
[`rustyfit`](https://crates.io/crates/rustyfit) do, and this crate's tests read every file they
write with both.
`examples/hr_activity.rs` writes an hour of made-up indoor cardio to a file in one pass.
## Design choices
Where FIT or the services that import it leave a question open, the encoder picks an answer.
Each is below with the alternative and the reason, so you can tell whether yours differs.
- **The encoder keeps the distance.** A record gives how far it moved since the last
(`distance_advanced_meters`); the encoder keeps the total, writes it in each record, and
takes every lap and session distance as the difference of those totals. Records written
this way never go backwards, so a sensor whose count resets or wraps, or a leg that starts
again from zero, cannot corrupt the file. A total from an odometer (`distance_meters`) is
accepted too, and one below the last is refused (`Error::DistanceWentBack`) rather than
guessed at as a reset. If your sensor's count resets, turn it into increments with your own
reset rule.
- **Distance counts from the start.** The first lap counts from zero, not from the first
record with a distance, so a late GPS fix or sensor still adds up to the last record's
total.
- **Nothing is recorded while the timer is paused.** A record, length or set then is refused
(`Error::Paused`), as FIT's timer stop and start leave a gap with no records. Every summary
therefore covers running time: the average speed is the distance over the timer time, as
the profile defines it, so a distance given after a pause should leave out what was covered
during it. To keep data from a pause, don't pause.
- **Ascent counts sustained climbs.** Altitude carries its source, which sets how far it must
climb or fall from the extreme it left before ascent or descent counts it, all of it: 2 m
for a barometric altimeter and 10 m for satellite altitude, as Strava publishes; every change
for `Altitude::smoothed_meters`, if you filter it yourself; or your own threshold. Counting
every 0.2 m step would turn a flat hour of sensor noise into hundreds of metres of climbing.
Until the first climb or fall, the extremes are the lowest and highest so far, so a rise
short of the threshold followed by a long fall counts the fall from the top. A pause keeps
the filter but not the jump across it, which isn't a climb; a change of source starts it
again, and so does each session, so a leg's ascent is its own: a rise short of the threshold
when a leg ends counts in neither leg. A lap's ascent is what its session's gained during it,
so laps add up to their session; a climb counts in the lap where it passes the threshold.
- **Altitude is averaged over the last few records before the threshold**, unless the caller
smoothed it, since otherwise each turn counts from a noise spike. The average trails the
altitude, so a session that ends mid-climb leaves out the last of it, and satellite altitude
that wanders for minutes still counts some of its wandering.
- **A maximum speed below the average is left out.** Speed samples can miss the fastest part
of a lap, so the lap has no maximum rather than a false one.
- **A bounding box across ±180° wraps.** The narrower of the two possible boxes is taken, so
east is less than west for a box that crosses the antimeridian, as in RFC 7946, rather than
one round the whole globe.
- **Summaries are derived, never given**, so they cannot disagree with the records or each
other. A summary its field can't hold is left out rather than making the file unwritable.
- **A wall-clock time is a date.** `Timestamp::from_unix` and `from_system_time` refuse times
before `Timestamp::FIRST_DATE`, which FIT readers take as seconds since the device started;
`Timestamp::from_fit` writes such a time on purpose.
- **A pool swim's distance is its lengths.** Each lap and session covers the pool's length for
each length swum, drills included, as Garmin's watches count it, so its distance cannot
disagree with its lengths. Its speed and stroke rate come from the lengths too, so a record
that gives distance, speed or cadence in a pool swim is refused (`Error::GivenByLengths`)
rather than letting two sources disagree.
- **A pool swim's average speed is over its timer time**, rests included, as the profile
defines it. Garmin's watches give the session the speed over its stroked lengths alone,
without rests and drills.
- **A rest in a pool swim is a lap of its own**: `rest` ends the lap of lengths before it, and
`end_rest` writes one idle length and ends its lap, as Garmin's watches and cookbook do.
- **Length counts include idle lengths.** A lap's and a session's `num_lengths` count every
length in them, rests too, as the SDK's example and older watches do, and
`num_active_lengths` the swum ones; newer watches count none in a rest lap and leave them
out of the session's count.
- **A drill length is timed but its strokes are not counted.** It carries its distance and
speed and no stroke count, where watches write zeros; distance per stroke leaves it out.
- **A length or set is stamped with its end.** Its `timestamp` is when it ended; watches
stamp it when they wrote it, which can be minutes later.
- **Strength sets and rests don't end laps.** Garmin's watches end a lap, or a split, with each
set and rest; here laps stay the caller's. Each set gives one exercise category, where
watches list up to three guesses.
- **Sets belong to training and HIIT sessions.** Elsewhere a set, or a rest outside a pool
swim, is refused (`Error::OutOfOrder`) rather than written as a strength `set` message in a
run; every device file with sets we found is strength training. A session's repetitions
are its total cycles, which the profile reads as total reps for strength training and HIIT;
it gives a lap's total cycles no such reading, so a lap has none.
- **A pool swim needs its pool.** `session` refuses `lap_swimming` (`Error::OutOfRange`), as
without the pool's length it could take no lengths; `pool_swim` or `Leg::pool_swim` starts
one.
- **Heartbeat intervals are padded, and follow the record they came after.** Each `hrv` message
holds five intervals, as every device file we could find does, with unused ones FIT's
"none"; readers that drop "none" read the same intervals as from a shorter message, and
one definition serves the whole file. Intervals given between two records are written before
the second, so a reader adding them to the time of the record before has them right, as
Garmin describes. They are kept while the timer is paused, as watches keep them, because
their running sum is their only clock.
- **The end's bytes are kept from the start.** Every call before the end leaves room for the
largest end: the rest it closes, the beat intervals waiting, the stop event, the largest lap
and session with every developer field the file may hold, and the activity. A new session
also leaves room for the rest, lap and session it ends and its own sport, and a call that
writes several messages is refused whole unless all of them fit. Near FIT's 4 GiB limit
records are refused (`Error::TooLarge`) a few hundred bytes early rather than leaving a file
that can never be finished.
- **Developer fields are declared before they are used, and written as they are declared.**
`Writer::developer` writes the `developer_data_id` and `Writer::declare` the
`field_description` there and then, so both come before any value, as the protocol requires
and as Garmin's own decoder needs. Writing a description when it is declared, rather than at
its first value, means the encoder never holds a name.
- **A developer field's handle is checked, not branded.** A handle carries the identity of the
file that declared it, and any other file refuses it (`Error::Undeclared`): one that
declared the same fields the same way, and the second pass of `write`, which must declare
them again and use its own handles. A handle with no lifetime can live beside a `OnePass` in
a long-running recorder, which a handle borrowing its writer could not.
- **A file's identity comes from a global counter.** Each file takes the next value of a
`static` 32-bit counter, so handles are told apart without a lifetime or an allocation. Two
files share an identity only after 2^32 more have been made, and two that share one take
each other's handles of the same slot and type. On a target without atomic
compare-and-swap the counter is taken in a critical section, so the same holds there.
- **Each developer field belongs to one kind of message**, records, laps or sessions, as in
Connect IQ, and says so in its `native_mesg_num`. A field wanted on both laps and sessions
is two fields.
- **Lap and session developer values are set, not derived.** The encoder does not summarise a
record field into its lap; `Writer::developer_value` gives the open lap or session a value,
the last given is written when it ends, and a lap's value does not carry over to the next lap.
- **Developer values are written as given.** `scale` and `offset` are only descriptions:
`fitparser` applies them, while Garmin's SDKs and `rustyfit` do not, so a value scaled to
fit an integer reads differently in different tools. A float, or an integer of the unit
itself, reads the same everywhere. Where the profile has a field, such as
`core_temperature` or `power`, write that field rather than a developer field standing in
for it; `native_field` only hints, and Garmin Connect ignores it.
- **Raw messages may not touch what the encoder derives.** `Writer::raw_message` refuses
(`Error::Reserved`) `file_id`, `device_info`, `sport`, `record`, `length`, `set`, `hrv`,
`lap`, `session`, `activity`, `developer_data_id` and `field_description`, which the encoder
writes and counts, and an `event` for the timer, a session, a lap or the activity, or with
no `event` at all, since those set the timer that every summary counts. A raw record field
may not be one `Record` sets, the `timestamp`, or another form of one
(`compressed_speed_distance`, `enhanced_speed`, `enhanced_altitude`). Anything else goes,
unchecked against the profile: a raw field's meaning is the caller's.
- **A raw message's time is the activity's.** A raw `timestamp` must be a `uint32` no earlier
than the last time written, as a call's would; it moves the activity on, and compressed
timestamps count from it.
- **Fixed capacities.** A file holds up to `DEVELOPERS_MAX` developers and
`DEVELOPER_FIELDS_MAX` developer fields, whose lap and session values take up to
`SUMMARY_BYTES_MAX` bytes together; names take up to `FIELD_NAME_MAX` bytes and units
`UNITS_MAX`, the sizes Connect IQ guarantees. A message carries up to `RAW_FIELDS_MAX` raw
fields. Past them a call is refused (`Error::TooMany`); FIT allows far more, but the encoder
holds its state without allocating.
- **Each session starts with a `sport` message**, its sport and sub-sport and, from
`Leg::named`, its profile's name, as Garmin's watches since the fenix 3 write it.
A reader going through the file in order then knows a leg's sport before its records rather
than at its session, which comes at its end. It is always written; there is no option to
leave it out.
- **A multisport activity says how its legs began.** `Options::auto_multisport` sets the
activity's `type` to `auto_multi_sport` and each session that a later one ended to the
`trigger` `auto_multi_sport`, as a watch's triathlon mode writes them; without it both are
`manual`, as when the user starts each leg. The last session's trigger is the activity's
end either way. A leg the wearer moved to by hand within an automatic activity is
`Leg::by_hand`, started with `Writer::leg`, which ends the session before it `manual`, as a
Forerunner 965's swimrun does. It is said of the leg that begins, when the change is known,
rather than of the session it ends, so it cannot be left set for a later change; without
the option it changes nothing.
- **A session's last lap says the session ended it.** Its `lap_trigger` is `session_end`, as
multisport watches write each leg's last lap, and the SDK's example does for legs changed by
hand; a lap from `lap` or a rest is `manual`, and `lap_by` gives what else ended one, such
as a distance or a time. Garmin's pool swims often call their last lap `manual` too,
whatever ended them; here it follows the rule.
- **Finishing hands the file back on failure.** `OnePass::finish` returns the file inside its
error, as `BufWriter::into_inner` does, so an activity not yet ended can be ended and
finished again. Dropping an unfinished file leaves its header claiming no messages, so
readers refuse it rather than trust it.
- **Async sinks take whole stages, and a call that spills runs again to fill them.** A call on
the writer is synchronous: its bytes go to a stage of `ASYNC_WRITE_LEN` bytes, which is
awaited to the sink each time it fills, so every write but a file's last is that long. Each
call works out how many bytes it will write before it writes or changes anything; one that
fits what is left of the stage writes straight into it. One that would spill writes
nothing, and runs instead on a copy of the file's state for each stage its bytes fall in,
keeping only those, the last copy becoming the file's state. A call's bytes depend only on
that state, so each run writes the same. The stage need not hold the largest call, and no
call is refused for its size; the cost is copying the state and running such a call a few
times. No copy is held across an await, so a call's future stays small rather than holding
the state. The alternatives each had a flaw: an async copy of the encoder doubles its logic,
a stage that must hold a whole call needs a bound that grows with every message added, and a
synchronous call cannot await a sink partway through.
- **Sinks are open; what the encoder lays out is closed.** The sink traits are for any writer
to implement, but the crate implements them only on its own types. A `Vec<u8>` is written
through `VecSink`, or `to_vec`, so importing `Sink` gives no `Vec` a `write` that clashes
with `std::io::Write`'s, or stands in for it where that is not imported. `DevType`,
`Scalar`, `Kind` and `Summary` are the crate's alone, since the encoder must know how each
is laid out; what it needs of them is on traits other crates cannot name, and none of it is
a method, so neither `use fit_encoder::*` nor a `T: Scalar` bound adds methods to the number
types. Profile values such as `Sport` go the other way: each takes any number with `new`, so
a value the profile gains later can be written now.
`LapTrigger` is the exception, closed because the encoder writes `session_end` itself.
- **Refusals can grow; who failed cannot.** `Error` and `EmbeddedIoError` are
`#[non_exhaustive]`, so a new refusal is not a breaking change. `WriteError` is the sink's
error or the source's and will stay so, and its chain names each cause once.
## FIT and Garmin
FIT, the Flexible and Interoperable Data Transfer protocol, is Garmin's. This crate is an
independent implementation, written from Garmin's public documentation:
- [FIT Protocol](https://developer.garmin.com/fit/protocol/): the file header, record headers,
definition and data messages, base types and the CRC;
- [Activity File](https://developer.garmin.com/fit/file-types/activity/) and
[Encoding FIT Activity Files](https://developer.garmin.com/fit/cookbook/encoding-activity-files/):
which messages an activity holds, in what order, and which fields each needs;
- [Working with Date Time Values](https://developer.garmin.com/fit/cookbook/datetime/): the
FIT epoch.
Those pages give the file layout but only a few message and field numbers; the protocol page
leaves the rest to the SDK's profile. The few dozen numbers this crate needs are written by hand,
as interoperability facts that every FIT decoder shares, and its tests check each one by name
against two independent open-source decoders. It contains no part of the FIT SDK: no code, no
profile spreadsheet, nothing generated from either, and no example files. It is not affiliated
with or endorsed by Garmin. Files it writes carry the manufacturer ID you give;
`Manufacturer::DEVELOPMENT` (255) is the one Garmin's documentation uses for devices without an
assigned ID. With it Strava shows no device name; another ID must be one assigned to you,
never someone else's.
## License
Licensed under either of
[Apache License 2.0](https://github.com/tobymurray/wrist-rs/blob/main/crates/fit-encoder/LICENSE-APACHE)
or [MIT](https://github.com/tobymurray/wrist-rs/blob/main/crates/fit-encoder/LICENSE-MIT), at your
option.