781642747f3f24077c6a88627284e30188c3154b
[platform/upstream/grpc.git] / examples / cpp / route_guide / route_guide_server.cc
1 /*
2  *
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  *
17  */
18
19 #include <algorithm>
20 #include <chrono>
21 #include <cmath>
22 #include <iostream>
23 #include <memory>
24 #include <string>
25
26 #include <grpc/grpc.h>
27 #include <grpcpp/server.h>
28 #include <grpcpp/server_builder.h>
29 #include <grpcpp/server_context.h>
30 #include <grpcpp/security/server_credentials.h>
31 #include "helper.h"
32 #ifdef BAZEL_BUILD
33 #include "examples/protos/route_guide.grpc.pb.h"
34 #else
35 #include "route_guide.grpc.pb.h"
36 #endif
37
38 using grpc::Server;
39 using grpc::ServerBuilder;
40 using grpc::ServerContext;
41 using grpc::ServerReader;
42 using grpc::ServerReaderWriter;
43 using grpc::ServerWriter;
44 using grpc::Status;
45 using routeguide::Point;
46 using routeguide::Feature;
47 using routeguide::Rectangle;
48 using routeguide::RouteSummary;
49 using routeguide::RouteNote;
50 using routeguide::RouteGuide;
51 using std::chrono::system_clock;
52
53
54 float ConvertToRadians(float num) {
55   return num * 3.1415926 /180;
56 }
57
58 // The formula is based on http://mathforum.org/library/drmath/view/51879.html
59 float GetDistance(const Point& start, const Point& end) {
60   const float kCoordFactor = 10000000.0;
61   float lat_1 = start.latitude() / kCoordFactor;
62   float lat_2 = end.latitude() / kCoordFactor;
63   float lon_1 = start.longitude() / kCoordFactor;
64   float lon_2 = end.longitude() / kCoordFactor;
65   float lat_rad_1 = ConvertToRadians(lat_1);
66   float lat_rad_2 = ConvertToRadians(lat_2);
67   float delta_lat_rad = ConvertToRadians(lat_2-lat_1);
68   float delta_lon_rad = ConvertToRadians(lon_2-lon_1);
69
70   float a = pow(sin(delta_lat_rad/2), 2) + cos(lat_rad_1) * cos(lat_rad_2) *
71             pow(sin(delta_lon_rad/2), 2);
72   float c = 2 * atan2(sqrt(a), sqrt(1-a));
73   int R = 6371000; // metres
74
75   return R * c;
76 }
77
78 std::string GetFeatureName(const Point& point,
79                            const std::vector<Feature>& feature_list) {
80   for (const Feature& f : feature_list) {
81     if (f.location().latitude() == point.latitude() &&
82         f.location().longitude() == point.longitude()) {
83       return f.name();
84     }
85   }
86   return "";
87 }
88
89 class RouteGuideImpl final : public RouteGuide::Service {
90  public:
91   explicit RouteGuideImpl(const std::string& db) {
92     routeguide::ParseDb(db, &feature_list_);
93   }
94
95   Status GetFeature(ServerContext* context, const Point* point,
96                     Feature* feature) override {
97     feature->set_name(GetFeatureName(*point, feature_list_));
98     feature->mutable_location()->CopyFrom(*point);
99     return Status::OK;
100   }
101
102   Status ListFeatures(ServerContext* context,
103                       const routeguide::Rectangle* rectangle,
104                       ServerWriter<Feature>* writer) override {
105     auto lo = rectangle->lo();
106     auto hi = rectangle->hi();
107     long left = (std::min)(lo.longitude(), hi.longitude());
108     long right = (std::max)(lo.longitude(), hi.longitude());
109     long top = (std::max)(lo.latitude(), hi.latitude());
110     long bottom = (std::min)(lo.latitude(), hi.latitude());
111     for (const Feature& f : feature_list_) {
112       if (f.location().longitude() >= left &&
113           f.location().longitude() <= right &&
114           f.location().latitude() >= bottom &&
115           f.location().latitude() <= top) {
116         writer->Write(f);
117       }
118     }
119     return Status::OK;
120   }
121
122   Status RecordRoute(ServerContext* context, ServerReader<Point>* reader,
123                      RouteSummary* summary) override {
124     Point point;
125     int point_count = 0;
126     int feature_count = 0;
127     float distance = 0.0;
128     Point previous;
129
130     system_clock::time_point start_time = system_clock::now();
131     while (reader->Read(&point)) {
132       point_count++;
133       if (!GetFeatureName(point, feature_list_).empty()) {
134         feature_count++;
135       }
136       if (point_count != 1) {
137         distance += GetDistance(previous, point);
138       }
139       previous = point;
140     }
141     system_clock::time_point end_time = system_clock::now();
142     summary->set_point_count(point_count);
143     summary->set_feature_count(feature_count);
144     summary->set_distance(static_cast<long>(distance));
145     auto secs = std::chrono::duration_cast<std::chrono::seconds>(
146         end_time - start_time);
147     summary->set_elapsed_time(secs.count());
148
149     return Status::OK;
150   }
151
152   Status RouteChat(ServerContext* context,
153                    ServerReaderWriter<RouteNote, RouteNote>* stream) override {
154     std::vector<RouteNote> received_notes;
155     RouteNote note;
156     while (stream->Read(&note)) {
157       for (const RouteNote& n : received_notes) {
158         if (n.location().latitude() == note.location().latitude() &&
159             n.location().longitude() == note.location().longitude()) {
160           stream->Write(n);
161         }
162       }
163       received_notes.push_back(note);
164     }
165
166     return Status::OK;
167   }
168
169  private:
170
171   std::vector<Feature> feature_list_;
172 };
173
174 void RunServer(const std::string& db_path) {
175   std::string server_address("0.0.0.0:50051");
176   RouteGuideImpl service(db_path);
177
178   ServerBuilder builder;
179   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
180   builder.RegisterService(&service);
181   std::unique_ptr<Server> server(builder.BuildAndStart());
182   std::cout << "Server listening on " << server_address << std::endl;
183   server->Wait();
184 }
185
186 int main(int argc, char** argv) {
187   // Expect only arg: --db_path=path/to/route_guide_db.json.
188   std::string db = routeguide::GetDbFileContent(argc, argv);
189   RunServer(db);
190
191   return 0;
192 }