Guest User

Untitled

a guest
Oct 18th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. require 'yajl'
  2. require 'geokit'
  3. require 'socket'
  4. require 'ruby-units'
  5. require 'json/pure'
  6.  
  7. class GPSPipe
  8. attr_accessor :host, :port
  9.  
  10. def initialize(host='127.0.0.1', port='2947')
  11. @host = host
  12. @port = port
  13. # Hash that stores history for distance calculation
  14. @history = {'TPV' => []} # defaultize the hash
  15. end
  16.  
  17. # Opens a connection to gpsd and streams from it
  18. def stream()
  19. TCPSocket.open(@host, @port) do |socket|
  20. socket.write "?WATCH={\"enable\":true,\"json\":true}"
  21. socket.each_line do |line|
  22. parsed = handle_data(line)
  23. yield parsed if parsed
  24. end
  25. end
  26. end
  27.  
  28. private
  29. def handle_data(data)
  30. data = JSON.parse(data.chomp)
  31. case data["class"]
  32. when "VERSION", "DEVICES", "WATCH"
  33. data
  34. when "SKY"
  35. # TODO
  36. when "TPV"
  37. moved?(data) ? data : nil
  38. else
  39. raise ArgumentError, 'Unknown input: %s' % data
  40. end
  41. end
  42.  
  43. def cleanup_history!
  44. @history.each_value do |value|
  45. raise "History is bogus" if value.length > 4
  46. value.shift if value.length > 3
  47. end
  48. end
  49.  
  50. def has_moved?(data)
  51. # Remove old items from history, append item to history and return the history
  52. cleanup_history!
  53. h = @history['TPV']
  54. h << data
  55.  
  56. # Check that we moved 1m away from history coordinates
  57. minimum_distance = Unit.new("0.2 meters")
  58. now = GeoKit::LatLng.new(h.last['lat'], h.last['lon'])
  59. matches = h[0..-2].select { |test|
  60. previous = GeoKit::LatLng.new(test['lat'], test['lon'])
  61. distance = Unit.new("%s miles" % previous.distance_to(now))
  62.  
  63. distance > minimum_distance
  64. }
  65.  
  66. # Return true if our distance changed compard to *all* items in history
  67. # If we really moved, then we aren't just jumping between 2 coordinates.
  68. matches.length == h.length-1
  69. end
  70. end
  71.  
  72. gpspipe = GPSPipe.new()
  73. gpspipe.stream do |output|
  74. p output
  75. end
Add Comment
Please, Sign In to add comment