public_transport_agent.rb 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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/adaAgency.jsp](http://www.nextbus.com/predictor/adaAgency.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/adaDirection.jsp?a=**sf-muni**](http://www.nextbus.com/predictor/adaDirection.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.
  15. Select your destination and lets use the n-judah route. The link should be [http://www.nextbus.com/predictor/adaStop.jsp?a=sf-muni&r=N](http://www.nextbus.com/predictor/adaStop.jsp?a=sf-muni&r=N) Once you find it, copy the part of the URL after `r=`.
  16. To find the tags for the sf-muni system, for the N route, visit this URL:
  17. [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)
  18. 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,
  19. agency: "sf-muni"
  20. stops: ["N|5221", "N|5215"]
  21. Remember to pick the appropriate stop, which will have different tags for in-bound and out-bound.
  22. This Agent will generate predictions by requesting a URL similar to the following:
  23. [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)
  24. 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.
  25. alert_window_in_minutes: 5
  26. MD
  27. event_description <<-MD
  28. Events look like this:
  29. { "routeTitle":"N-Judah",
  30. "stopTag":"5215",
  31. "prediction":
  32. {"epochTime":"1389622846689",
  33. "seconds":"3454","minutes":"57","isDeparture":"false",
  34. "affectedByLayover":"true","dirTag":"N__OB4KJU","vehicle":"1489",
  35. "block":"9709","tripTag":"5840086"
  36. }
  37. }
  38. MD
  39. def check_url
  40. stop_query = URI.encode(interpolated["stops"].collect{|a| "&stops=#{a}"}.join)
  41. "http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=#{interpolated["agency"]}#{stop_query}"
  42. end
  43. def stops
  44. interpolated["stops"].collect{|a| a.split("|").last}
  45. end
  46. def check
  47. hydra = Typhoeus::Hydra.new
  48. request = Typhoeus::Request.new(check_url, :followlocation => true)
  49. request.on_success do |response|
  50. page = Nokogiri::XML response.body
  51. predictions = page.css("//prediction")
  52. predictions.each do |pr|
  53. parent = pr.parent.parent
  54. vals = {"routeTitle" => parent["routeTitle"], "stopTag" => parent["stopTag"]}
  55. if pr["minutes"] && pr["minutes"].to_i < interpolated["alert_window_in_minutes"].to_i
  56. vals = vals.merge Hash.from_xml(pr.to_xml)
  57. if not_already_in_memory?(vals)
  58. create_event(:payload => vals)
  59. log "creating event..."
  60. update_memory(vals)
  61. else
  62. log "not creating event since already in memory"
  63. end
  64. end
  65. end
  66. end
  67. hydra.queue request
  68. hydra.run
  69. end
  70. def update_memory(vals)
  71. add_to_memory(vals)
  72. cleanup_old_memory
  73. end
  74. def cleanup_old_memory
  75. self.memory["existing_routes"] ||= []
  76. self.memory["existing_routes"].reject!{|h| h["currentTime"].to_time <= (Time.now - 2.hours)}
  77. end
  78. def add_to_memory(vals)
  79. self.memory["existing_routes"] ||= []
  80. self.memory["existing_routes"] << {"stopTag" => vals["stopTag"], "tripTag" => vals["prediction"]["tripTag"], "epochTime" => vals["prediction"]["epochTime"], "currentTime" => Time.now}
  81. end
  82. def not_already_in_memory?(vals)
  83. m = self.memory["existing_routes"] || []
  84. m.select{|h| h['stopTag'] == vals["stopTag"] &&
  85. h['tripTag'] == vals["prediction"]["tripTag"] &&
  86. h['epochTime'] == vals["prediction"]["epochTime"]
  87. }.count == 0
  88. end
  89. def default_options
  90. {
  91. agency: "sf-muni",
  92. stops: ["N|5221", "N|5215"],
  93. alert_window_in_minutes: 5
  94. }
  95. end
  96. def validate_options
  97. errors.add(:base, 'agency is required') unless options['agency'].present?
  98. errors.add(:base, 'alert_window_in_minutes is required') unless options['alert_window_in_minutes'].present?
  99. errors.add(:base, 'stops are required') unless options['stops'].present?
  100. end
  101. def working?
  102. event_created_within?(2) && !recent_error_logs?
  103. end
  104. end
  105. end