1
0

public_transport_agent.rb 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. require 'date'
  2. require 'cgi'
  3. module Agents
  4. class PublicTransportAgent < Agent
  5. cannot_receive_events!
  6. default_schedule "every_2m"
  7. description <<-MD
  8. The Public Transport Request Agent generates Events based on NextBus GPS transit predictions.
  9. Specify the following user settings:
  10. * agency (string)
  11. * stops (array)
  12. * alert_window_in_minutes (integer)
  13. First, select an agency by visiting [http://www.nextbus.com/predictor/agencySelector.jsp](http://www.nextbus.com/predictor/agencySelector.jsp) and finding your transit system. Once you find it, copy the part of the URL after `?a=`. For example, for the San Francisco MUNI system, you would end up on [http://www.nextbus.com/predictor/stopSelector.jsp?a=**sf-muni**](http://www.nextbus.com/predictor/stopSelector.jsp?a=sf-muni) and copy "sf-muni". Put that into this Agent's agency setting.
  14. Next, find the stop tags that you care about. To find the tags for the sf-muni system, for the N route, visit this URL:
  15. [http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=**N**](http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=N)
  16. The tags are listed as tag="1234". Copy that number and add the route before it, separated by a pipe '&#124;' symbol. Once you have one or more tags from that page, add them to this Agent's stop list. E.g,
  17. agency: "sf-muni"
  18. stops: ["N|5221", "N|5215"]
  19. Remember to pick the appropriate stop, which will have different tags for in-bound and out-bound.
  20. This Agent will generate predictions by requesting a URL similar to the following:
  21. [http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=sf-muni&stops=N&#124;5221&stops=N&#124;5215](http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=sf-muni&stops=N&#124;5221&stops=N&#124;5215)
  22. Finally, set the arrival window that you're interested in. E.g., 5 minutes. Events will be created by the agent anytime a new train or bus comes into that time window.
  23. alert_window_in_minutes: 5
  24. MD
  25. event_description <<-MD
  26. Events look like this:
  27. { "routeTitle":"N-Judah",
  28. "stopTag":"5215",
  29. "prediction":
  30. {"epochTime":"1389622846689",
  31. "seconds":"3454","minutes":"57","isDeparture":"false",
  32. "affectedByLayover":"true","dirTag":"N__OB4KJU","vehicle":"1489",
  33. "block":"9709","tripTag":"5840086"
  34. }
  35. }
  36. MD
  37. def check_url
  38. stop_query = URI.encode(interpolated["stops"].collect{|a| "&stops=#{a}"}.join)
  39. "http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=#{interpolated["agency"]}#{stop_query}"
  40. end
  41. def stops
  42. interpolated["stops"].collect{|a| a.split("|").last}
  43. end
  44. def check
  45. hydra = Typhoeus::Hydra.new
  46. request = Typhoeus::Request.new(check_url, :followlocation => true)
  47. request.on_success do |response|
  48. page = Nokogiri::XML response.body
  49. predictions = page.css("//prediction")
  50. predictions.each do |pr|
  51. parent = pr.parent.parent
  52. vals = {"routeTitle" => parent["routeTitle"], "stopTag" => parent["stopTag"]}
  53. if pr["minutes"] && pr["minutes"].to_i < interpolated["alert_window_in_minutes"].to_i
  54. vals = vals.merge Hash.from_xml(pr.to_xml)
  55. if not_already_in_memory?(vals)
  56. create_event(:payload => vals)
  57. log "creating event..."
  58. update_memory(vals)
  59. else
  60. log "not creating event since already in memory"
  61. end
  62. end
  63. end
  64. end
  65. hydra.queue request
  66. hydra.run
  67. end
  68. def update_memory(vals)
  69. add_to_memory(vals)
  70. cleanup_old_memory
  71. end
  72. def cleanup_old_memory
  73. self.memory["existing_routes"] ||= []
  74. self.memory["existing_routes"].reject!{|h| h["currentTime"].to_time <= (Time.now - 2.hours)}
  75. end
  76. def add_to_memory(vals)
  77. self.memory["existing_routes"] ||= []
  78. self.memory["existing_routes"] << {"stopTag" => vals["stopTag"], "tripTag" => vals["prediction"]["tripTag"], "epochTime" => vals["prediction"]["epochTime"], "currentTime" => Time.now}
  79. end
  80. def not_already_in_memory?(vals)
  81. m = self.memory["existing_routes"] || []
  82. m.select{|h| h['stopTag'] == vals["stopTag"] &&
  83. h['tripTag'] == vals["prediction"]["tripTag"] &&
  84. h['epochTime'] == vals["prediction"]["epochTime"]
  85. }.count == 0
  86. end
  87. def default_options
  88. {
  89. agency: "sf-muni",
  90. stops: ["N|5221", "N|5215"],
  91. alert_window_in_minutes: 5
  92. }
  93. end
  94. def validate_options
  95. errors.add(:base, 'agency is required') unless options['agency'].present?
  96. errors.add(:base, 'alert_window_in_minutes is required') unless options['alert_window_in_minutes'].present?
  97. errors.add(:base, 'stops are required') unless options['stops'].present?
  98. end
  99. def working?
  100. event_created_within?(2) && !recent_error_logs?
  101. end
  102. end
  103. end