forked from GPSBabel/gpsbabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
garmin_fit.cc
1314 lines (1212 loc) · 43.2 KB
/
garmin_fit.cc
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Support for FIT track files.
Copyright (C) 2011 Paul Brook, [email protected]
Copyright (C) 2003-2011 Robert Lipe, [email protected]
Copyright (C) 2019 Martin Buck, [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <cstdint> // for uint8_t, uint16_t, uint32_t, int32_t, int8_t, uint64_t
#include <cstdio> // for EOF, SEEK_SET, snprintf
#include <deque> // for deque, _Deque_iterator, operator!=
#include <memory> // for allocator_traits<>::value_type
#include <string> // for operator+, to_string, char_traits
#include <utility> // for pair
#include <vector> // for vector
#include <QByteArray> // for QByteArray
#include <QDateTime> // for QDateTime
#include <QFileInfo> // for QFileInfo
#include <QLatin1Char> // for QLatin1Char
#include <QString> // for QString
#include <Qt> // for CaseInsensitive
#include <QtGlobal> // for uint, qint64
#include "defs.h"
#include "garmin_fit.h"
#include "gbfile.h" // for gbfputc, gbfputuint16, gbfputuint32, gbfgetc, gbfread, gbfseek, gbfclose, gbfgetuint16, gbfopen_le, gbfputint32, gbfflush, gbfgetuint32, gbfputs, gbftell, gbfwrite, gbfile, gbsize_t
#include "jeeps/gpsmath.h" // for GPS_Math_Semi_To_Deg, GPS_Math_Gtime_To_Utime, GPS_Math_Deg_To_Semi, GPS_Math_Utime_To_Gtime
#include "src/core/logging.h" // for Warning, Fatal
#define MYNAME "fit"
/*******************************************************************************
* %%% global callbacks called by gpsbabel main process %%% *
*******************************************************************************/
void
GarminFitFormat::rd_init(const QString& fname)
{
fin = gbfopen_le(fname, "rb", MYNAME);
}
void
GarminFitFormat::rd_deinit()
{
fit_data = fit_data_t();
gbfclose(fin);
}
void
GarminFitFormat::wr_init(const QString& fname)
{
fout = gbfopen_le(fname, "w+b", MYNAME);
}
void
GarminFitFormat::wr_deinit()
{
gbfclose(fout);
}
/*******************************************************************************
* fit_parse_header- parse the global FIT header
*******************************************************************************/
void
GarminFitFormat::fit_parse_header()
{
char sig[4];
int len = gbfgetc(fin);
if (len == EOF || len < 12) {
fatal(MYNAME ": Bad header\n");
}
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": header len=" << len;
}
int ver = gbfgetc(fin);
if (ver == EOF || (ver >> 4) > 2)
fatal(MYNAME ": Unsupported protocol version %d.%d\n",
ver >> 4, ver & 0xf);
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": protocol version=" << ver;
}
// profile version
ver = gbfgetuint16(fin);
// data length
fit_data.len = gbfgetuint32(fin);
// File signature
if (gbfread(sig, 4, 1, fin) != 1) {
fatal(MYNAME ": Unexpected end of file\n");
}
if (sig[0] != '.' || sig[1] != 'F' || sig[2] != 'I' || sig[3] != 'T') {
fatal(MYNAME ": .FIT signature missing\n");
}
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": profile version=" << ver;
Debug(1) << MYNAME ": fit_data.len=" << fit_data.len;
}
// Header CRC may be omitted entirely
if (len >= kReadHeaderCrcLen) {
uint16_t hdr_crc = gbfgetuint16(fin);
// Header CRC may be set to 0, or contain the CRC over previous bytes.
if (hdr_crc != 0) {
// Check the header CRC
uint16_t crc = 0;
gbfseek(fin, 0, SEEK_SET);
for (unsigned int i = 0; i < kReadHeaderCrcLen; ++i) {
int data = gbfgetc(fin);
if (data == EOF) {
fatal(MYNAME ": File %s truncated\n", fin->name);
}
crc = fit_crc16(data, crc);
}
if (crc != 0) {
Warning().nospace() << MYNAME ": Header CRC mismatch in file " << fin->name << ".";
if (!opt_recoverymode) {
fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
}
} else if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": Header CRC verified.";
}
}
}
QFileInfo fi(fin->name);
qint64 size = fi.size();
if ((len + fit_data.len + 2) != size) {
Warning().nospace() << MYNAME ": File size " << size << " is not expected given header len " << len << ", data length " << fit_data.len << " and a 2 byte file CRC.";
} else if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": File size matches expectations from information in the header.";
}
gbfseek(fin, len, SEEK_SET);
fit_data.global_utc_offset = 0;
}
uint8_t
GarminFitFormat::fit_getuint8()
{
if (fit_data.len < 1) {
throw ReaderException("record truncated: expecting char[1], but only got " + std::to_string(fit_data.len) + ".");
}
int val = gbfgetc(fin);
if (val == EOF) {
throw ReaderException("unexpected end of file with fit_data.len=" + std::to_string(fit_data.len) + ".");
}
--fit_data.len;
return static_cast<uint8_t>(val);
}
uint16_t
GarminFitFormat::fit_getuint16()
{
char buf[2];
if (fit_data.len < 2) {
throw ReaderException("record truncated: expecting char[2], but only got " + std::to_string(fit_data.len) + ".");
}
gbsize_t count = gbfread(buf, 2, 1, fin);
if (count != 1) {
throw ReaderException("unexpected end of file with fit_data.len=" + std::to_string(fit_data.len) + ".");
}
fit_data.len -= 2;
if (fit_data.endian) {
return be_read16(buf);
} else {
return le_read16(buf);
}
}
uint32_t
GarminFitFormat::fit_getuint32()
{
char buf[4];
if (fit_data.len < 4) {
throw ReaderException("record truncated: expecting char[4], but only got " + std::to_string(fit_data.len) + ".");
}
gbsize_t count = gbfread(buf, 4, 1, fin);
if (count != 1) {
throw ReaderException("unexpected end of file with fit_data.len=" + std::to_string(fit_data.len) + ".");
}
fit_data.len -= 4;
if (fit_data.endian) {
return be_read32(buf);
} else {
return le_read32(buf);
}
}
QString
GarminFitFormat::fit_getstring(int size)
{
if (fit_data.len < size) {
throw ReaderException("record truncated: expecting " + std::to_string(size) + " bytes, but only got " + std::to_string(fit_data.len) + ".");
}
QByteArray buf(size + 1, 0); // almost certainly an extra byte, QByteArray should guarnatee a terminator.
gbsize_t count = gbfread(buf.data(), size, 1, fin);
if (count != 1) {
throw ReaderException("unexpected end of file with fit_data.len=" + std::to_string(fit_data.len) + ".");
}
fit_data.len -= size;
return QString(buf.constData());
}
void
GarminFitFormat::fit_parse_definition_message(uint8_t header)
{
int local_id = header & 0x0f;
fit_message_def def;
// first byte is reserved. It's usually 0 and we don't know what it is,
// but we've seen some files that are 0x40. So we just read it and toss it.
(void) fit_getuint8();
// second byte is endianness
def.endian = fit_getuint8();
if (def.endian > 1) {
throw ReaderException(QStringLiteral("Bad endian field 0x%1 at file position 0x%2.").arg(def.endian, 0, 16).arg(gbftell(fin) - 1, 0, 16).toStdString());
}
fit_data.endian = def.endian;
// next two bytes are the global message number
def.global_id = fit_getuint16();
// byte 5 has the number of records in the remainder of the definition message
int num_fields = fit_getuint8();
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": definition message contains " << num_fields << " records";
}
// remainder of the definition message is data at one byte per field * 3 fields
for (int i = 0; i < num_fields; ++i) {
int id = fit_getuint8();
int size = fit_getuint8();
int type = fit_getuint8();
fit_field_t field = {id, size, type};
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": record " << i << " ID: " << field.id << " SIZE: "
<< field.size << " TYPE: " << field.type << " fit_data.len="
<< fit_data.len;
}
def.fields.append(field);
}
// If we have developer fields (since version 2.0) they must be read too
// These is one byte containing the number of fields and 3 bytes for every field.
// So this is identical to the normal fields but the meaning of the content is different.
//
// Currently we just want to ignore the developer fields because they are not meant
// to hold relevant data we need (currently handle) for the conversion.
// For simplicity using the existing infrastructure we do it in the following way:
// * We read it in as normal fields
// * We set the field id to kFieldInvalid so that it do not interfere with valid id's from
// the normal fields.
// -In our opinion in practice this will not happen, because we do not expect
// developer fields e.g. inside lap or record records. But we want to be safe here.
// * We do not have to change the type as we did for the id above, because fit_read_field()
// already uses the size information to read the data, if the type does not match the size.
//
// If we want to change this or if we want to avoid the xrealloc call, we can change
// it in the future by e.g. extending the fit_message_def struct.
// Bit 5 of the header specify if we have developer fields in the data message
bool hasDevFields = static_cast<bool>(header & 0x20);
if (hasDevFields) {
int numOfDevFields = fit_getuint8();
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": definition message contains " << numOfDevFields << " developer records";
}
if (numOfDevFields > 0) {
int numOfFields = num_fields + numOfDevFields;
for (int i = num_fields; i < numOfFields; ++i) {
int id = fit_getuint8();
int size = fit_getuint8();
int type = fit_getuint8();
fit_field_t field = {id, size, type};
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": developer record " << i - num_fields <<
" ID: " << field.id << " SIZE: " << field.size <<
" TYPE: " << field.type << " fit_data.len=" << fit_data.len;
}
// Because we parse developer fields like normal fields and we do not want
// that the field id interfere which valid id's from the normal fields
field.id = kFieldInvalid;
def.fields.append(field);
}
}
}
fit_data.message_def.insert(local_id, def);
}
QVariant
GarminFitFormat::fit_read_field(const fit_field_t& f)
{
/* https://forums.garmin.com/showthread.php?223645-Vivoactive-problems-plus-suggestions-for-future-firmwares&p=610929#post610929
* Per section 4.2.1.4.2 of the FIT Protocol the size of a field may be a
* multiple of the size of the underlying type, indicating the field
* contains multiple elements represented as an array.
*
* Garmin Product Support
*/
// In the case that the field contains one value of the indicated type we return that value,
// otherwise we just skip over the data.
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": fit_read_field: read data field with f.type=0x" <<
Qt::hex << f.type << " and f.size=" <<
Qt::dec << f.size << " fit_data.len=" << fit_data.len;
}
switch (f.type) {
case 0: // enum
case 1: // sint8
case 2: // uint8
if (f.size == 1) {
return fit_getuint8();
} else { // ignore array data
for (int i = 0; i < f.size; ++i) {
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": fit_read_field: skipping 1-byte array data";
}
return -1;
}
case 0x7:
return fit_getstring(f.size);
case 0x83: // sint16
case 0x84: // uint16
if (f.size == 2) {
return fit_getuint16();
} else { // ignore array data
for (int i = 0; i < f.size; ++i) {
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": fit_read_field: skipping 2-byte array data";
}
return -1;
}
case 0x85: // sint32
case 0x86: // uint32
if (f.size == 4) {
return fit_getuint32();
} else { // ignore array data
for (int i = 0; i < f.size; ++i) {
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": fit_read_field: skipping 4-byte array data";
}
return -1;
}
default: // Ignore everything else for now.
for (int i = 0; i < f.size; ++i) {
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
Debug(8) << MYNAME ": fit_read_field: skipping unrecognized data type";
}
return -1;
}
}
void
GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset)
{
uint32_t timestamp = fit_data.last_timestamp + time_offset;
int32_t lat = 0x7fffffff;
int32_t lon = 0x7fffffff;
uint16_t alt = 0xffff;
uint16_t speed = 0xffff;
uint8_t heartrate = 0xff;
uint8_t cadence = 0xff;
uint16_t power = 0xffff;
int8_t temperature = 0x7f;
//int32_t startlat = 0x7fffffff;
//int32_t startlon = 0x7fffffff;
int32_t endlat = 0x7fffffff;
int32_t endlon = 0x7fffffff;
//uint32_t starttime = 0; // ??? default ?
uint8_t event = 0xff;
uint8_t eventtype = 0xff;
QString name;
QString description;
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data ID " << def.global_id << " with num_fields=" << def.fields.size();
}
for (int i = 0; i < def.fields.size(); ++i) {
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing field " << i;
}
const fit_field_t& f = def.fields.at(i);
QVariant field = fit_read_field(f);
uint32_t val = -1;
if (field.canConvert<uint>()) {
val = field.toUInt();
}
if (f.id == kFieldTimestamp) {
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: timestamp=" << static_cast<int32_t>(val);
}
timestamp = val;
// if the timestamp is < 0x10000000, this value represents
// system time; to convert it to UTC, add the global utc offset to it
if (timestamp < 0x10000000) {
timestamp += fit_data.global_utc_offset;
}
fit_data.last_timestamp = timestamp;
} else {
switch (def.global_id) {
case kIdDeviceSettings: // device settings message
switch (f.id) {
case kFieldGlobalUtcOffset:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: global utc_offset=" << static_cast<int32_t>(val);
}
fit_data.global_utc_offset = val;
break;
default:
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT device settings: f.id=" << f.id;
}
break;
} // switch (f.id)
// end of case def.global_id = kIdDeviceSettings
break;
case kIdRecord: // record message - trkType is a track
switch (f.id) {
case kFieldLatitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast<int32_t>(val);
}
lat = val;
break;
case kFieldLongitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast<int32_t>(val);
}
lon = val;
break;
case kFieldAltitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
}
break;
case kFieldHeartRate:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: heartrate=" << static_cast<int32_t>(val);
}
heartrate = val;
break;
case kFieldCadence:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: cadence=" << static_cast<int32_t>(val);
}
cadence = val;
break;
case kFieldDistance:
// NOTE: 5 is DISTANCE in cm ... unused.
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id;
}
break;
case kFieldSpeed:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: speed=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
speed = val;
}
break;
case kFieldPower:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: power=" << static_cast<int32_t>(val);
}
power = val;
break;
case kFieldTemperature:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: temperature=" << static_cast<int32_t>(val);
}
temperature = val;
break;
case kFieldEnhancedSpeed:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: enhanced_speed=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
speed = val;
}
break;
case kFieldEnhancedAltitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: enhanced_altitude=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
}
break;
default:
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id;
}
break;
} // switch (f.id)
// end of case def.global_id = kIdRecord
break;
case kIdLap: // lap wptType , endlat+lon is wpt
switch (f.id) {
case kFieldStartTime:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: starttime=" << static_cast<int32_t>(val);
}
//starttime = val;
break;
case kFieldStartLatitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: startlat=" << static_cast<int32_t>(val);
}
//startlat = val;
break;
case kFieldStartLongitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: startlon=" << static_cast<int32_t>(val);
}
//startlon = val;
break;
case kFieldEndLatitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: endlat=" << static_cast<int32_t>(val);
}
endlat = val;
break;
case kFieldEndLongitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: endlon=" << static_cast<int32_t>(val);
}
endlon = val;
break;
case kFieldElapsedTime:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: elapsedtime=" << static_cast<int32_t>(val);
}
//elapsedtime = val;
break;
case kFieldTotalDistance:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: totaldistance=" << static_cast<int32_t>(val);
}
//totaldistance = val;
break;
default:
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT lap: f.id=" << f.id;
}
break;
} // switch (f.id)
// end of case def.global_id = kIdLap
break;
case kIdEvent:
switch (f.id) {
case kFieldEvent:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: event=" << static_cast<int32_t>(val);
}
event = val;
break;
case kFieldEventType:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: eventtype=" << static_cast<int32_t>(val);
}
eventtype = val;
break;
} // switch (f.id)
// end of case def.global_id = kIdEvent
break;
case kIdLocations:
switch (f.id) {
case kFieldLocLatitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast<int32_t>(val);
}
lat = val;
break;
case kFieldLocLongitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast<int32_t>(val);
}
lon = val;
break;
case kFieldLocAltitude:
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
}
break;
case kFieldLocationName:
name = field.toString();
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: location name=" << name;
}
break;
case kFieldLocationDescription:
description = field.toString();
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": parsing fit data: location description=" << description;
}
break;
default:
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT locations: f.id=" << f.id;
}
break;
} // switch (f.id)
// end of case def.global_id = kIdLocations
break;
default:
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": unrecognized/unhandled global ID for GARMIN FIT: " << def.global_id;
}
break;
} // switch (def.global_id)
}
}
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": storing fit data with num_fields=" << def.fields.size();
}
switch (def.global_id) {
case kIdLap: { // lap message
if (endlat == 0x7fffffff || endlon == 0x7fffffff) {
break;
}
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": storing fit data LAP " << def.global_id;
}
auto* lappt = new Waypoint;
lappt->latitude = GPS_Math_Semi_To_Deg(endlat);
lappt->longitude = GPS_Math_Semi_To_Deg(endlon);
lappt->shortname = QStringLiteral("LAP%1").arg(++lap_ct, 3, 10, QLatin1Char('0'));
waypt_add(lappt);
}
break;
case kIdRecord: { // record message
if ((lat == 0x7fffffff || lon == 0x7fffffff) && !opt_allpoints) {
break;
}
auto* waypt = new Waypoint;
if (lat != 0x7fffffff) {
waypt->latitude = GPS_Math_Semi_To_Deg(lat);
}
if (lon != 0x7fffffff) {
waypt->longitude = GPS_Math_Semi_To_Deg(lon);
}
if (alt != 0xffff) {
waypt->altitude = (alt / 5.0) - 500;
}
waypt->SetCreationTime(GPS_Math_Gtime_To_Utime(timestamp));
if (speed != 0xffff) {
WAYPT_SET(waypt, speed, speed / 1000.0f);
}
if (heartrate != 0xff) {
waypt->heartrate = heartrate;
}
if (cadence != 0xff) {
waypt->cadence = cadence;
}
if (power != 0xffff) {
waypt->power = power;
}
if (temperature != 0x7f) {
WAYPT_SET(waypt, temperature, temperature);
}
if (new_trkseg) {
waypt->wpt_flags.new_trkseg = 1;
new_trkseg = false;
}
track_add_wpt(fit_data.track, waypt);
}
break;
case kIdEvent: // event message
if (event == kEnumEventTimer && eventtype == kEnumEventTypeStart) {
// Start event, start new track segment. Note: We don't do this
// on stop events because some GPS devices seem to generate a last
// trackpoint after the stop event and that would erroneously get
// assigned to the next segment.
new_trkseg = true;
}
break;
case kIdLocations: { // locations message
if (lat == 0x7fffffff || lon == 0x7fffffff) {
break;
}
if (global_opts.debug_level >= 7) {
Debug(7) << MYNAME ": storing fit data location " << def.global_id;
}
auto* locpt = new Waypoint;
locpt->latitude = GPS_Math_Semi_To_Deg(lat);
locpt->longitude = GPS_Math_Semi_To_Deg(lon);
if (alt != 0xffff) {
locpt->altitude = (alt / 5.0) - 500;
}
locpt->shortname = name;
locpt->description = description;
waypt_add(locpt);
}
break;
}
}
void
GarminFitFormat::fit_parse_data_message(uint8_t header)
{
int local_id = header & 0x0f;
if (fit_data.message_def.contains(local_id)) {
fit_parse_data(fit_data.message_def.value(local_id), 0);
} else {
throw ReaderException(
QString("Message %1 hasn't been defined before being used at file position 0x%2.").
arg(local_id).arg(gbftell(fin) - 1, 0, 16).toStdString());
}
}
void
GarminFitFormat::fit_parse_compressed_message(uint8_t header)
{
int local_id = (header >> 5) & 3;
if (fit_data.message_def.contains(local_id)) {
fit_parse_data(fit_data.message_def.value(local_id), header & 0x1f);
} else {
throw ReaderException(
QString("Compressed message %1 hasn't been defined before being used at file position 0x%2.").
arg(local_id).arg(gbftell(fin) - 1, 0, 16).toStdString());
}
}
/*******************************************************************************
* fit_parse_record- parse each record in the file
*******************************************************************************/
void
GarminFitFormat::fit_parse_record()
{
gbsize_t position = gbftell(fin);
uint8_t header = fit_getuint8();
// high bit 7 set -> compressed message (0 for normal)
// second bit 6 set -> 0 for data message, 1 for definition message
// bit 5 -> message type specific
// definition message: Bit set means that we have additional Developer Field definitions
// behind the field definitions inside the record content
// data message: currently not used
// bit 4 -> reserved
// bits 3..0 -> local message type
if (header & 0x80) {
if (global_opts.debug_level >= 6) {
Debug(6) << MYNAME ": got compressed message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
fit_parse_compressed_message(header);
} else if (header & 0x40) {
if (global_opts.debug_level >= 6) {
Debug(6) << MYNAME ": got definition message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
fit_parse_definition_message(header);
} else {
if (global_opts.debug_level >= 6) {
Debug(6) << MYNAME ": got data message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
fit_parse_data_message(header);
}
}
void
GarminFitFormat::fit_check_file_crc() const
{
// Check file CRC
gbsize_t position = gbftell(fin);
uint16_t crc = 0;
gbfseek(fin, 0, SEEK_SET);
while (true) {
int data = gbfgetc(fin);
if (data == EOF) {
break;
}
crc = fit_crc16(data, crc);
}
if (crc != 0) {
Warning().nospace() << MYNAME ": File CRC mismatch in file " << fin->name << ".";
if (!opt_recoverymode) {
fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
}
} else if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": File CRC verified.";
}
gbfseek(fin, position, SEEK_SET);
}
/*******************************************************************************
* fit_read- global entry point
* - parse the header
* - parse all the records in the file
*******************************************************************************/
void
GarminFitFormat::read()
{
fit_check_file_crc();
fit_parse_header();
fit_data.track = new route_head;
track_add_head(fit_data.track);
if (global_opts.debug_level >= 1) {
Debug(1) << MYNAME ": starting to read data with fit_data.len=" << fit_data.len;
}
try {
while (fit_data.len) {
fit_parse_record();
}
} catch (ReaderException& e) {
if (opt_recoverymode) {
warning(MYNAME ": %s\n",e.what());
warning(MYNAME ": Aborting read and continuning processing.\n");
} else {
fatal(MYNAME ": %s Use recoverymode option at your risk.\n",e.what());
}
}
}
/*******************************************************************************
* FIT writing
*******************************************************************************/
void
GarminFitFormat::fit_write_message_def(uint8_t local_id, uint16_t global_id, const std::vector<fit_field_t>& fields) const
{
gbfputc(0x40 | local_id, fout); // Local ID
gbfputc(0, fout); // Reserved
gbfputc(0, fout); // Little endian
gbfputuint16(global_id, fout); // Global ID
gbfputc(fields.size(), fout); // Number of fields
for (auto&& field : fields) {
gbfputc(field.id, fout); // Field definition number
gbfputc(field.size, fout); // Field size in bytes
gbfputc(field.type, fout); // Field type
}
}
uint16_t
GarminFitFormat::fit_crc16(uint8_t data, uint16_t crc)
{
static const uint16_t crc_table[] = {
0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400
};
crc = (crc >> 4) ^ crc_table[crc & 0xf] ^ crc_table[data & 0xf];
crc = (crc >> 4) ^ crc_table[crc & 0xf] ^ crc_table[(data >> 4) & 0xf];
return crc;
}
void
GarminFitFormat::fit_write_timestamp(const gpsbabel::DateTime& t) const
{
uint32_t t_fit;
if (t.isValid() && t.toTime_t() >= (unsigned int)GPS_Math_Gtime_To_Utime(0)) {
t_fit = GPS_Math_Utime_To_Gtime(t.toTime_t());
} else {
t_fit = 0xffffffff;
}
gbfputuint32(t_fit, fout);
}
void
GarminFitFormat::fit_write_fixed_string(const QString& s, unsigned int len) const
{
QString trimmed(s);
QByteArray u8buf;
// Truncate if too long, making sure not to chop in the middle of a UTF-8
// character (i.e. we chop the unicode string and then check whether its
// UTF-8 representation fits)
while (true) {
u8buf = trimmed.toUtf8();
if (static_cast<unsigned int>(u8buf.size()) < len) {
break;
}
trimmed.chop(1);
}
// If the string was too short initially or we had to chop multibyte
// characters, the UTF-8 representation might be too short now, so pad
// it.
u8buf.append(len - u8buf.size(), '\0');
gbfwrite(u8buf.data(), len, 1, fout);
}
void
GarminFitFormat::fit_write_position(double pos) const
{
if (pos >= -180 && pos < 180) {
gbfputint32(GPS_Math_Deg_To_Semi(pos), fout);
} else {
gbfputint32(0xffffffff, fout);
}
}
// Note: The data fields written using fit_write_msg_*() below need to match
// the message field definitions in fit_msg_fields_* above!
void
GarminFitFormat::fit_write_msg_file_id(uint8_t type, uint16_t manufacturer, uint16_t product,
const gpsbabel::DateTime& time_created) const
{
gbfputc(kWriteLocalIdFileId, fout);
gbfputc(type, fout);
gbfputuint16(manufacturer, fout);
gbfputuint16(product, fout);
fit_write_timestamp(time_created);
}
void
GarminFitFormat::fit_write_msg_course(const QString& name, uint8_t sport) const
{
gbfputc(kWriteLocalIdCourse, fout);
fit_write_fixed_string(name, 0x10);
gbfputc(sport, fout);
}
void
GarminFitFormat::fit_write_msg_lap(const gpsbabel::DateTime& timestamp, const gpsbabel::DateTime& start_time,
double start_position_lat, double start_position_long,
double end_position_lat, double end_position_long,
uint32_t total_elapsed_time_s, double total_distance_m,
double avg_speed_ms, double max_speed_ms) const
{
gbfputc(kWriteLocalIdLap, fout);
fit_write_timestamp(timestamp);
fit_write_timestamp(start_time);
fit_write_position(start_position_lat);
fit_write_position(start_position_long);
fit_write_position(end_position_lat);
fit_write_position(end_position_long);
if (total_elapsed_time_s < 4294967) {
gbfputuint32(total_elapsed_time_s * 1000, fout);
gbfputuint32(total_elapsed_time_s * 1000, fout);
} else {
gbfputuint32(0xffffffff, fout);
gbfputuint32(0xffffffff, fout);
}
if (total_distance_m >= 0 && total_distance_m < 42949672.94) {
gbfputuint32(total_distance_m * 100, fout);
} else {
gbfputuint32(0xffffffff, fout);
}
if (avg_speed_ms >= 0 && avg_speed_ms < 65.534) {
gbfputuint16(avg_speed_ms * 1000, fout);