-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbart.rb
90 lines (76 loc) · 2.62 KB
/
bart.rb
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
require 'bart_api'
require 'eventmachine'
require_relative 'timetable'
class BartStrategy < TimetableStrategy
class << self
include Configurable
end
def initialize *_
super
@bart = Bart.new
end
def visits_between station, start_time, end_time, limit
return nil if (start_time - Time.now).abs > refresh_time
result = EM::DefaultDeferrable.new
on_estimates = proc do |estimates|
arrivals = transform(estimates).first(2)
if arrivals.count < limit
# If BART didn't provide enough results, ask Timetable for more.
EM::Deferrable.future(super(station,
Time.parse(arrivals.last[0]),
end_time,
limit - arrivals.count),
proc { |tt_arrivals| result.succeed arrivals + tt_arrivals },
result.method(:fail))
else
result.succeed arriavls
end
end
EM::Deferrable.future(estimates_at(station),
on_estimates,
result.method(:fail))
result
end
private
def estimates_at station
EM.defer_block { @bart.estimates.get station }
end
def transform station
station.etd.map do |destination|
# Map Destination objects to timetable-formatted arrival tuples...
destination.arrivals.map { |arrival| tuple_for destination, arrival }
# ...merge the different destionations into one list...
end.flatten(1).sort do |a, b|
# ...sort by arrival time...
a[0] <=> b[0]
# ...and convert times to their string format.
end.each &(method :serialize)
end
# Return a timetable-style (eta, etd, route, headsign) tuple given a
# `Destination` and one of its `Arrival`s.
def tuple_for destination, arrival
arrival_time = Time.now + arrival.minutes.to_i * 60
[arrival_time,
arrival_time,
route_id_for(arrival),
destination.name,
{realtime: true}]
end
# Given an arrival, returns the known route id by comparing the hex color of
# the arrival. Since BART doesn't provide route numbers of its `etd`
# endpoint, we have to look for the right route ourselves.
def route_id_for arrival
@agency.routes.lazy.select { |r| r[:color] == arrival.hexcolor }.first[:short_name]
end
# Return `arrival` with its times converted into the wire string format.
def serialize arrival
arrival[0] = arrival[0].strftime(date_format)
arrival[1] = arrival[1].strftime(date_format)
end
def deserialize arrival
arrival[0]
end
def refresh_time
Bart.configuration.refresh_time
end
end