-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle_data.go
250 lines (218 loc) · 7.06 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
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
package njtapi
import (
"context"
"encoding/xml"
"errors"
"regexp"
"strconv"
"strings"
"time"
)
const (
vehicleDataEndpoint = "getVehicleDataXML"
trainMapEndpoint = "getTrainMapXML"
trainStopsEndpoint = "getTrainStopListXML"
)
var (
ErrTrainNotFound = errors.New("train not found")
trainIDRe = regexp.MustCompile(`(\d+)`)
)
// 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 // Next station the train is stopping at, like "New York" or "Dover".
LatLng *LatLng // Last identified latlng
TrackCircuit string // Track Circuit ID, like "CL-2WAK" or "BC-8251TK".
Stops []StationStop // Stations the train stops at.
}
// Get information about a specific train from the "Map" API endpoint.
//
// The `Train` object returned will not have all the fields set. It will
// typically only have `ID`, `Line`, `Direction`, `LastModified`, `LatLng`,
// and `TrackCircuit`.
func (c *Client) GetTrainMap(ctx context.Context, trainID int) (*Train, error) {
resp, err := c.fetch(ctx, trainMapEndpoint, map[string]string{"trainID": strconv.Itoa(trainID), "station": "-"})
if err != nil {
return nil, err
}
data := struct {
XMLName xml.Name `xml:"Trains"`
Trains []struct {
ID string `xml:"Train_ID"`
Line string `xml:"TrainLine"`
Direction string `xml:"DIRECTION"`
LastModified string `xml:"LAST_MODIFIED"`
Longitude string `xml:"longitude"`
Latitude string `xml:"latitude"`
TrackCircuit string `xml:"TrackCKT"`
} `xml:"Train"`
}{}
err = xml.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
// There is always 1 train returned, even when it doesn't exist.
// We use 'Direction' and 'Line' as good signals for a real train.
t := data.Trains[0]
if t.Direction == "" && t.Line == "" {
return nil, ErrTrainNotFound
}
train := Train{
ID: trainID,
Line: t.Line,
Direction: t.Direction,
TrackCircuit: t.TrackCircuit,
}
train.LastModified, _ = parseTime(t.LastModified)
t.Longitude = strings.TrimSpace(t.Longitude)
t.Latitude = strings.TrimSpace(t.Latitude)
if t.Longitude != "" && t.Latitude != "" {
lat, _ := strconv.ParseFloat(t.Latitude, 64)
lng, _ := strconv.ParseFloat(t.Longitude, 64)
train.LatLng = &LatLng{lat, lng}
}
return &train, nil
}
// Get information about a specific train from the "Stops" API endpoint.
//
// The `Train` object returned will not have all the fields set. It will
// typically only have `ID`, `LastModified`, `LatLng`, and `Stops`.
func (c *Client) GetTrainStops(ctx context.Context, trainID int) (*Train, error) {
resp, err := c.fetch(ctx, trainStopsEndpoint, map[string]string{"trainID": strconv.Itoa(trainID)})
if err != nil {
return nil, err
}
data := struct {
XMLName xml.Name `xml:"Train"`
ID string `xml:"Train_ID"`
Destination string `xml:"DESTINATION"`
GPSTime string `xml:"GPSTIME"`
Longitude string `xml:"GPSLONGITUDE"`
Latitude string `xml:"GPSLATITUDE"`
Stops []struct {
Name string `xml:"NAME"`
Station2Char string `xml:"STATION_2CHAR"`
Time string `xml:"TIME"`
Departed string `xml:"DEPARTED"`
Status string `xml:"STOP_STATUS"`
DepartureTime string `xml:"DEP_TIME"`
Lines []struct {
Code string `xml:"LINE_CODE"`
Name string `xml:"LINE_NAME"`
} `xml:"STOP_LINES>STOP_LINE"`
} `xml:"STOPS>STOP"`
}{}
err = xml.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
if data.ID == "" {
return nil, ErrTrainNotFound
}
train := Train{
ID: trainID,
Stops: []StationStop{},
}
train.LastModified, _ = parseTime(data.GPSTime)
data.Longitude = strings.TrimSpace(data.Longitude)
data.Latitude = strings.TrimSpace(data.Latitude)
if data.Longitude != "" && data.Latitude != "" {
lat, _ := strconv.ParseFloat(data.Latitude, 64)
lng, _ := strconv.ParseFloat(data.Longitude, 64)
train.LatLng = &LatLng{lat, lng}
}
for _, s := range data.Stops {
stop := StationStop{
Name: s.Name,
Departed: (s.Departed == "YES"),
}
stop.Time, _ = parseTime(s.Time)
stop.DepartureTime, _ = parseTime(s.DepartureTime)
if len(s.Lines) > 0 {
stop.Lines = make([]Line, len(s.Lines))
for i, l := range s.Lines {
stop.Lines[i] = Line{Name: l.Name}
}
}
train.Stops = append(train.Stops, stop)
}
return &train, nil
}
// VehicleData returns up the most recent information about all "active" 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 string `xml:"LONGITUDE"`
Latitude string `xml:"LATITUDE"`
TrackCircuit string `xml:"ICS_TRACK_CKT"`
} `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 {
// Use a Regex to extract the numbers from the ID.
// Some trains have an "a" (amtrak suffix). Others
// randomly have leading or trailing ".".
//
// https://github.com/bamnet/njtapi/issues/7
idM := trainIDRe.FindStringSubmatch(d.ID)
d.ID = idM[1]
id, err := strconv.Atoi(d.ID)
if err != nil {
return nil, err
}
// Sometimes the lat lng fields contain " ".
lat, _ := parseDegrees(d.Latitude)
lng, _ := parseDegrees(d.Longitude)
trains[i] = Train{
ID: id,
Line: d.Line,
Direction: d.Direction,
SecondsLate: time.Duration(d.SecondsLate) * time.Second,
NextStop: strings.TrimSpace(d.NextStop),
LatLng: &LatLng{lat, lng},
TrackCircuit: strings.TrimSpace(d.TrackCircuit),
}
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
}