-
Notifications
You must be signed in to change notification settings - Fork 0
/
vehicle_data.go
96 lines (83 loc) · 2.59 KB
/
vehicle_data.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
package njtapi
import (
"context"
"encoding/xml"
"strconv"
"strings"
"time"
)
const vehicleDataEndpoint = "getVehicleDataXML"
// A Train summarizes the latest information about a train.
type Train struct {
ID int // Train number
Line string // Train line
Direction string // Eastbound or Westbound
LastModified time.Time // ???
ScheduledDepartureTime time.Time // ???
SecondsLate time.Duration // Train delay
NextStop string // ???
LatLng *LatLng // Last identified latlng
}
// VehicleData returns up the most recent information about trains.
func (c *Client) VehicleData(ctx context.Context) ([]Train, error) {
resp, err := c.fetch(ctx, vehicleDataEndpoint, nil)
if err != nil {
return nil, err
}
data := struct {
XMLName xml.Name `xml:"TRAINS"`
Trains []struct {
ID string `xml:"ID"`
Line string `xml:"TRAIN_LINE"`
Direction string `xml:"DIRECTION"`
LastModified string `xml:"LAST_MODIFIED"`
ScheduledDepartureTime string `xml:"SCHED_DEP_TIME"`
SecondsLate int `xml:"SEC_LATE"`
NextStop string `xml:"NEXT_STOP"`
Longitude float64 `xml:"LONGITUDE"`
Latitude float64 `xml:"LATITUDE"`
} `xml:"TRAIN"`
}{}
err = xml.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
trains := make([]Train, len(data.Trains))
for i, d := range data.Trains {
// Remove any "a" (amtrak) suffix from the ID.
d.ID = strings.TrimSuffix(d.ID, "a")
id, err := strconv.Atoi(d.ID)
if err != nil {
return nil, err
}
trains[i] = Train{
ID: id,
Line: d.Line,
Direction: d.Direction,
SecondsLate: time.Duration(d.SecondsLate) * time.Second,
NextStop: d.NextStop,
LatLng: &LatLng{d.Latitude, d.Longitude},
}
trains[i].LastModified, _ = parseTime(d.LastModified)
trains[i].ScheduledDepartureTime, _ = parseTime(d.ScheduledDepartureTime)
}
return removeDupTrains(trains), nil
}
// removeDupTrains ensures there is only 1 train per ID in the array.
// If duplicates are found, the train with the most recent LastModified time is kept.
func removeDupTrains(trains []Train) []Train {
ts := map[int]Train{}
for _, t := range trains {
if val, ok := ts[t.ID]; !ok || val.LastModified.Before(t.LastModified) {
ts[t.ID] = t
}
}
if len(ts) == len(trains) {
return trains
}
unique := []Train{}
for _, t := range ts {
unique = append(unique, t)
}
return unique
}