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