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.
use *;
// A swim, a transition and a run, from a stored log of heart rates at 1 Hz per leg.
let start = from_unix.unwrap;
let legs: = ;
let mut buf = ;
let file = write.unwrap;
assert_eq!;
A pool swim is its lengths, and a strength session its sets; a rest is bracketed by two calls.
use *;
let start = from_unix.unwrap;
let at = ;
let mut buf = ;
let mut file = new.unwrap;
let mut w = file.writer;
w.start.unwrap;
w.pool_swim.unwrap;
w.length.unwrap;
w.length.unwrap;
w.rest.unwrap; // the lap of two lengths, 50 m, ends here
w.end_rest.unwrap; // the rest, an idle length in a lap of its own
w.length.unwrap;
w.session.unwrap;
w.beat_intervals_ms.unwrap; // from a chest strap, as they arrive
let squat = new;
w.set.unwrap;
w.rest.unwrap;
w.end_rest.unwrap;
w.set.unwrap;
w.end.unwrap;
assert_eq!;
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.
use *;
let start = from_unix.unwrap;
let mut buf = ;
let mut file = new.unwrap;
let mut w = file.writer;
w.start.unwrap;
w.session.unwrap;
for in .zip
w.end.unwrap;
let sink = file.finish.unwrap;
assert_eq!;
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.
use *;
const APP: = *b"my-app-uuid-0001";
let start = from_unix.unwrap;
let at = ;
let mut buf = ;
let file = write
.unwrap;
assert_eq!;
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
RawFields 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.
use *;
async
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, 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,sessionandactivity;developer_data_idandfield_descriptionfor 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
hrvmessages. - 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,fitparseandmuktihari/fitread 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 and
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_unixandfrom_system_timerefuse times beforeTimestamp::FIRST_DATE, which FIT readers take as seconds since the device started;Timestamp::from_fitwrites 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:
restends the lap of lengths before it, andend_restwrites 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_lengthscount every length in them, rests too, as the SDK's example and older watches do, andnum_active_lengthsthe 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
timestampis 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 strengthsetmessage 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.
sessionrefuseslap_swimming(Error::OutOfRange), as without the pool's length it could take no lengths;pool_swimorLeg::pool_swimstarts one. - A leg says whether it can start.
Leg::checkrefuses whatWriter::legwould refuse in any activity:lap_swimmingwithout a pool, a pool of no length or too long, a sport or sub-sport of 255, FIT's "none", and a name too long or holding a NUL;legandsessionrefuse through it. A recorder that keeps an activity to write later can refuse a sport when it is chosen, from the same rule rather than a copy of it. The rule is the leg's, not a sport's or sub-sport's, since a pool and a name can be refused too. - FIT's limits are refused, not wrapped, and are public. A lap, session, length or set
numbered past FIT's 12-bit
message_index, or a sensor past itsdevice_index, is refused (Error::IndexFull), and so is a lap, session, length or set lasting longer than FIT's milliseconds hold, or an activity's timer running longer, or a distance past its centimetres (Error::OutOfRange), rather than written with a number that repeats or a value that reads as none.LAPS_MAX,SESSIONS_MAX,LENGTHS_MAX,SETS_MAX,SENSORS_MAX,DURATION_SECONDS_MAXandDISTANCE_METERS_MAXare the limits the encoder checks, so a recorder can refuse at the time what could never be written. - Heartbeat intervals are padded, and follow the record they came after. Each
hrvmessage 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::developerwrites thedeveloper_data_idandWriter::declarethefield_descriptionthere 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 ofwrite, which must declare them again and use its own handles. A handle with no lifetime can live beside aOnePassin 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
static32-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_valuegives 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.
scaleandoffsetare only descriptions:fitparserapplies them, while Garmin's SDKs andrustyfitdo 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 ascore_temperatureorpower, write that field rather than a developer field standing in for it;native_fieldonly hints, and Garmin Connect ignores it. - Raw messages may not touch what the encoder derives.
Writer::raw_messagerefuses (Error::Reserved)file_id,device_info,sport,record,length,set,hrv,lap,session,activity,developer_data_idandfield_description, which the encoder writes and counts, and aneventfor the timer, a session, a lap or the activity, or with noeventat all, since those set the timer that every summary counts. A raw record field may not be oneRecordsets, thetimestamp, 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
timestampmust be auint32no 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_MAXdevelopers andDEVELOPER_FIELDS_MAXdeveloper fields, whose lap and session values take up toSUMMARY_BYTES_MAXbytes together; names take up toFIELD_NAME_MAXbytes and unitsUNITS_MAX, the sizes Connect IQ guarantees. A message carries up toRAW_FIELDS_MAXraw 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
sportmessage, its sport and sub-sport and, fromLeg::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_multisportsets the activity'stypetoauto_multi_sportand each session that a later one ended to thetriggerauto_multi_sport, as a watch's triathlon mode writes them; without it both aremanual, 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 isLeg::by_hand, started withWriter::leg, which ends the session before itmanual, 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_triggerissession_end, as multisport watches write each leg's last lap, and the SDK's example does for legs changed by hand; a lap fromlapor a rest ismanual, andlap_bygives what else ended one, such as a distance or a time. Garmin's pool swims often call their last lapmanualtoo, whatever ended them; here it follows the rule. - Finishing hands the file back on failure.
OnePass::finishreturns the file inside its error, asBufWriter::into_innerdoes, 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_LENbytes, 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 throughVecSink, orto_vec, so importingSinkgives noVecawritethat clashes withstd::io::Write's, or stands in for it where that is not imported.DevType,Scalar,KindandSummaryare 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 neitheruse fit_encoder::*nor aT: Scalarbound adds methods to the number types. Profile values such asSportgo the other way: each takes any number withnew, so a value the profile gains later can be written now.LapTriggeris the exception, closed because the encoder writessession_enditself. - Refusals can grow; who failed cannot.
ErrorandEmbeddedIoErrorare#[non_exhaustive], so a new refusal is not a breaking change.WriteErroris 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: the file header, record headers, definition and data messages, base types and the CRC;
- Activity File and Encoding FIT Activity Files: which messages an activity holds, in what order, and which fields each needs;
- Working with Date Time Values: 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 or MIT, at your option.