1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! A stateless and static-friendly [`#![no_std]`](https://docs.rust-embedded.org/book/intro/no-std.html)
//! library to decode and encode Garmin FIT files, supporting FIT Protocol V2.
//!
//! [The Flexible and Interoperable Data Transfer (FIT) Protocol](https://developer.garmin.com/fit)
//! is a protocol developed by Garmin for storing and sharing data originating from sports, fitness,
//! and health devices. Activities recorded using devices such as smartwatch and cycling computer
//! are now mostly in a FIT file format (\*.fit).
//!
//! This library is a rewrite of [FIT SDK for Go](https://github.com/muktihari/fit) and is designed to run on
//! baremetal Rust, where performance and memory efficiency is carefully considered.
//!
//! ## Usage
//!
//! For [`#![no_std]`](https://docs.rust-embedded.org/book/intro/no-std.html), you need to provide
//! [`#[global_allocator]`](https://doc.rust-lang.org/std/alloc/index.html#the-global_allocator-attribute)
//! since this library requires allocation.
//!
//! For [`std`](https://doc.rust-lang.org/std), you need to wrap `std::io`'s
//! [Read](https://doc.rust-lang.org/std/io/trait.Read.html) or
//! [Write](https://doc.rust-lang.org/std/io/trait.Write.html) with
//! [embedded_io_adapters::std:FromStd](https://docs.rs/embedded-io-adapters/0.7.0/embedded_io_adapters/std/struct.FromStd.html).
//!
//! We will provide examples in `std` for simplicity and a wider audience, since `#![no_std]` is platform-dependent.
//!
//! - [Decoding](#decoding)
//! - [Streaming Decoding](#streaming-decoding)
//! - [DecoderBuilder](#decoderbuilder)
//! - [Encoding](#encoding)
//! - [Encode using mesgdef module](#encode-using-mesgdef-module)
//! - [Streaming Encoding](#streaming-encoding)
//! - [EncoderBuilder](#encoderbuilder)
//!
//! ####
//!
//! ### Decoding
//!
//! `Decoder`'s `decode` method allows us to interact with FIT files directly through their original protocol messages' structure.
//! This method can be invoked multiple times to decode chained FIT file until it return Ok(None) or Err(err).
//!
//! ```
//! use embedded_io_adapters::std::FromStd;
//! use rustyfit::{Decoder, profile::{mesgdef, typedef}, proto::Value};
//! use std::{error::Error, fs::File, io::BufReader};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let name = "tests/data/from_official_sdk/Activity.fit";
//! let f = File::open(name)?;
//! let br = BufReader::new(f);
//! let mut reader = FromStd::new(br);
//!
//! let mut dec = Decoder::new();
//!
//! let fit = match dec.decode(&mut reader)? {
//! Some(fit) => fit,
//! None => {
//! // First decode call to reader should be `Ok` or `Err`.
//! // Except, reader is already empty to begin with.
//! return Err(Box::from("empty reader"));
//! }
//! };
//!
//! println!("file_header's data_size: {}", fit.file_header.data_size);
//! println!("messages count: {}", fit.messages.len());
//! for field in &fit.messages[0].fields {
//! // first message: file_id
//! if field.num == mesgdef::FileId::TYPE
//! && let Value::Uint8(v) = field.value
//! {
//! println!("file type: {}", typedef::File(v));
//! }
//! }
//!
//! Ok(())
//!
//! // # Output:
//! // file_header's data_size: 94080
//! // messages count: 3611
//! // file type: activity
//! }
//!
//! ```
//!
//! #### Streaming Decoding
//!
//! `StreamDecoder` allows us to retrieve event data (`FileHeader`, `MessageDefinition`, `Message`, `CRC`) as soon as it is being decoded.
//! This way, users can have fine-grained control on how to interact with the data efficiently. And since this is lazily evaluated, users can
//! decide when to stop without required to read the whole reader.
//!
//! ```
//! use embedded_io_adapters::std::FromStd;
//! use rustyfit::{Decoder, DecoderEvent, StreamingIterator, profile::{mesgdef, typedef}};
//! use std::{error::Error, fs::File, io::BufReader};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let name = "tests/data/from_official_sdk/Activity.fit";
//! let f = File::open(name)?;
//! let br = BufReader::new(f);
//! let mut reader = FromStd::new(br);
//!
//! let mut dec = Decoder::new(); // stateless and static-friendly
//! let mut stream = dec.stream(&mut reader); // stateful but small since it borrows Decoder.
//!
//! while let Some(event) = stream.next() {
//! match event? {
//! DecoderEvent::FileHeader(_) => {},
//! DecoderEvent::MessageDefinition(_) => {},
//! DecoderEvent::Message(mesg) => {
//! if mesg.num == typedef::MesgNum::SESSION {
//! // Convert mesg into Session struct
//! let ses = mesgdef::Session::from(mesg);
//! println!(
//! "session:\n start_time: {}\n sport: {}\n num_laps: {}",
//! ses.start_time.0, ses.sport, ses.num_laps
//! );
//! }
//! }
//! DecoderEvent::Crc(_) => {}
//! }
//! }
//!
//! Ok(())
//!
//! // # Output
//! // session:
//! // start_time: 995749880
//! // sport: stand_up_paddleboarding
//! // num_laps: 1
//! }
//! ```
//!
//! Users can also use `discard()` to discard this current FIT sequence and direct the `StreamDecoder`
//! to point to next FIT sequence in the reader. If desired, users can also stop the process entirely.
//!
//! ```
//! # use std::{error::Error, fs::File, io::BufReader};
//! # use embedded_io_adapters::std::FromStd;
//! # use rustyfit::{Decoder, DecoderEvent, StreamingIterator, profile::{mesgdef, typedef}};
//! # fn main() -> Result<(), Box<dyn Error>> {
//! # let name = "tests/data/from_official_sdk/Activity.fit";
//! # let f = File::open(name)?;
//! # let br = BufReader::new(f);
//! # let mut reader = FromStd::new(br);
//! # let mut dec = Decoder::new();
//! # let mut stream = dec.stream(&mut reader);
//! while let Some(event) = stream.next() {
//! if let DecoderEvent::Message(mesg) = event? {
//! if mesg.num == typedef::MesgNum::FILE_ID {
//! // Let's say we just want to decode Activity file,
//! let file_id = mesgdef::FileId::from(mesg);
//! if file_id.r#type != typedef::File::ACTIVITY {
//! stream.discard()?; // discard this sequence
//! continue;
//! }
//! }
//! // It's an Activity File!
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! #### DecoderBuilder
//!
//! Create `Decoder` instance with options using `Decoder::builder()` or `DecoderBuilder::new()`.
//!
//! ```
//! # use rustyfit::Decoder;
//! let mut dec = Decoder::builder()
//! .checksum(false)
//! .expand_components(false)
//! .build();
//! ```
//!
//! These associated functions and method are `const fn`, so we can use it to declare a static variable
//! as long as we wrap it with a lock, e.g. `Mutex`. This is useful on microcrontrollers where RAM is only hundred KBs.
//!
//! ####
//!
//! ### Encoding
//!
//! Here is the example of manually encode FIT protocol using this library to give the idea how it works.
//!
//! ```
//! use embedded_io_adapters::std::FromStd;
//! use rustyfit::{Encoder, profile::{ProfileType, mesgdef, typedef}, proto::{FIT, Field, Message, Value}};
//! use std::{error::Error, fs::File, io::{BufWriter, Write}};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let mut fit = FIT {
//! messages: vec![
//! Message {
//! num: typedef::MesgNum::FILE_ID,
//! fields: vec![
//! Field {
//! num: mesgdef::FileId::MANUFACTURER,
//! profile_type: ProfileType::MANUFACTURER, // or ProfileType::UINT16 is also valid
//! value: Value::Uint16(typedef::Manufacturer::GARMIN.0),
//! is_expanded: false,
//! },
//! Field {
//! num: mesgdef::FileId::PRODUCT,
//! profile_type: ProfileType::UINT16,
//! value: Value::Uint16(typedef::GarminProduct::FENIX8_SOLAR.0),
//! is_expanded: false,
//! },
//! Field {
//! num: mesgdef::FileId::TYPE,
//! profile_type: ProfileType::UINT8,
//! value: Value::Uint8(typedef::File::ACTIVITY.0),
//! is_expanded: false,
//! },
//! ],
//! ..Default::default()
//! },
//! Message {
//! num: typedef::MesgNum::RECORD,
//! fields: vec![
//! Field {
//! num: mesgdef::Record::DISTANCE,
//! profile_type: ProfileType::UINT32,
//! value: Value::Uint32(100 * 100), // 100 m
//! is_expanded: false,
//! },
//! Field {
//! num: mesgdef::Record::HEART_RATE,
//! profile_type: ProfileType::UINT8,
//! value: Value::Uint8(70), // 70 bpm
//! is_expanded: false,
//! },
//! Field {
//! num: mesgdef::Record::SPEED,
//! profile_type: ProfileType::UINT16,
//! value: Value::Uint16(2 * 1000), // 2 m/s
//! is_expanded: false,
//! },
//! ],
//! ..Default::default()
//! },
//! ],
//! ..Default::default()
//! };
//!
//! let fout_name = "output.fit";
//! let fout = File::create(fout_name)?;
//! let mut bw = BufWriter::new(fout);
//! let mut writer = FromStd::new(&mut bw);
//!
//! let mut enc = Encoder::new();
//! enc.encode(&mut writer, &mut fit)?;
//! bw.flush()?;
//! # let _ = std::fs::remove_file(fout_name);
//!
//! Ok(())
//! }
//! ```
//!
//! #### Encode using mesgdef module
//!
//! Alternatively, users can create messages using the mesgdef module for convenience.
//!
//! ```
//! use embedded_io_adapters::std::FromStd;
//! use rustyfit::{Encoder, profile::{mesgdef, typedef}, proto::{FIT, Message}};
//! use std::{error::Error, fs::File, io::{BufWriter, Write}};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let mut fit = FIT {
//! messages: vec![
//! {
//! let mut file_id = mesgdef::FileId::new();
//! file_id.manufacturer = typedef::Manufacturer::GARMIN;
//! file_id.product = typedef::GarminProduct::FENIX8_SOLAR.0;
//! file_id.r#type = typedef::File::ACTIVITY;
//! Message::from(file_id)
//! },
//! {
//! let mut record = mesgdef::Record::new();
//! record.distance = 100 * 100; // 100 m
//! record.heart_rate = 70; // 70 bpm
//! record.speed = 2 * 1000; // 2 m/s
//! Message::from(record)
//! },
//! ],
//! ..Default::default()
//! };
//!
//! let fout_name = "output.fit";
//! let fout = File::create(fout_name)?;
//! let mut bw = BufWriter::new(fout);
//! let mut writer = FromStd::new(&mut bw);
//!
//! let mut enc = Encoder::new();
//! enc.encode(&mut writer, &mut fit)?;
//! bw.flush()?;
//! # let _ = std::fs::remove_file(fout_name);
//!
//! Ok(())
//! }
//! ```
//!
//! #### Streaming Encoding
//!
//! `StreamEncoder` allows us to encode in streaming fashion. Write each message directly without retain them first in the memory.
//! This is useful when the device is the one who produce the data such as smartwatch, cycling computer or other health devices.
//!
//!
//! ```
//! use embedded_io_adapters::std::FromStd;
//! use rustyfit::{Encoder, profile::{mesgdef, typedef}, proto::Message};
//! use std::{error::Error, fs::File, io::{BufWriter, Write}};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let fout_name = "output.fit";
//! let fout = File::create(fout_name)?;
//! let mut bw = BufWriter::new(fout);
//! let mut writer = FromStd::new(&mut bw);
//!
//! let mut enc = Encoder::new(); // stateless and static-friendly
//! let mut stream = enc.stream(&mut writer); // stateful but small since it borrows Encoder.
//!
//! stream.write_message(&mut {
//! let mut file_id = mesgdef::FileId::new();
//! file_id.manufacturer = typedef::Manufacturer::GARMIN;
//! file_id.product = typedef::GarminProduct::FENIX8_SOLAR.0;
//! file_id.r#type = typedef::File::ACTIVITY;
//! Message::from(file_id)
//! })?;
//!
//! stream.write_message(&mut {
//! let mut record = mesgdef::Record::new();
//! record.distance = 100 * 100; // 100 m
//! record.heart_rate = 70; // 70 bpm
//! record.speed = 2 * 1000; // 2 m/s
//! Message::from(record)
//! })?;
//!
//! stream.finish()?;
//! bw.flush()?;
//! # let _ = std::fs::remove_file(fout_name);
//!
//! Ok(())
//! }
//!
//! ```
//!
//! NOTE:
//! - For `#![no_std]` on MCU with only few hundred KBs of RAM, we recommend allocating a Message once
//! and reuse it instead of using these `mesgdef` building blocks which might yield few KBs stack memory.
//! MCU may only has 2KB or less stack memory configuration.
//!
//! - For `std`, you don't need to worry about this, on Linux for example, stack can have a range from 2MB to 8MB,
//! which is abundant.
//!
//! #### EncoderBuilder
//!
//! Create `Encoder` instance with options using `Encoder::builder()` or `EncoderBuilder::new()`.
//!
//! ```
//! # use rustyfit::{Encoder, HeaderOption, Endianness};
//! # use rustyfit::proto::ProtocolVersion;
//! let mut enc = Encoder::builder()
//! .endianness(Endianness::BigEndian)
//! .protocol_version(ProtocolVersion::V2)
//! .header_option(HeaderOption::Compressed(3))
//! .build();
//! ```
//!
//! These associated functions and method are `const fn`, so we can use it to declare a static variable
//! as long as we wrap it with a lock, e.g. `Mutex`. This is useful on microcrontrollers where RAM is only hundred KBs.
extern crate alloc;
pub use ;
pub use ;
/// The `profile` module represents FIT Global Profile containing types and messages generated from Profile.xlsx.
/// The `proto` module provides FIT Protocol low level representation.
/// Semicircles/Degrees converter.