Skip to content

Instantly share code, notes, and snippets.

@jdiller
Created July 23, 2014 20:13
Show Gist options
  • Save jdiller/3e8e4a84c7af474cde44 to your computer and use it in GitHub Desktop.
Save jdiller/3e8e4a84c7af474cde44 to your computer and use it in GitHub Desktop.
FB streetcar prediction fetching code
require 'net/http'
require 'rexml/document'
lastindex = 0
stops = [
{:route=>"506", :stop=>"8999"},
{:route=>"505", :stop=>"2954"},
{:route=>"506", :stop=>"5094"},
{:route=>"504", :stop=>"14808"},
{:route=>"504", :stop=>"9383"}
]
SCHEDULER.every '10s' do
base_uri = "http://webservices.nextbus.com/service/publicXMLFeed"
params = {
:a => 'ttc',
:command => 'predictions',
:s => stops[lastindex][:stop],
:r => stops[lastindex][:route]
}
lastindex += 1
lastindex = 0 if lastindex == stops.length
begin
uri = URI(base_uri)
uri.query = URI.encode_www_form(params)
resp = Net::HTTP.get_response(uri)
xml_data = resp.body
doc = REXML::Document.new(xml_data)
root = doc.root
route = root.elements["predictions"].attributes['routeTitle']
direction = root.elements["predictions/direction"].attributes['title']
dir_exp = /^(.*)\s\-/
match = dir_exp.match(direction)
direction = match[1] unless match.nil?
times = []
root.elements["predictions/direction"].elements.each do |ele|
seconds = ele.attributes['seconds'].to_i
time_str = Time.at(seconds).gmtime.strftime('%M:%S')
times << {:time => time_str }
end
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
route = "halp!"
direction = "Something went wrong"
times = [0,0,0]
puts e
return
end
send_event('streetcar', {title:route, moreinfo:direction, items:times[0,3]})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment