-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
119 lines (105 loc) · 2.27 KB
/
parser.go
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
package hitrack2gpx
import (
"bufio"
"log"
"math"
"strconv"
"strings"
"time"
)
type heartRate struct {
k int
v int
}
type position struct {
lat float32
lon float32
k int
alt float32
t float32
}
type TrackLine map[string]string
type TimedLine map[string]TrackLine
type HuaweiTrack map[int]TimedLine
/*
ParseTrackDump gets a dump as a test, loops over lines and, for each line, identifies the
type and populates a map
*/
func ParseTrackDump(trackDump string) *HuaweiTrack {
track := HuaweiTrack{}
scanner := bufio.NewScanner(strings.NewReader(trackDump))
for scanner.Scan() {
timestamp, recordType, payload, err := parseLine(scanner.Text())
if err != nil {
log.Fatal(err)
}
if _, ok := track[timestamp]; !ok {
track[timestamp] = TimedLine{}
}
track[timestamp][recordType] = payload
}
/* [
s-r (k, v sempre 0) cadence
rs (k, v)
lbs (alt, t, lon, lat, k) location
p-m (k, v) ritmo medio al km (in secondi)
b-p-m (k, v)
h-r (k, v) heart-rate
] */
return &track
}
func parseLine(line string) (int, string, TrackLine, error) {
payload := TrackLine{}
var tp string
var timestamp int
var err error
for _, value := range strings.Split(line, ";") {
if value != "" {
r := strings.Split(value, "=")
if r[0] == "tp" {
tp = r[1]
}
v := r[1]
if isTimestamp(r[0], tp) {
v = fixTimestamp(v)
timestamp, err = strconv.Atoi(v)
if err != nil {
return 0, "", TrackLine{}, err
}
}
payload[r[0]] = v
// fmt.Println(r[0])
}
}
if timestamp == 0 {
return 0, "", TrackLine{}, err
}
return timestamp, tp, payload, nil
}
func isTimestamp(value, lineType string) bool {
return (lineType == "h-r" && value == "k") || (lineType == "lbs" && value == "t")
}
// All timestamps must have 9 digits
func fixTimestamp(timestampStr string) string {
f, err := strconv.ParseFloat(timestampStr, 64)
if err != nil {
log.Fatal(err)
}
t := int(f)
oom := int(math.Log10(float64(t)))
divisor := 1
if oom > 9 {
divisor = int(math.Pow(10, float64(oom-9)))
} else if oom < 9 {
divisor = int(math.Pow(0.1, float64(9-oom)))
}
t = int(t / divisor)
return strconv.Itoa(t)
}
func parseTimestamp(timestamp string) time.Time {
t, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
log.Fatal(err)
}
return time.Unix(t, 0)
}