route_guide_server.rb 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env ruby
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2015 gRPC authors.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # Sample app that connects to a Route Guide service.
  17. #
  18. # Usage: $ path/to/route_guide_server.rb path/to/route_guide_db.json &
  19. this_dir = File.expand_path(File.dirname(__FILE__))
  20. lib_dir = File.join(File.dirname(this_dir), 'lib')
  21. $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
  22. require 'grpc'
  23. require 'multi_json'
  24. require 'route_guide_services_pb'
  25. include Routeguide
  26. COORD_FACTOR = 1e7
  27. RADIUS = 637_100
  28. # Determines the distance between two points.
  29. # The formula is based on http://mathforum.org/library/drmath/view/51879.html.
  30. def calculate_distance(point_a, point_b)
  31. to_radians = proc { |x| x * Math::PI / 180 }
  32. lat_a = to_radians.call(point_a.latitude / COORD_FACTOR)
  33. lat_b = to_radians.call(point_b.latitude / COORD_FACTOR)
  34. lon_a = to_radians.call(point_a.longitude / COORD_FACTOR)
  35. lon_b = to_radians.call(point_b.longitude / COORD_FACTOR)
  36. delta_lat = lat_a - lat_b
  37. delta_lon = lon_a - lon_b
  38. a = Math.sin(delta_lat / 2)**2 +
  39. Math.cos(lat_a) * Math.cos(lat_b) +
  40. Math.sin(delta_lon / 2)**2
  41. (2 * RADIUS * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))).to_i
  42. end
  43. # RectangleEnum provides an Enumerator of the points in a feature_db within a
  44. # given Rectangle.
  45. class RectangleEnum
  46. # @param [Hash] feature_db
  47. # @param [Rectangle] bounds
  48. def initialize(feature_db, bounds)
  49. @feature_db = feature_db
  50. @bounds = bounds
  51. lats = [@bounds.lo.latitude, @bounds.hi.latitude]
  52. longs = [@bounds.lo.longitude, @bounds.hi.longitude]
  53. @lo_lat, @hi_lat = lats.min, lats.max
  54. @lo_long, @hi_long = longs.min, longs.max
  55. end
  56. # in? determines if location lies within the bounds of this instances
  57. # Rectangle.
  58. def in?(location)
  59. location['longitude'] >= @lo_long &&
  60. location['longitude'] <= @hi_long &&
  61. location['latitude'] >= @lo_lat &&
  62. location['latitude'] <= @hi_lat
  63. end
  64. # each yields the features in the instances feature_db that lie within the
  65. # instance rectangle.
  66. def each
  67. return enum_for(:each) unless block_given?
  68. @feature_db.each_pair do |location, name|
  69. next unless in?(location)
  70. next if name.nil? || name == ''
  71. pt = Point.new(
  72. Hash[location.each_pair.map { |k, v| [k.to_sym, v] }])
  73. yield Feature.new(location: pt, name: name)
  74. end
  75. end
  76. end
  77. # ServerImpl provides an implementation of the RouteGuide service.
  78. class ServerImpl < RouteGuide::Service
  79. # @param [Hash] feature_db {location => name}
  80. def initialize(feature_db)
  81. @feature_db = feature_db
  82. @received_notes = Hash.new { |h, k| h[k] = [] }
  83. end
  84. def get_feature(point, _call)
  85. name = @feature_db[{
  86. 'longitude' => point.longitude,
  87. 'latitude' => point.latitude }] || ''
  88. Feature.new(location: point, name: name)
  89. end
  90. def list_features(rectangle, _call)
  91. RectangleEnum.new(@feature_db, rectangle).each
  92. end
  93. def record_route(call)
  94. started, elapsed_time = 0, 0
  95. distance, count, features, last = 0, 0, 0, nil
  96. call.each_remote_read do |point|
  97. count += 1
  98. name = @feature_db[{
  99. 'longitude' => point.longitude,
  100. 'latitude' => point.latitude }] || ''
  101. features += 1 unless name == ''
  102. if last.nil?
  103. last = point
  104. started = Time.now.to_i
  105. next
  106. end
  107. elapsed_time = Time.now.to_i - started
  108. distance += calculate_distance(point, last)
  109. last = point
  110. end
  111. RouteSummary.new(point_count: count,
  112. feature_count: features,
  113. distance: distance,
  114. elapsed_time: elapsed_time)
  115. end
  116. def route_chat(notes)
  117. RouteChatEnumerator.new(notes, @received_notes).each_item
  118. end
  119. end
  120. class RouteChatEnumerator
  121. def initialize(notes, received_notes)
  122. @notes = notes
  123. @received_notes = received_notes
  124. end
  125. def each_item
  126. return enum_for(:each_item) unless block_given?
  127. begin
  128. @notes.each do |n|
  129. key = {
  130. 'latitude' => n.location.latitude,
  131. 'longitude' => n.location.longitude
  132. }
  133. earlier_msgs = @received_notes[key]
  134. @received_notes[key] << n.message
  135. # send back the earlier messages at this point
  136. earlier_msgs.each do |r|
  137. yield RouteNote.new(location: n.location, message: r)
  138. end
  139. end
  140. rescue StandardError => e
  141. fail e # signal completion via an error
  142. end
  143. end
  144. end
  145. def main
  146. if ARGV.length == 0
  147. fail 'Please specify the path to the route_guide json database'
  148. end
  149. raw_data = []
  150. File.open(ARGV[0]) do |f|
  151. raw_data = MultiJson.load(f.read)
  152. end
  153. feature_db = Hash[raw_data.map { |x| [x['location'], x['name']] }]
  154. port = '0.0.0.0:50051'
  155. s = GRPC::RpcServer.new
  156. s.add_http2_port(port, :this_port_is_insecure)
  157. GRPC.logger.info("... running insecurely on #{port}")
  158. s.handle(ServerImpl.new(feature_db))
  159. # Runs the server with SIGHUP, SIGINT and SIGQUIT signal handlers to
  160. # gracefully shutdown.
  161. # User could also choose to run server via call to run_till_terminated
  162. s.run_till_terminated_or_interrupted([1, 'int', 'SIGQUIT'])
  163. end
  164. main