@garmin/fitsdk 21.115.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/stream.js ADDED
@@ -0,0 +1,259 @@
1
+ /////////////////////////////////////////////////////////////////////////////////////////////
2
+ // Copyright 2023 Garmin International, Inc.
3
+ // Licensed under the Flexible and Interoperable Data Transfer (FIT) Protocol License; you
4
+ // may not use this file except in compliance with the Flexible and Interoperable Data
5
+ // Transfer (FIT) Protocol License.
6
+ /////////////////////////////////////////////////////////////////////////////////////////////
7
+ // ****WARNING**** This file is auto-generated! Do NOT edit this file.
8
+ // Profile Version = 21.115Release
9
+ // Tag = production/release/21.115.00-0-gfe0a7f8
10
+ /////////////////////////////////////////////////////////////////////////////////////////////
11
+
12
+
13
+ import FIT from "./fit.js";
14
+ import UtilsInternal from "./utils-internal.js";
15
+
16
+ class Stream {
17
+ static LITTLE_ENDIAN = true;
18
+ static BIG_ENDIAN = false;
19
+
20
+ #position = 0;
21
+ #arrayBuffer = null;
22
+ #textDecoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
23
+ #crcCalculator = null;
24
+
25
+ /**
26
+ * Convenience method for creating a Stream from a byte array
27
+ * @param {Array<number>} data An array of bytes
28
+ * @returns {Stream} A new Stream object
29
+ * @static
30
+ */
31
+ static fromByteArray(data) {
32
+ const buf = new Uint8Array(data);
33
+ return this.fromArrayBuffer(buf.buffer);
34
+ }
35
+
36
+ /**
37
+ * Convenience method for creating a Stream from a Node Buffer
38
+ * @param {Buffer} buffer - Node Buffer of bytes
39
+ * @returns {Stream} A new Stream object
40
+ * @static
41
+ */
42
+ static fromBuffer(buffer) {
43
+ const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
44
+ return this.fromArrayBuffer(arrayBuffer);
45
+ }
46
+
47
+ /**
48
+ * Convenience method for creating a Stream from an ArrayBuffer
49
+ * @param {ArrayBuffer} arrayBuffer - An ArrayBuffer of bytes
50
+ * @returns {Stream} A new Stream object
51
+ * @static
52
+ */
53
+ static fromArrayBuffer(arrayBuffer) {
54
+ const stream = new Stream(arrayBuffer);
55
+ return stream;
56
+ }
57
+
58
+ /**
59
+ * Creates a Stream containing a FIT file
60
+ * @constructor
61
+ * @param {ArrayBuffer} stream - ArrayBuffer containing a FIT file
62
+ */
63
+ constructor(arrayBuffer) {
64
+ this.#position = 0;
65
+ this.#arrayBuffer = arrayBuffer;
66
+ }
67
+
68
+ get length() {
69
+ return this.#arrayBuffer.byteLength;
70
+ }
71
+
72
+ get bytesRead() {
73
+ return this.#position;
74
+ }
75
+
76
+ get position() {
77
+ return this.#position;
78
+ }
79
+
80
+ get crcCalculator() {
81
+ return this.#crcCalculator;
82
+ }
83
+
84
+ set crcCalculator(crcCalculator) {
85
+ this.#crcCalculator = crcCalculator;
86
+ }
87
+
88
+ reset() {
89
+ this.seek(0);
90
+ }
91
+
92
+ seek(position) {
93
+ this.#position = position;
94
+ }
95
+
96
+ slice(begin, end) {
97
+ return this.#arrayBuffer.slice(begin, end);
98
+ }
99
+
100
+ peekByte() {
101
+ const arrayBuffer = this.#arrayBuffer.slice(this.#position, this.#position + 1);
102
+ const dataView = new DataView(arrayBuffer);
103
+ return dataView.getUint8(0);
104
+ }
105
+
106
+ readByte() {
107
+ return this.readUInt8();
108
+ }
109
+
110
+ readBytes(size) {
111
+ if (this.#position + size > this.#arrayBuffer.byteLength) {
112
+ throw Error(`FIT Runtime Error end of stream at byte ${this.#position}`);
113
+ }
114
+
115
+ const bytes = this.#arrayBuffer.slice(this.#position, this.#position + size);
116
+ this.#position += size;
117
+
118
+ this.#crcCalculator?.addBytes(new Uint8Array(bytes), 0, size);
119
+
120
+ return bytes;
121
+ }
122
+
123
+ readUInt8() {
124
+ return this.readValue(FIT.BaseType.UINT8, 1);
125
+ }
126
+
127
+ readInt8() {
128
+ return this.readValue(FIT.BaseType.SINT8, 1);
129
+ }
130
+
131
+ readUInt16(opts) {
132
+ return this.readValue(FIT.BaseType.UINT16, 2, { convertInvalidToNull: false, ...opts });
133
+ }
134
+
135
+ readInt16(opts) {
136
+ return this.readValue(FIT.BaseType.SINT16, 2, { convertInvalidToNull: false, ...opts });
137
+ }
138
+
139
+ readUInt32(opts) {
140
+ return this.readValue(FIT.BaseType.UINT32, 4, { convertInvalidToNull: false, ...opts });
141
+ }
142
+
143
+ readInt32(opts) {
144
+ return this.readValue(FIT.BaseType.SINT32, 4, { convertInvalidToNull: false, ...opts });
145
+ }
146
+
147
+ readUInt64(opts) {
148
+ return this.readValue(FIT.BaseType.UINT64, 8, { convertInvalidToNull: false, ...opts });
149
+ }
150
+
151
+ readInt64(opts) {
152
+ return this.readValue(FIT.BaseType.SINT64, 8, { convertInvalidToNull: false, ...opts });
153
+ }
154
+
155
+ readFloat32(opts) {
156
+ return this.readValue(FIT.BaseType.FLOAT32, 4, { convertInvalidToNull: false, ...opts });
157
+ }
158
+
159
+ readFloat64(opts) {
160
+ return this.readValue(FIT.BaseType.FLOAT64, 8, { convertInvalidToNull: false, ...opts });
161
+ }
162
+
163
+ readString(strlen) {
164
+ return this.readValue(FIT.BaseType.STRING, strlen);
165
+ }
166
+
167
+ readValue(baseType, size, { endianness = Stream.LITTLE_ENDIAN, convertInvalidToNull = true } = {}) {
168
+ const baseTypeSize = FIT.BaseTypeDefinitions[baseType].size;
169
+ const baseTypeInvalid = FIT.BaseTypeDefinitions[baseType].invalid;
170
+
171
+ const arrayBuffer = this.readBytes(size);
172
+
173
+ if (size % baseTypeSize !== 0) {
174
+ return convertInvalidToNull ? null : baseTypeInvalid;
175
+ }
176
+
177
+ if (baseType === FIT.BaseType.STRING) {
178
+ const string = this.#textDecoder.decode(arrayBuffer).replace(/\uFFFD/g, "");
179
+ const strings = string.split('\0');
180
+
181
+ while (strings[strings.length - 1] === "") {
182
+ strings.pop();
183
+ }
184
+
185
+ if (strings.length === 0) {
186
+ return null;
187
+ }
188
+
189
+ return strings.length === 1 ? strings[0] : strings;
190
+ }
191
+
192
+ const dataView = new DataView(arrayBuffer);
193
+ let values = [];
194
+
195
+ const count = size / baseTypeSize;
196
+
197
+ for (let i = 0; i < count; i++) {
198
+
199
+ switch (baseType) {
200
+ case FIT.BaseType.BYTE:
201
+ case FIT.BaseType.ENUM:
202
+ case FIT.BaseType.UINT8:
203
+ case FIT.BaseType.UINT8Z:
204
+ values.push(dataView.getUint8(i * baseTypeSize));
205
+ break;
206
+
207
+ case FIT.BaseType.SINT8:
208
+ values.push(dataView.getInt8(i * baseTypeSize));
209
+ break;
210
+
211
+ case FIT.BaseType.UINT16:
212
+ case FIT.BaseType.UINT16Z:
213
+ values.push(dataView.getUint16(i * baseTypeSize, endianness));
214
+ break;
215
+
216
+ case FIT.BaseType.SINT16:
217
+ values.push(dataView.getInt16(i * baseTypeSize, endianness));
218
+ break;
219
+
220
+ case FIT.BaseType.UINT32:
221
+ case FIT.BaseType.UINT32Z:
222
+ values.push(dataView.getUint32(i * baseTypeSize, endianness));
223
+ break;
224
+
225
+ case FIT.BaseType.SINT32:
226
+ values.push(dataView.getInt32(i * baseTypeSize, endianness));
227
+ break;
228
+
229
+ case FIT.BaseType.UINT64:
230
+ case FIT.BaseType.UINT64Z:
231
+ values.push(dataView.getBigUint64(i * baseTypeSize, endianness));
232
+ break;
233
+ case FIT.BaseType.SINT64:
234
+ values.push(dataView.getBigInt64(i * baseTypeSize, endianness));
235
+ break;
236
+
237
+ case FIT.BaseType.FLOAT32:
238
+ values.push(dataView.getFloat32(i * baseTypeSize, endianness));
239
+ break;
240
+
241
+ case FIT.BaseType.FLOAT64:
242
+ values.push(dataView.getFloat64(i * baseTypeSize, endianness));
243
+ break;
244
+ }
245
+ }
246
+
247
+ if (baseType === FIT.BaseType.BYTE) {
248
+ return UtilsInternal.onlyInvalidValues(values, baseTypeInvalid) ? null : values;
249
+ }
250
+
251
+ if (convertInvalidToNull) {
252
+ values = values.map(value => value === baseTypeInvalid ? null : value);
253
+ }
254
+
255
+ return UtilsInternal.sanitizeValues(values);
256
+ }
257
+ }
258
+
259
+ export default Stream;
@@ -0,0 +1,175 @@
1
+ /////////////////////////////////////////////////////////////////////////////////////////////
2
+ // Copyright 2023 Garmin International, Inc.
3
+ // Licensed under the Flexible and Interoperable Data Transfer (FIT) Protocol License; you
4
+ // may not use this file except in compliance with the Flexible and Interoperable Data
5
+ // Transfer (FIT) Protocol License.
6
+ /////////////////////////////////////////////////////////////////////////////////////////////
7
+ // ****WARNING**** This file is auto-generated! Do NOT edit this file.
8
+ // Profile Version = 21.115Release
9
+ // Tag = production/release/21.115.00-0-gfe0a7f8
10
+ /////////////////////////////////////////////////////////////////////////////////////////////
11
+
12
+
13
+ import Utils from "./utils.js";
14
+
15
+ const mergeHeartRates = (hrMesgs, recordMesgs) => {
16
+
17
+ if (hrMesgs == null || recordMesgs == null ||
18
+ hrMesgs.length == 0 || recordMesgs.length == 0) {
19
+ return;
20
+ }
21
+
22
+ const heartrates = expandHeartRates(hrMesgs);
23
+
24
+ let heartrateIndex = 0;
25
+ let recordRangeStartTime = null;
26
+
27
+ for (let i = 0; i < recordMesgs.length; ++i) {
28
+ const recordMesg = recordMesgs[i];
29
+
30
+ let hrSum = 0;
31
+ let hrSumCount = 0;
32
+
33
+ const recordRangeEndTime = secondsSinceFitEpoch(recordMesg.timestamp);
34
+
35
+ if (recordRangeStartTime == null) {
36
+ recordRangeStartTime = recordRangeEndTime;
37
+ }
38
+
39
+ if (recordRangeStartTime === recordRangeEndTime) {
40
+ recordRangeStartTime--;
41
+ heartrateIndex = (heartrateIndex >= 1) ? heartrateIndex - 1 : 0;
42
+ }
43
+
44
+ let findingInRangeHrMesgs = true;
45
+ while (findingInRangeHrMesgs && (heartrateIndex < heartrates.length)) {
46
+
47
+ const heartrate = heartrates[heartrateIndex];
48
+
49
+ // Check if the heartrate timestamp is gt record start time
50
+ // and if the heartrate timestamp is lte to record end time
51
+ if (heartrate.timestamp > recordRangeStartTime
52
+ && heartrate.timestamp <= recordRangeEndTime) {
53
+ hrSum += heartrate.heartRate;
54
+ hrSumCount++;
55
+ }
56
+ // Check if the heartrate timestamp exceeds the record time
57
+ else if (heartrate.timestamp > recordRangeEndTime) {
58
+ findingInRangeHrMesgs = false;
59
+
60
+ if (hrSumCount > 0) {
61
+ // Update record's heart rate value
62
+ const avgHR = Math.round(hrSum / hrSumCount);
63
+ recordMesg.heartRate = avgHR;
64
+
65
+ }
66
+ // Reset HR average accumulators
67
+ hrSum = 0;
68
+ hrSumCount = 0;
69
+
70
+ recordRangeStartTime = recordRangeEndTime;
71
+
72
+ // Breaks out of findingInRangeHrMesgs while loop w/o incrementing heartrateIndex
73
+ break;
74
+ }
75
+
76
+ heartrateIndex++;
77
+ }
78
+ }
79
+ }
80
+
81
+ const expandHeartRates = (hrMesgs) => {
82
+ const GAP_INCREMENT_MILLISECONDS = 250;
83
+ const GAP_INCREMENT_SECONDS = GAP_INCREMENT_MILLISECONDS / 1000.0;
84
+ const GAP_MAX_MILLISECONDS = 5000;
85
+ const GAP_MAX_STEPS = GAP_MAX_MILLISECONDS / GAP_INCREMENT_MILLISECONDS;
86
+
87
+ if (hrMesgs == null || hrMesgs.length == 0) {
88
+ return [];
89
+ }
90
+
91
+ let anchorEventTimestamp = 0.0;
92
+ let anchorTimestamp = null;
93
+
94
+ const heartrates = [];
95
+ hrMesgs.forEach(hrMesg => {
96
+ if (hrMesg == null) {
97
+ throwError("HR mesg must not be null");
98
+ }
99
+
100
+ const eventTimestamps = Array.isArray(hrMesg.eventTimestamp) ? hrMesg.eventTimestamp : [hrMesg.eventTimestamp];
101
+ const filteredBpms = Array.isArray(hrMesg.filteredBpm) ? hrMesg.filteredBpm : [hrMesg.filteredBpm];
102
+
103
+ // Update HR timestamp anchor, if present
104
+ if (hrMesg.timestamp != null) {
105
+ anchorTimestamp = secondsSinceFitEpoch(hrMesg.timestamp);
106
+
107
+ if (hrMesg.fractionalTimestamp != null) {
108
+ anchorTimestamp += hrMesg.fractionalTimestamp;
109
+ }
110
+
111
+ if (eventTimestamps.length == 1) {
112
+ anchorEventTimestamp = eventTimestamps[0];
113
+ } else {
114
+ throwError("anchor HR mesg must have 1 event_timestamp");
115
+ }
116
+ }
117
+
118
+ if (anchorTimestamp == null || anchorEventTimestamp == null) {
119
+ // We cannot process any HR messages if we have not received a timestamp anchor
120
+ throwError("no anchor timestamp received in a HR mesg before delta HR mesgs");
121
+ } else if (eventTimestamps.length != filteredBpms.length) {
122
+ throwError("HR mesg with mismatching event timestamp and filtered bpm");
123
+ }
124
+
125
+ for (let i = 0; i < eventTimestamps.length; i++) {
126
+ let eventTimestamp = eventTimestamps[i];
127
+
128
+ // Check to see if the event timestamp rolled over
129
+ if (eventTimestamp < anchorEventTimestamp) {
130
+ if ((anchorEventTimestamp - eventTimestamp) > (0x400000)) {
131
+ eventTimestamp += (0x400000);
132
+ } else {
133
+ throwError("anchor event_timestamp is greater than subsequent event_timestamp. This does not allow for correct delta calculation.");
134
+ }
135
+ }
136
+
137
+ const currentHr = { timestamp: anchorTimestamp, heartRate: filteredBpms[i] };
138
+ currentHr.timestamp += (eventTimestamp - anchorEventTimestamp);
139
+
140
+ // Carry the previous HR value forward across the gap to the current
141
+ // HR value for up to 5 Seconds (5000ms) in 250ms increments
142
+ if (heartrates.length > 0) {
143
+ const previousHR = heartrates[heartrates.length - 1];
144
+ let gapInMilliseconds = Math.abs(currentHr.timestamp - previousHR.timestamp) * 1000;
145
+ let step = 1;
146
+ while (gapInMilliseconds > GAP_INCREMENT_MILLISECONDS && step <= GAP_MAX_STEPS) {
147
+ const gapHR = { timestamp: previousHR.timestamp, heartRate: previousHR.heartRate };
148
+ gapHR.timestamp += (GAP_INCREMENT_SECONDS * step);
149
+ heartrates.push(gapHR);
150
+
151
+ gapInMilliseconds -= GAP_INCREMENT_MILLISECONDS;
152
+ step++;
153
+ }
154
+ }
155
+
156
+ heartrates.push(currentHr);
157
+ }
158
+ });
159
+
160
+ return heartrates;
161
+ }
162
+
163
+ const secondsSinceFitEpoch = (timestamp) => {
164
+ if (timestamp instanceof Date) {
165
+ return (timestamp.getTime() - Utils.FIT_EPOCH_MS) / 1000;
166
+ }
167
+
168
+ return timestamp;
169
+ }
170
+
171
+ const throwError = (error = "") => {
172
+ throw Error(`FIT Runtime Error ${error}`.trimEnd());
173
+ }
174
+
175
+ export default { mergeHeartRates, expandHeartRates };
@@ -0,0 +1,35 @@
1
+ /////////////////////////////////////////////////////////////////////////////////////////////
2
+ // Copyright 2023 Garmin International, Inc.
3
+ // Licensed under the Flexible and Interoperable Data Transfer (FIT) Protocol License; you
4
+ // may not use this file except in compliance with the Flexible and Interoperable Data
5
+ // Transfer (FIT) Protocol License.
6
+ /////////////////////////////////////////////////////////////////////////////////////////////
7
+ // ****WARNING**** This file is auto-generated! Do NOT edit this file.
8
+ // Profile Version = 21.115Release
9
+ // Tag = production/release/21.115.00-0-gfe0a7f8
10
+ /////////////////////////////////////////////////////////////////////////////////////////////
11
+
12
+
13
+ const sanitizeValues = (values) => {
14
+ if (onlyNullValues(values)) {
15
+ return null;
16
+ }
17
+
18
+ return values.length === 1 ? values[0] : values;
19
+ }
20
+
21
+ const onlyNullValues = (values) => values.reduce((state, value) => value != null ? false : state, true);
22
+
23
+ const onlyInvalidValues = (rawFieldValue, invalidValue) => {
24
+ if (Array.isArray(rawFieldValue)) {
25
+ return rawFieldValue.reduce((state, value) => value != invalidValue ? false : state, true);
26
+ }
27
+
28
+ return rawFieldValue === invalidValue;
29
+ }
30
+
31
+ export default {
32
+ sanitizeValues,
33
+ onlyNullValues,
34
+ onlyInvalidValues
35
+ };
package/src/utils.js ADDED
@@ -0,0 +1,31 @@
1
+ /////////////////////////////////////////////////////////////////////////////////////////////
2
+ // Copyright 2023 Garmin International, Inc.
3
+ // Licensed under the Flexible and Interoperable Data Transfer (FIT) Protocol License; you
4
+ // may not use this file except in compliance with the Flexible and Interoperable Data
5
+ // Transfer (FIT) Protocol License.
6
+ /////////////////////////////////////////////////////////////////////////////////////////////
7
+ // ****WARNING**** This file is auto-generated! Do NOT edit this file.
8
+ // Profile Version = 21.115Release
9
+ // Tag = production/release/21.115.00-0-gfe0a7f8
10
+ /////////////////////////////////////////////////////////////////////////////////////////////
11
+
12
+
13
+ /**
14
+ * The millisecond offset between UNIX and FIT Epochs (631065600000).
15
+ * @const {number}
16
+ */
17
+ const FIT_EPOCH_MS = 631065600000;
18
+
19
+ /**
20
+ * Convert a FIT DateTime to a JavaScript Date
21
+ * @param {number} datetime - Seconds since FIT EPOCH
22
+ * @returns {Date} A JavaScript Date object
23
+ */
24
+ const convertDateTimeToDate = (datetime) => {
25
+ return new Date((datetime ?? 0) * 1000 + FIT_EPOCH_MS);
26
+ };
27
+
28
+ export default {
29
+ FIT_EPOCH_MS,
30
+ convertDateTimeToDate,
31
+ };