public_transport_agent.rb 5.6 KB

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