-
Notifications
You must be signed in to change notification settings - Fork 20
/
fit2gpx.pl
executable file
·2023 lines (1777 loc) · 73.2 KB
/
fit2gpx.pl
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
#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use lib $FindBin::RealBin;
use Garmin::FIT;
use POSIX;
use POSIX::strftime::GNU;
use File::Basename;
use List::Util qw(sum);
use Config::Simple ('-lc'); # ignore case
#use GD::Graph::Data;
#use GD::Graph::lines;
#------------------------------------------------------------------------------
# Global variables definition
(my $prog = basename($0)) =~ s/.pl$//i;
my $def_ini_file = $prog.".ini"; # default ini file
my $indent = " " x 4; # default indent: 4 spaces
my $timeoffs = 631065600; # sec since Garmin Epoch (1989-12-31 00:00:00 GMT)
# Min/max/average values
my $g_minAlt = 10000;
my $g_maxAlt = -10000;
my $alts = [];
my $g_minHr = 10000;
my $g_maxHr = -10000; # already in session/lap data
my $hrs = []; # already in session/lap data
my $g_minTemp = 10000;
my $g_maxTemp = -10000;
my $temps = [];
my $speedDownhills = [];
my $speedUphills = [];
my $g_minIncl = 10000;
my $g_maxIncl = -10000;
my $incls = [];
my $inclDownhills = [];
my $inclUphills = [];
my $g_minPower = 10000;
my $g_maxPower = -10000;
my $powers = [];
my $g_minRiseRate = 10000;
my $g_maxRiseRate = -10000;
my $riseRates = [];
my $riseRateDownhills = [];
my $riseRateUphills = [];
# General info (from file_id)
my $g_manuf; # garmin, suunto, magellan, holux, sigmasport, ...
my $g_product; # fr___, edge___, hrm___, vivo___, virb___, ...
my $g_serial;
# SigmaSport: cycling, mountainbike, racing_bicycle (road bike), running, ...
my $g_sport; # generic, running, cycling, training, walking, ...
my $g_subSport; # generic, road, mountain, downhill, ...
my $g_trainType; # SigmaSport specific (manual entry)
# Personal info (from user_profile)
my $g_name; my $g_gender; my $g_age; my $g_height; my $g_weight;
my $g_resHr; my $g_hrMax;
my $g_bmr; my $g_bmrs; # basal metabolic rate
my $g_bike;
my $g_bikeName; my $g_bikeType; my $g_bikeWeight; my $g_wheelSize;
my $g_homeAlt;
my $g_trackName; my $g_description;
# Functional threshold power (from zones_target)
my $g_funcThresPower;
my $g_hrMax1; # another one???
# Intensity zones starting percent of maximum heart rate
my $pc_iZone0s = 0.50; # recovery (aerobic)
my $pc_iZone1s = 0.60; # endurance (aerobic)
my $pc_iZone2s = 0.70; # stamina (aerobic)
my $pc_iZone3s = 0.80; # economy (anaerobic)
my $pc_iZone4s = 0.90; # speed (anaerobic)
my $g_iZone0s; my $g_iZone1s; my $g_iZone2s;
my $g_iZone3s; my $g_iZone4s; my $g_iZone4e;
# Target zone (endurance (aerobic), can be overriden)
my $g_targetZoneStart; # 60% of hrMax
my $g_targetZoneEnd; # 70% of hrMax
# Power zones starting percent of functional threshold power
my $pc_pZone1s = 0; # active recovery
my $pc_pZone2s = 0.56; # endurance
my $pc_pZone3s = 0.76; # tempo
my $pc_pZone4s = 0.91; # lactate threshold
my $pc_pZone5s = 1.06; # VO2 max
my $pc_pZone6s = 1.21; # anaerobic capacity
my $pc_pZone7s = 1.50; # neuromuscular power
my $g_pZoneMax = 2000; # W, maximum power
my $g_pZone1s; my $g_pZone2s; my $g_pZone3s;
my $g_pZone4s; my $g_pZone5s; my $g_pZone6s;
my $g_pZone7s; my $g_pZone7e;
# Power calculation
# Crr = coef of rolling resistance ???
# 0 = Clinchers, 1 = Tubulars, 2 = MTB
my @Crr = (0.005, 0.004, 0.012);
# CdA = coef of drag * frontal area ???
# 0 = Hoods, 1 = Bartops, 2 = Bar ends, 3 = Drops, 4 = Aerobar, 5 = ???
my @CdA = (0.388, 0.445, 0.420, 0.300, 0.233, 0.200);
my $g_crr = $Crr[2]; # MTB
my $g_cda = $CdA[0]; # Hoods
my $g_pcf = 0.65;
my $g_kcf = 0.65;
# Totals/summary info (from lap/session)
my $g_startTime;
my $f_startTime = ""; # start time in proper format
my $g_startLon; my $g_startLat;
# endLon and endLat are not present in session!
my $g_endLon; my $g_endLat;
my $g_totElapsTime; my $g_totTimerTime;
my $g_totTimeStand;
my $g_totDistance; my $g_totCycles;
my $g_totCal;
my $g_timeHrZone; # array
my $g_avgSpeed; my $g_maxSpeed;
my $g_totAscent; my $g_totDescent;
my $g_avgHr; # my $g_maxHr;
my $g_avgCad; my $g_maxCad;
my $g_avgPower; # my $g_maxPower;
# Calculated totals/summary info
my $g_distDownhill; my $g_distUphill;
my $g_timeDownhill; my $g_timeUphill;
my $g_pauseTime;
my $g_timeInTargetZone;
my $g_timeOverTargetZone; my $g_timeUnderTargetZone;
my $g_timeInIntZone1; my $g_timeInIntZone2;
my $g_timeInIntZone3; my $g_timeInIntZone4;
my $g_timeOverIntZone; my $g_timeUnderIntZone;
# Previous values of each track point
my $prev_timestamp;
my $prev_lat; my $prev_lon;
# my $prev_dist; my $prev_alt;
my $prev_speed; my $prev_hr; my $prev_cad; my $prev_temp;
my $tot_time = 0;
my $tot_records = 0;
my $tot_locations = 0;
# Previous values of dist/alt for dist/alt filtering (smoothing)
my $histSize = 6;
my @prev_time;
my @prev_dist; my @prev_distDiff;
my @prev_alt; my @prev_altDiff;
my %alt_state = ( q => 0, r => 0, p => 0, x => 0, k => 0, );
my $orig_alt = [];
my $filt_alt = [];
#my %pwr_state = ( q => 0, r => 0, p => 0, x => 0, k => 0, );
#------------------------------------------------------------------------------
# Command line parsing
my $overwrite = 0;
my $fpcalc = 0; # force power calculation
my $zeroll = 0; # allow zero values for latitude/longitude if not present
my $garmin_ext = 1; # 0 means cluetrust_ext
my $rev_coord = 0; # default: lat=... lon=...
my $ts_offs = 0; # timestamp offset
my $ini_file = $def_ini_file; # ini file
my $file;
my $next_arg = "";
foreach (@ARGV) {
my $arg = $_;
if ($next_arg eq "ts_offs") { $ts_offs = $arg; $next_arg = ""; }
elsif ($next_arg eq "ini_file") { $ini_file = $arg; $next_arg = ""; }
elsif ($arg eq "-v") { Usage(1); }
elsif ($arg eq "-h" || $arg eq "-?") { Usage(0); }
elsif ($arg eq "-y") { $overwrite = 1; }
elsif ($arg eq "-p") { $fpcalc = 1; }
elsif ($arg eq "-z") { $zeroll = 1; }
elsif ($arg eq "-g") { $garmin_ext = 1; }
elsif ($arg eq "-c") { $garmin_ext = 0; }
elsif ($arg eq "-r") { $rev_coord = 1; }
elsif ($arg eq "-t") { $next_arg = "ts_offs"; }
elsif ($arg eq "-i") { $next_arg = "ini_file"; }
else { $file = $arg; }
}
Usage(0) if !defined $file;
(my $gpx_file = $file) =~ s/.fit$/.gpx/i;
die "File $gpx_file already exists\n" if -f $gpx_file && !$overwrite;
#------------------------------------------------------------------------------
# Fit file reading
# Array of HASHes where fit data is stored
my $file_ids = [];
my $profiles = [];
my $sensors = [];
my $zones = [];
my $records = [];
my $lengths = [];
my $laps = [];
my $sessions = [];
my $locations = [];
my $fit = Garmin::FIT->new();
ReadFitFile($file);
#------------------------------------------------------------------------------
# Fill global vars with values from fit file
FillGlobalVars();
# Override values from fit file with values from ini file
ReadIniFile($ini_file);
#------------------------------------------------------------------------------
# Convert and display fit file content in slf format
PrintGpxData($gpx_file);
exit(0);
# main
#==============================================================================
# Print version/usage and exit
sub Usage {
my $ver_only = shift;
if ($ver_only) {
printf STDERR "fit2gpx 2.19 Copyright (c) 2016-2021 Matjaz Rihtar (Jan 9, 2021)\n";
printf STDERR "Garmin::FIT Copyright (c) 2010-2017 Kiyokazu Suto\n";
printf STDERR "FIT protocol ver: %s, profile ver: %s\n",
Garmin::FIT->protocol_version_string, Garmin::FIT->profile_version_string;
}
else {
printf STDERR "Usage: $prog [-v|-h] [-y] [-p] [-z] [-g|-c] [-r] [-t <offs>] [-i <config-file>] <fit-file>\n";
printf STDERR " -v Print version and exit\n";
printf STDERR " -h Print short help and exit\n";
printf STDERR " -y Overwrite <slf-file> if it exists (default: don't overwrite)\n";
printf STDERR " -p Force power calculation (default: use fit power data if present)\n";
printf STDERR " -z Allow zero values for latitude/longitude if not present\n";
printf STDERR " (default: ignore records with no latitude/longitude)\n";
printf STDERR " -g Use Garmin extension format for hr/cad/temp (default)\n";
printf STDERR " <gpxtpx:TrackPointExtension>, <gpxtpx:...>: atemp, hr, cad\n";
printf STDERR " -c Use Cluetrust extension format for hr/cad/temp\n";
printf STDERR " <gpxdata:...>: temp, hr, cadence\n";
printf STDERR " -r Reverse print of lat and lon in trkpt entries\n";
printf STDERR " (default: <trkpt lat=... lon=...>)\n";
printf STDERR " -t <offs> Add timestamp offset (integer, default: 0)\n";
printf STDERR " -i <config-file> Specify location of .ini file (default: program's location)\n";
}
_exit(1);
} # Usage
#==============================================================================
# Read fit file, parse messages and store interesting data for later processing
sub ReadFitFile {
my $fname = shift;
# Setup some defaults
$fit->use_gmtime(1);
$fit->numeric_date_time(1);
$fit->semicircles_to_degree(1);
$fit->mps_to_kph(1);
$fit->without_unit(1);
$fit->maybe_chained(0);
$fit->drop_developer_data(1);
$fit->file($fname);
$fit->data_message_callback_by_name('',
sub {
my ($msg, $name) = Message(@_);
if ($msg) {
if ($name eq "file_id") { push @$file_ids, $msg; }
elsif ($name eq "user_profile") { push @$profiles, $msg; }
elsif ($name eq "sensor") { push @$sensors, $msg; }
elsif ($name eq "zones_target") { push @$zones, $msg; }
elsif ($name eq "record") { push @$records, $msg; }
elsif ($name eq "length") { push @$lengths, $msg; }
elsif ($name eq "lap") { push @$laps, $msg; }
elsif ($name eq "session") { push @$sessions, $msg; }
elsif ($name eq "location") { push @$locations, $msg; }
}
return 1;
}
);
# Open and read fit file
$fit->open() or die $fit->error()."\n";
my ($f_size) = $fit->fetch_header();
if (!defined $f_size) {
if (!defined $fit->error()) { $fit->error("can't read FIT header"); }
die $fit->error()."\n";
}
1 while $fit->fetch();
} # ReadFitFile
#==============================================================================
# Parse messages from fit file (see Garmin::FIT)
sub Message {
my ($fit, $desc, $v) = @_;
my $mname = $desc->{message_name};
return undef if !$mname;
my $m = {};
foreach my $i_name (keys %$desc) {
next if $i_name !~ /^i_/;
my $name = $i_name;
$name =~ s/^i_//;
my $attr = $desc->{'a_' . $name};
my $tname = $desc->{'t_' . $name};
my $pname = $name;
if (ref $attr->{switch} eq 'HASH') {
my $t_attr = $fit->switched($desc, $v, $attr->{switch});
if (ref $t_attr eq 'HASH') {
$attr = $t_attr;
$tname = $attr->{type_name};
$pname = $attr->{name};
}
}
my $i = $desc->{$i_name};
my $c = $desc->{'c_' . $name};
my $type = $desc->{'T_' . $name};
my $invalid = $desc->{'I_' . $name};
my $j;
my $len = @$v;
for ($j = 0 ; $j < $c ; $j++) {
my $ij = $i + $j;
$ij >= $len && next;
Garmin::FIT->isnan($v->[$ij]) && next;
$v->[$ij] != $invalid && last;
}
if ($j < $c) { # skip invalid
if ($type == FIT_STRING) {
$m->{$pname} = $fit->string_value($v, $i, $c);
}
else {
# return only the first value if array
$m->{$pname} = $fit->value_cooked($tname, $attr, $invalid, $v->[$i]);
}
}
}
return ($m, $mname);
} # Message
#==============================================================================
# Go through fit data and fill global vars with general data
# For calculating some missing aver/min/max values, routine for processing
# all track points is called at the end with some reasonable defaults.
sub FillGlobalVars {
my $m; my %mh;
my $k; my $v;
# Find manufacturer, product name and serial in file_id
$m = @{$file_ids}[0];
if (defined $m) {
%mh = %$m;
while (($k, $v) = each %mh) {
if ($k eq "manufacturer") { $g_manuf = ucfirst $v; }
elsif ($k eq "garmin_product") { $g_product = $v; }
elsif ($k eq "product") { $g_product = $v; } # for non Garmin products
elsif ($k eq "serial_number") { $g_serial = $v; }
}
}
# Fill in default values if no data found
$g_manuf = "Generic" if !defined $g_manuf;
$g_product = "unknown" if !defined $g_product;
# Find profile data in first user_profile
$m = @{$profiles}[0];
if (defined $m) {
%mh = %$m;
while (($k, $v) = each %mh) {
if ($k eq "friendly_name") { my $friendlyName = $v; }
elsif ($k eq "weight") { $g_weight = $v; } # kg
elsif ($k eq "gender") { $g_gender = $v; }
elsif ($k eq "age") { $g_age = $v; } # years
elsif ($k eq "height") { $g_height = $v; } # m
elsif ($k eq "resting_heart_rate") { $g_resHr = $v; }
elsif ($k eq "default_max_heart_rate") { $g_hrMax = $v; }
}
}
my $undef_gender = 0;
if (!defined $g_gender) { $g_gender = "male"; $undef_gender = 1; }
my $undef_age = 0;
if (!defined $g_age) { $g_age = 40; $undef_age = 1; }
my $undef_weight = 0;
if (!defined $g_weight) { $g_weight = 75.0; $undef_weight = 1; }
my $undef_resHr = 0;
if (!defined $g_resHr) { $g_resHr = 72; $undef_resHr = 1; }
my $undef_hrMax = 0;
if (!defined $g_hrMax) {
# Usual formula: 220 - age
# Tanaka(2001): 208 - 0.7*age
# Gellish(2007): 206.9 - 0.67*age (207 - 0.7*age)
# HUNT(2012): 211 - 0.64*age (men: 213 - 0.65*age, women: 210 - 0.62*age)
if ($g_gender eq "male") { $g_hrMax = int(213 - 0.65*$g_age); }
else { $g_hrMax = int(210 - 0.62*$g_age); }
$undef_hrMax = 1;
}
# Intensity zones
$g_iZone0s = int($g_hrMax * $pc_iZone0s); # recovery (aerobic)
$g_iZone1s = int($g_hrMax * $pc_iZone1s); # endurance (aerobic)
$g_iZone2s = int($g_hrMax * $pc_iZone2s); # stamina (aerobic)
$g_iZone3s = int($g_hrMax * $pc_iZone3s); # economy (anaerobic)
$g_iZone4s = int($g_hrMax * $pc_iZone4s); # speed (anaerobic)
$g_iZone4e = $g_hrMax;
# Target zone
$g_targetZoneStart = int($g_hrMax * $pc_iZone1s); # endurance (aerobic)
$g_targetZoneEnd = int($g_hrMax * $pc_iZone2s);
# Find wheel size in sensors
foreach (@$sensors) {
while (($k, $v) = each %$_) {
if ($k eq "wheel_size") { $g_wheelSize = $v; }
}
}
my $undef_wheelSize = 0;
if (!defined $g_wheelSize) { $g_wheelSize = 2326; $undef_wheelSize = 1; }
# find zones data in first zones_target
$m = @{$zones}[0];
if (defined $m) {
%mh = %$m;
while (($k, $v) = each %mh) {
if ($k eq "functional_threshold_power") { $g_funcThresPower = $v; }
elsif ($k eq "max_heart_rate") { $g_hrMax1 = $v; } # ???
}
}
my $undef_funcThresPower = 0;
if (!defined $g_funcThresPower) {
$g_funcThresPower = 253; $undef_funcThresPower = 1;
}
# Power zones
$g_pZone1s = $g_funcThresPower * $pc_pZone1s;
$g_pZone2s = $g_funcThresPower * $pc_pZone2s;
$g_pZone3s = $g_funcThresPower * $pc_pZone3s;
$g_pZone4s = $g_funcThresPower * $pc_pZone4s;
$g_pZone5s = $g_funcThresPower * $pc_pZone5s;
$g_pZone6s = $g_funcThresPower * $pc_pZone6s;
$g_pZone7s = $g_funcThresPower * $pc_pZone7s;
$g_pZone7e = $g_pZoneMax;
# Find all needed general info in first session
$m = @{$sessions}[0];
if (defined $m) {
%mh = %$m;
while (($k, $v) = each %mh) {
if ($k eq "start_time") { $g_startTime = $v + $ts_offs; } # + $timeoffs;
elsif ($k eq "sport") { $g_sport = $v; }
elsif ($k eq "sub_sport") { $g_subSport = $v; }
elsif ($k eq "start_position_lat") { $g_startLat = $v; }
elsif ($k eq "start_position_long") { $g_startLon = $v; }
elsif ($k eq "total_elapsed_time") { $g_totElapsTime = $v; }
elsif ($k eq "total_timer_time") { $g_totTimerTime = $v; }
elsif ($k eq "time_standing") { $g_totTimeStand = $v; } # invalid
elsif ($k eq "total_distance") { $g_totDistance = $v; } # m
elsif ($k eq "total_cycles") { $g_totCycles = $v; }
elsif ($k eq "total_calories") { $g_totCal = $v; }
elsif ($k eq "time_in_hr_zone") { $g_timeHrZone = $v; } # array
elsif ($k eq "avg_speed" && !defined $g_avgSpeed) { $g_avgSpeed = $v; }
elsif ($k eq "enhanced_avg_speed") {
if (defined $v) { $g_avgSpeed = $v; } # only if valid
}
elsif ($k eq "max_speed" && !defined $g_maxSpeed) { $g_maxSpeed = $v; }
elsif ($k eq "enhanced_max_speed") {
if (defined $v) { $g_maxSpeed = $v; } # only if valid
}
elsif ($k eq "total_ascent") { $g_totAscent = $v; }
elsif ($k eq "total_descent") { $g_totDescent = $v; }
elsif ($k eq "avg_heart_rate") { $g_avgHr = $v; }
elsif ($k eq "max_heart_rate") { $g_maxHr = $v; }
elsif ($k eq "avg_cadence") { $g_avgCad = $v; }
elsif ($k eq "max_cadence") { $g_maxCad = $v; }
elsif ($k eq "avg_power") { $g_avgPower = $v; } # invalid
elsif ($k eq "max_power") { $g_maxPower = $v; } # invalid
}
}
if (scalar @$laps == 1) {
# Find additional/missing general info in first (and only) lap
$m = @{$laps}[0];
if (defined $m) {
%mh = %$m;
while (($k, $v) = each %mh) {
if ($k eq "start_time" && !defined $g_startTime)
{ $g_startTime = $v + $ts_offs; } # + $timeoffs;
elsif ($k eq "sport" && !defined $g_sport)
{ $g_sport = $v; }
elsif ($k eq "sub_sport" && !defined $g_subSport)
{ $g_subSport = $v; }
elsif ($k eq "start_position_lat" && !defined $g_startLat)
{ $g_startLat = $v; }
elsif ($k eq "start_position_long" && !defined $g_startLon)
{ $g_startLon = $v; }
elsif ($k eq "end_position_lat" && !defined $g_endLat)
{ $g_endLat = $v; }
elsif ($k eq "end_position_long" && !defined $g_endLon)
{ $g_endLon = $v; }
elsif ($k eq "total_elapsed_time" && !defined $g_totElapsTime)
{ $g_totElapsTime = $v; }
elsif ($k eq "total_timer_time" && !defined $g_totTimerTime)
{ $g_totTimerTime = $v; }
elsif ($k eq "time_standing" && !defined $g_totTimeStand)
{ $g_totTimeStand = $v; } # invalid
elsif ($k eq "total_distance" && !defined $g_totDistance)
{ $g_totDistance = $v; } # m
elsif ($k eq "total_cycles" && !defined $g_totCycles)
{ $g_totCycles = $v; }
elsif ($k eq "total_calories" && !defined $g_totCal)
{ $g_totCal = $v; }
elsif ($k eq "time_in_hr_zone" && !defined $g_timeHrZone)
{ $g_timeHrZone = $v; } # array
elsif ($k eq "avg_speed" && !defined $g_avgSpeed)
{ $g_avgSpeed = $v; }
elsif ($k eq "enhanced_avg_speed") {
if (defined $v && !defined $g_avgSpeed) { $g_avgSpeed = $v; } # only if valid
}
elsif ($k eq "max_speed" && !defined $g_maxSpeed)
{ $g_maxSpeed = $v; }
elsif ($k eq "enhanced_max_speed") {
if (defined $v && !defined $g_maxSpeed) { $g_maxSpeed = $v; } # only if valid
}
elsif ($k eq "total_ascent" && !defined $g_totAscent)
{ $g_totAscent = $v; }
elsif ($k eq "total_descent" && !defined $g_totDescent)
{ $g_totDescent = $v; }
elsif ($k eq "avg_heart_rate" && !defined $g_avgHr)
{ $g_avgHr = $v; }
elsif ($k eq "max_heart_rate" && !defined $g_maxHr)
{ $g_maxHr = $v; }
elsif ($k eq "avg_cadence" && !defined $g_avgCad)
{ $g_avgCad = $v; }
elsif ($k eq "max_cadence" && !defined $g_maxCad)
{ $g_maxCad = $v; }
elsif ($k eq "avg_power" && !defined $g_avgPower)
{ $g_avgPower = $v; } # invalid
elsif ($k eq "max_power" && !defined $g_maxPower)
{ $g_maxPower = $v; } # invalid
}
}
}
# Fill in default values if no data found
$g_sport = "generic" if !defined $g_sport;
$g_subSport = "generic" if !defined $g_subSport;
$g_totCal = 0 if !defined $g_totCal;
$g_avgHr = 0 if !defined $g_avgHr;
$g_startTime = time() if !defined $g_startTime;
my @lt = localtime($g_startTime);
$f_startTime = POSIX::strftime("%d-%b-%y %H:%M", @lt);
$g_totElapsTime = 0 if !defined $g_totElapsTime;
$g_trackName = "Track ".$f_startTime;
my $product = ucfirst $g_product;
$g_description = ucfirst "$g_sport ($g_subSport) recorded on $g_manuf $product";
# Some other defaults needed for the 1st call (overriden later)
my $undef_homeAlt;
if (!defined $g_homeAlt) { $g_homeAlt = 315; $undef_homeAlt = 1; }
my $undef_bikeWeight;
if (!defined $g_bikeWeight) { $g_bikeWeight = 12.3; $undef_bikeWeight = 1; }
# Calc missing aver/min/max alt, power, hr, cad and temp from all records
ProcessRecords();
if ($undef_gender) { $g_gender = undef; }
if ($undef_age) { $g_age = undef; }
if ($undef_weight) { $g_weight = undef; }
if ($undef_resHr) { $g_resHr = undef; }
if ($undef_hrMax) { $g_hrMax = undef; }
if ($undef_wheelSize) { $g_wheelSize = undef; }
if ($undef_funcThresPower) { $g_funcThresPower = undef; }
if ($undef_homeAlt) { $g_homeAlt = undef; }
if ($undef_bikeWeight) { $g_bikeWeight = undef; }
} # FillGlobalVars
#==============================================================================
# Read ini file
# File name is the same as this script's name with extension .ini.
# Format is the same as normal Windows .ini file.
# If file is not found, reasonable defaults are applied to undefined variables.
sub ReadIniFile {
my $fname = shift;
my $val;
my $ini = new Config::Simple(syntax=>"ini");
if ($fname eq $def_ini_file) { $ini->read($fname); } # ignore error if no ini file
else { $ini->read($fname) or print STDERR $ini->error()."\n"; }
$val = $ini->param("sport");
# print STDERR "INI: sport = |$val|\n" if defined $val;
if (defined $val) { $g_sport = $val; }
elsif (!defined $g_sport) { $g_sport = "mountainbike"; }
$val = $ini->param("training_type");
# print STDERR "INI: training_type = |$val|\n" if defined $val;
if (defined $val) { $g_trainType = $val; }
elsif (!defined $g_trainType) { $g_trainType = "Riding"; }
$val = $ini->param("home_altitude");
# print STDERR "INI: home_altitude = |$val|\n" if defined $val;
if (defined $val) { $g_homeAlt = $val; }
elsif (!defined $g_homeAlt) { $g_homeAlt = 315; }
$val = $ini->param("track_name");
# print STDERR "INI: track_name = |$val|\n" if defined $val;
if (defined $val) { $g_trackName = $val; }
elsif (!defined $g_trackName) { $g_trackName = ""; }
$val = $ini->param("description");
# print STDERR "INI: description = |$val|\n" if defined $val;
if (defined $val) { $g_description = $val; }
elsif (!defined $g_description) { $g_description = ""; }
$val = $ini->param("personal.name");
# print STDERR "INI: personal.name = |$val|\n" if defined $val;
if (defined $val) { $g_name = $val; }
elsif (!defined $g_name) { $g_name = "John Smith"; }
$val = $ini->param("personal.gender");
# print STDERR "INI: personal.gender = |$val|\n" if defined $val;
if (defined $val) { $g_gender = $val; }
elsif (!defined $g_gender) { $g_gender = "male"; }
my $recalc_hrMax = 0;
$val = $ini->param("personal.age");
# print STDERR "INI: personal.age = |$val|\n" if defined $val;
if (defined $val) { $g_age = $val; $recalc_hrMax = 1; }
elsif (!defined $g_age) { $g_age = 40; $recalc_hrMax = 1; }
$val = $ini->param("personal.height");
# print STDERR "INI: personal.height = |$val|\n" if defined $val;
if (defined $val) { $g_height = $val; }
elsif (!defined $g_height) { $g_height = 183; }
$val = $ini->param("personal.weight");
# print STDERR "INI: personal.weight = |$val|\n" if defined $val;
if (defined $val) { $g_weight = $val; }
elsif (!defined $g_weight) { $g_weight = 75.0; }
$val = $ini->param("personal.resting_heart_rate");
# print STDERR "INI: personal.resting_heart_rate = |$val|\n" if defined $val;
if (defined $val) { $g_resHr = $val; }
elsif (!defined $g_resHr) { $g_resHr = 72; }
my $recalc_targetZone = 0;
$val = $ini->param("personal.max_heart_rate");
# print STDERR "INI: personal.max_heart_rate = |$val|\n" if defined $val;
if (defined $val) { $g_hrMax = $val; $recalc_targetZone = 1; }
elsif (!defined $g_hrMax || $recalc_hrMax) {
# Usual formula: 220 - age
# Tanaka(2001): 208 - 0.7*age
# Gellish(2007): 206.9 - 0.67*age (207 - 0.7*age)
# HUNT(2012): 211 - 0.64*age (men: 213 - 0.65*age, women: 210 - 0.62*age)
if ($g_gender eq "male") { $g_hrMax = int(213 - 0.65*$g_age); }
else { $g_hrMax = int(210 - 0.62*$g_age); }
$recalc_targetZone = 1;
}
$val = $ini->param("personal.target_zone_start");
# print STDERR "INI: personal.target_zone_start = |$val|\n" if defined $val;
if (defined $val) { $g_targetZoneStart = $val; }
elsif (!defined $g_targetZoneStart || $recalc_targetZone) {
$g_targetZoneStart = int($g_hrMax * $pc_iZone1s);
}
$val = $ini->param("personal.target_zone_end");
# print STDERR "INI: personal.target_zone_end = |$val|\n" if defined $val;
if (defined $val) { $g_targetZoneEnd = $val; }
elsif (!defined $g_targetZoneEnd || $recalc_targetZone) {
$g_targetZoneEnd = int($g_hrMax * $pc_iZone2s);
}
$val = $ini->param("personal.ftp");
# print STDERR "INI: personal.ftp = |$val|\n" if defined $val;
if (defined $val) { $g_funcThresPower = $val; }
elsif (!defined $g_funcThresPower) { $g_funcThresPower = 253; }
$g_bike = $ini->param("bike");
$g_bike = "bike1" if !defined $g_bike;
$val = $ini->param($g_bike.".name");
# print STDERR "INI: $g_bike.name = |$val|\n" if defined $val;
if (defined $val) { $g_bikeName = $val; }
elsif (!defined $g_bikeName) { $g_bikeName = "Ibis Ripley 29 LS"; }
$val = $ini->param($g_bike.".type");
# print STDERR "INI: $g_bike.type = |$val|\n" if defined $val;
if (defined $val) { $g_bikeType = $val; }
elsif (!defined $g_bikeType) { $g_bikeType = "MTB"; }
$val = $ini->param($g_bike.".weight");
# print STDERR "INI: $g_bike.weight = |$val|\n" if defined $val;
if (defined $val) { $g_bikeWeight = $val; }
elsif (!defined $g_bikeWeight) { $g_bikeWeight = 12.3; }
$val = $ini->param($g_bike.".wheel_size");
# print STDERR "INI: $g_bike.wheel_size = |$val|\n" if defined $val;
if (defined $val) { $g_wheelSize = $val; }
elsif (!defined $g_wheelSize) { $g_wheelSize = 2326; }
$val = $ini->param($g_bike.".crr");
# print STDERR "INI: $g_bike.crr = |$val|\n" if defined $val;
if (defined $val) { $g_crr = $val; }
elsif (!defined $g_crr) { $g_crr = $Crr[2]; } # MTB
$val = $ini->param($g_bike.".cda");
# print STDERR "INI: $g_bike.cda = |$val|\n" if defined $val;
if (defined $val) { $g_cda = $val; }
elsif (!defined $g_cda) { $g_cda = $CdA[0]; } # Hoods
$val = $ini->param($g_bike.".pcf");
# print STDERR "INI: $g_bike.pcf = |$val|\n" if defined $val;
if (defined $val) { $g_pcf = $val; }
elsif (!defined $g_pcf) { $g_pcf = 0.65; }
$val = $ini->param($g_bike.".kcf");
# print STDERR "INI: $g_bike.kcf = |$val|\n" if defined $val;
if (defined $val) { $g_kcf = $val; }
elsif (!defined $g_kcf) { $g_kcf = 0.65; }
# Mifflin-St.Jeor formula for BMR (1990)
if ($g_gender eq "male")
{ $g_bmr = 9.99*$g_weight + 6.25*$g_height - 4.92*$g_age + 5; }
else
{ $g_bmr = 9.99*$g_weight + 6.25*$g_height - 4.92*$g_age - 161; }
$g_bmrs = $g_bmr / 86400; # bmr/s (bmr is for whole day)
# Intensity zones
$g_iZone0s = int($g_hrMax * $pc_iZone0s); # recovery (aerobic)
$g_iZone1s = int($g_hrMax * $pc_iZone1s); # endurance (aerobic)
$g_iZone2s = int($g_hrMax * $pc_iZone2s); # stamina (aerobic)
$g_iZone3s = int($g_hrMax * $pc_iZone3s); # economy (anaerobic)
$g_iZone4s = int($g_hrMax * $pc_iZone4s); # speed (anaerobic)
$g_iZone4e = $g_hrMax;
# Power zones
$g_pZone1s = $g_funcThresPower * $pc_pZone1s;
$g_pZone2s = $g_funcThresPower * $pc_pZone2s;
$g_pZone3s = $g_funcThresPower * $pc_pZone3s;
$g_pZone4s = $g_funcThresPower * $pc_pZone4s;
$g_pZone5s = $g_funcThresPower * $pc_pZone5s;
$g_pZone6s = $g_funcThresPower * $pc_pZone6s;
$g_pZone7s = $g_funcThresPower * $pc_pZone7s;
$g_pZone7e = $g_pZoneMax;
} # ReadIniFile
#==============================================================================
# Calculate average value of an array
sub Average {
my $len = scalar @_;
$len ? sum( @_ )/$len : 0;
} # Average
#==============================================================================
# Calculate weighted average of an array
# First parameter determines how many values from the array should be used
# Array's last entered value starts at the end of array!
sub Waverage {
my $used = shift;
my $len = scalar @_;
if (!defined $used || $used > $len) { $used = $len; }
my $w; my $wsum = 0; my $div = 0;
for (my $ii = 0, my $jj = -1; $ii < $used; $ii++, $jj--) {
$w = $len + 1 + $jj;
$wsum += $_[$jj]*$w;
$div += $w;
}
$div ? $wsum/$div : 0;
} # Waverage
#==============================================================================
# Calculate median value of an array
sub Median {
my $len = scalar @_;
$len ? sum( ( sort { $a <=> $b } @_ )[ int( $#_/2 ), ceil( $#_/2 ) ] )/2 : 0;
} # Median
#==============================================================================
# Print gpx block (1st line, header) in gpx
sub PrintGpxHeader {
# <gpx version="1.1 [1]" creator="xsd:string [1]">
# <metadata> metadataType </metadata> [0..1]
# <wpt> wptType </wpt> [0..*]
# <rte> rteType </rte> [0..*]
# <trk> trkType </trk> [0..*]
# <extensions> extensionsType </extensions> [0..1]
# </gpx>
printf "<gpx %s", 'version="1.1" creator="fit2gpx by Matjaz Rihtar"';
my $loc = 'xsi:schemaLocation="';
$loc = $loc . "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd";
$loc = $loc . " http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd";
$loc = $loc . " http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www8.garmin.com/xmlschemas/TrackPointExtensionv1.xsd";
$loc = $loc . " http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd";
$loc = $loc . " http://www.cluetrust.com/XML/GPXDATA/1/0 http://www.cluetrust.com/Schemas/gpxdata10.xsd";
$loc = $loc . '"';
printf " %s", $loc;
printf " %s", 'xmlns="http://www.topografix.com/GPX/1/1"';
printf " %s", 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"';
# garmin_ext
printf " %s", 'xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"';
printf " %s", 'xmlns:gpxtrx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"';
printf " %s", 'xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"';
printf " %s", 'xmlns:gpxwpx="http://www.garmin.com/xmlschemas/WaypointExtension/v1"';
# cluetrust_ext
printf " %s", 'xmlns:gpxdata="http://www.cluetrust.com/XML/GPXDATA/1/0"';
# trekbuddy_ext
# printf " %s", 'xmlns:nmea="http://trekbuddy.net/2009/01/gpx/nmea"';
# nmea:course, nmea:speed
printf ">\n";
} # PrintGpxHeader
#==============================================================================
# Print metadata block in gpx
sub PrintGpxMetadata {
# <metadata>
# <name> xsd:string </name> [0..1]
# <desc> xsd:string </desc> [0..1]
# <author> personType </author> [0..1]
# <copyright> copyrightType </copyright> [0..1]
# <link> linkType </link> [0..*]
# <time> xsd:dateTime </time> [0..1]
# <keywords> xsd:string </keywords> [0..1]
# <bounds> boundsType </bounds> [0..1]
# <extensions> extensionsType </extensions> [0..1]
# </metadata>
#
# <author>
# <name> xsd:string </name> [0..*]
# <email id="xsd:string [1]" domain="xsd:string [1]"/> [0..*]
# </author>
printf "%s<metadata>\n", $indent;
printf "%s<name>%s</name>\n", $indent x 2, $g_trackName;
printf "%s<desc>%s</desc>\n", $indent x 2, $g_description;
printf "%s<author>\n", $indent x 2;
printf "%s<name>%s</name>\n", $indent x 4, $g_name;
printf "%s</author>\n", $indent x 2;
printf "%s<link href=\"%s\">\n", $indent x 2, "http://acme.com/fit2gpx.pl";
printf "%s<text>%s</text>\n", $indent x 4, "fit2gpx by Matjaz Rihtar";
printf "%s</link>\n", $indent x 2;
printf "%s<time>%s</time>\n", $indent x 2, $fit->date_string($g_startTime);
printf "%s</metadata>\n", $indent;
} # PrintGpxMetadata
#==============================================================================
# Get 1st altitude from records. If not found, return home altitude.
sub Get1stAlt {
my $timestamp = undef;
my $alt = undef;
foreach (@$records) {
my $k; my $v;
while (($k, $v) = each %$_) {
if ($k eq "timestamp") { $timestamp = $v + $ts_offs; } # + $timeoffs;
elsif ($k eq "altitude" && !defined $alt) { $alt = $v; } # can be invalid
elsif ($k eq "enhanced_altitude") {
if (defined $v) { $alt = $v; } # only if valid
}
}
last; # check only 1st record
}
if (!defined $alt) { $alt = $g_homeAlt; }
return $alt;
} # Get1stAlt
#==============================================================================
# Simple Kalman filtering routines (used as low-pass filter) for smoothing data
sub kalman_init {
my ($state, $q, $r, $p, $initial_value) = @_;
$state->{q} = $q;
$state->{r} = $r;
$state->{p} = $p;
$state->{x} = $initial_value;
} # kalman_init
#------------------------------------------------------------------------------
sub kalman_update {
my ($state, $value) = @_;
my $q = $state->{q};
my $r = $state->{r};
my $p = $state->{p};
my $x = $state->{x};
my $k;
$p = $p + $q;
$k = $p / ($p + $r);
$x = $x + $k * ($value - $x);
$p = (1 - $k) * $p;
$state->{q} = $q;
$state->{r} = $r;
$state->{p} = $p;
$state->{x} = $x;
return $x;
} # kalman_update
#==============================================================================
# Filter altitude data (smoothing sudden jumps in altitude)
# Because of the delay introduced with filter, final data is shifted left by
# 2 positions.
# Displaying the comparison graph is possible, if code at the end is uncommented.
sub FilterAlt {
my $priv_alt = shift; # initial/home altitude
my $k; my $v;
# q = bigger (>4) => more precisely follows the original curve
# smaller (closer to zero) => more smooth, but also very delayed
# r = bigger (>100) => more smooth, some delay, lowered peaks
# smaller (0.1) => exactly follows original curve
# q & r stay the same, p & x are overwritten in each step
# p = same as r
# initial_value = initial/home altitude
kalman_init(\%alt_state, 1, 15, 1, $priv_alt);
my $timestamp;
my $alt; my $altf;
my $times = [];
$orig_alt = [];
$filt_alt = [];
foreach (@$records) {
$timestamp = undef;
$alt = undef;
while (($k, $v) = each %$_) {
if ($k eq "timestamp") { $timestamp = $v + $ts_offs; } # + $timeoffs;
elsif ($k eq "altitude" && !defined $alt) { $alt = $v; } # can be invalid
elsif ($k eq "enhanced_altitude") {
if (defined $v) { $alt = $v; } # only if valid
}
}
if (!defined $alt) { $alt = $priv_alt; }
$altf = kalman_update(\%alt_state, $alt);
push @$times, $timestamp;
push @$orig_alt, $alt;
push @$filt_alt, $altf;
# printf STDERR "alt = %g, altf = %g\n", $alt, $altf;
$priv_alt = $alt;
}
# Fix filtered delay (2 positions, depends on kalman_init parameters)
if (scalar @$filt_alt) {
shift @$filt_alt;
shift @$filt_alt;
push @$filt_alt, $altf;
push @$filt_alt, $altf;
}
# Display graph of original and filtered alt
# my $data = GD::Graph::Data->new([$times, $orig_alt, $filt_alt]) or die GD::Graph::Data->error."\n";
# my $graph = GD::Graph::lines->new(5000,1000) or die GD::Graph::lines->error."\n";
# $graph->set(title => 'Altitude');
# my $gp = $graph->plot($data) or die $graph->error."\n";
# Save graph to file
# open OUT, ">", "alt.png" or die $!."\n";
# binmode OUT;
# print OUT $gp->png();
# close OUT;
} # FilterAlt
#==============================================================================
# Process all track points (records) from fit file
# This routine is called for calculating missing aver/min/max values only!
sub ProcessRecords {
# Initialize arrays
$alts = [];
$hrs = [];
$temps = [];