• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2021 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 <grpc/grpc.h>
20 #include <grpcpp/alarm.h>
21 #include <grpcpp/channel.h>
22 #include <grpcpp/client_context.h>
23 #include <grpcpp/create_channel.h>
24 #include <grpcpp/security/credentials.h>
25 
26 #include <chrono>
27 #include <condition_variable>
28 #include <iostream>
29 #include <memory>
30 #include <mutex>
31 #include <random>
32 #include <string>
33 #include <thread>
34 
35 #include "helper.h"
36 #ifdef BAZEL_BUILD
37 #include "examples/protos/route_guide.grpc.pb.h"
38 #else
39 #include "route_guide.grpc.pb.h"
40 #endif
41 
42 using grpc::Channel;
43 using grpc::ClientContext;
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 
MakePoint(long latitude,long longitude)52 Point MakePoint(long latitude, long longitude) {
53   Point p;
54   p.set_latitude(latitude);
55   p.set_longitude(longitude);
56   return p;
57 }
58 
MakeFeature(const std::string & name,long latitude,long longitude)59 Feature MakeFeature(const std::string& name, long latitude, long longitude) {
60   Feature f;
61   f.set_name(name);
62   f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
63   return f;
64 }
65 
MakeRouteNote(const std::string & message,long latitude,long longitude)66 RouteNote MakeRouteNote(const std::string& message, long latitude,
67                         long longitude) {
68   RouteNote n;
69   n.set_message(message);
70   n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
71   return n;
72 }
73 
74 class RouteGuideClient {
75  public:
RouteGuideClient(std::shared_ptr<Channel> channel,const std::string & db)76   RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
77       : stub_(RouteGuide::NewStub(channel)) {
78     routeguide::ParseDb(db, &feature_list_);
79   }
80 
GetFeature()81   void GetFeature() {
82     Point point;
83     Feature feature;
84     point = MakePoint(409146138, -746188906);
85     GetOneFeature(point, &feature);
86     point = MakePoint(0, 0);
87     GetOneFeature(point, &feature);
88   }
89 
ListFeatures()90   void ListFeatures() {
91     routeguide::Rectangle rect;
92     Feature feature;
93 
94     rect.mutable_lo()->set_latitude(400000000);
95     rect.mutable_lo()->set_longitude(-750000000);
96     rect.mutable_hi()->set_latitude(420000000);
97     rect.mutable_hi()->set_longitude(-730000000);
98     std::cout << "Looking for features between 40, -75 and 42, -73"
99               << std::endl;
100 
101     class Reader : public grpc::ClientReadReactor<Feature> {
102      public:
103       Reader(RouteGuide::Stub* stub, float coord_factor,
104              const routeguide::Rectangle& rect)
105           : coord_factor_(coord_factor) {
106         stub->async()->ListFeatures(&context_, &rect, this);
107         StartRead(&feature_);
108         StartCall();
109       }
110       void OnReadDone(bool ok) override {
111         if (ok) {
112           std::cout << "Found feature called " << feature_.name() << " at "
113                     << feature_.location().latitude() / coord_factor_ << ", "
114                     << feature_.location().longitude() / coord_factor_
115                     << std::endl;
116           StartRead(&feature_);
117         }
118       }
119       void OnDone(const Status& s) override {
120         std::unique_lock<std::mutex> l(mu_);
121         status_ = s;
122         done_ = true;
123         cv_.notify_one();
124       }
125       Status Await() {
126         std::unique_lock<std::mutex> l(mu_);
127         cv_.wait(l, [this] { return done_; });
128         return std::move(status_);
129       }
130 
131      private:
132       ClientContext context_;
133       float coord_factor_;
134       Feature feature_;
135       std::mutex mu_;
136       std::condition_variable cv_;
137       Status status_;
138       bool done_ = false;
139     };
140     Reader reader(stub_.get(), kCoordFactor_, rect);
141     Status status = reader.Await();
142     if (status.ok()) {
143       std::cout << "ListFeatures rpc succeeded." << std::endl;
144     } else {
145       std::cout << "ListFeatures rpc failed." << std::endl;
146     }
147   }
148 
RecordRoute()149   void RecordRoute() {
150     class Recorder : public grpc::ClientWriteReactor<Point> {
151      public:
152       Recorder(RouteGuide::Stub* stub, float coord_factor,
153                const std::vector<Feature>* feature_list)
154           : coord_factor_(coord_factor),
155             feature_list_(feature_list),
156             generator_(
157                 std::chrono::system_clock::now().time_since_epoch().count()),
158             feature_distribution_(0, feature_list->size() - 1),
159             delay_distribution_(500, 1500) {
160         stub->async()->RecordRoute(&context_, &stats_, this);
161         // Use a hold since some StartWrites are invoked indirectly from a
162         // delayed lambda in OnWriteDone rather than directly from the reaction
163         // itself
164         AddHold();
165         NextWrite();
166         StartCall();
167       }
168       void OnWriteDone(bool ok) override {
169         // Delay and then do the next write or WritesDone
170         alarm_.Set(
171             std::chrono::system_clock::now() +
172                 std::chrono::milliseconds(delay_distribution_(generator_)),
173             [this](bool /*ok*/) { NextWrite(); });
174       }
175       void OnDone(const Status& s) override {
176         std::unique_lock<std::mutex> l(mu_);
177         status_ = s;
178         done_ = true;
179         cv_.notify_one();
180       }
181       Status Await(RouteSummary* stats) {
182         std::unique_lock<std::mutex> l(mu_);
183         cv_.wait(l, [this] { return done_; });
184         *stats = stats_;
185         return std::move(status_);
186       }
187 
188      private:
189       void NextWrite() {
190         if (points_remaining_ != 0) {
191           const Feature& f =
192               (*feature_list_)[feature_distribution_(generator_)];
193           std::cout << "Visiting point "
194                     << f.location().latitude() / coord_factor_ << ", "
195                     << f.location().longitude() / coord_factor_ << std::endl;
196           StartWrite(&f.location());
197           points_remaining_--;
198         } else {
199           StartWritesDone();
200           RemoveHold();
201         }
202       }
203       ClientContext context_;
204       float coord_factor_;
205       int points_remaining_ = 10;
206       Point point_;
207       RouteSummary stats_;
208       const std::vector<Feature>* feature_list_;
209       std::default_random_engine generator_;
210       std::uniform_int_distribution<int> feature_distribution_;
211       std::uniform_int_distribution<int> delay_distribution_;
212       grpc::Alarm alarm_;
213       std::mutex mu_;
214       std::condition_variable cv_;
215       Status status_;
216       bool done_ = false;
217     };
218     Recorder recorder(stub_.get(), kCoordFactor_, &feature_list_);
219     RouteSummary stats;
220     Status status = recorder.Await(&stats);
221     if (status.ok()) {
222       std::cout << "Finished trip with " << stats.point_count() << " points\n"
223                 << "Passed " << stats.feature_count() << " features\n"
224                 << "Travelled " << stats.distance() << " meters\n"
225                 << "It took " << stats.elapsed_time() << " seconds"
226                 << std::endl;
227     } else {
228       std::cout << "RecordRoute rpc failed." << std::endl;
229     }
230   }
231 
RouteChat()232   void RouteChat() {
233     class Chatter : public grpc::ClientBidiReactor<RouteNote, RouteNote> {
234      public:
235       explicit Chatter(RouteGuide::Stub* stub)
236           : notes_{MakeRouteNote("First message", 0, 0),
237                    MakeRouteNote("Second message", 0, 1),
238                    MakeRouteNote("Third message", 1, 0),
239                    MakeRouteNote("Fourth message", 0, 0)},
240             notes_iterator_(notes_.begin()) {
241         stub->async()->RouteChat(&context_, this);
242         NextWrite();
243         StartRead(&server_note_);
244         StartCall();
245       }
246       void OnWriteDone(bool ok) override {
247         if (ok) {
248           NextWrite();
249         }
250       }
251       void OnReadDone(bool ok) override {
252         if (ok) {
253           std::cout << "Got message " << server_note_.message() << " at "
254                     << server_note_.location().latitude() << ", "
255                     << server_note_.location().longitude() << std::endl;
256           StartRead(&server_note_);
257         }
258       }
259       void OnDone(const Status& s) override {
260         std::unique_lock<std::mutex> l(mu_);
261         status_ = s;
262         done_ = true;
263         cv_.notify_one();
264       }
265       Status Await() {
266         std::unique_lock<std::mutex> l(mu_);
267         cv_.wait(l, [this] { return done_; });
268         return std::move(status_);
269       }
270 
271      private:
272       void NextWrite() {
273         if (notes_iterator_ != notes_.end()) {
274           const auto& note = *notes_iterator_;
275           std::cout << "Sending message " << note.message() << " at "
276                     << note.location().latitude() << ", "
277                     << note.location().longitude() << std::endl;
278           StartWrite(&note);
279           notes_iterator_++;
280         } else {
281           StartWritesDone();
282         }
283       }
284       ClientContext context_;
285       const std::vector<RouteNote> notes_;
286       std::vector<RouteNote>::const_iterator notes_iterator_;
287       RouteNote server_note_;
288       std::mutex mu_;
289       std::condition_variable cv_;
290       Status status_;
291       bool done_ = false;
292     };
293 
294     Chatter chatter(stub_.get());
295     Status status = chatter.Await();
296     if (!status.ok()) {
297       std::cout << "RouteChat rpc failed." << std::endl;
298     }
299   }
300 
301  private:
GetOneFeature(const Point & point,Feature * feature)302   bool GetOneFeature(const Point& point, Feature* feature) {
303     ClientContext context;
304     bool result;
305     std::mutex mu;
306     std::condition_variable cv;
307     bool done = false;
308     stub_->async()->GetFeature(
309         &context, &point, feature,
310         [&result, &mu, &cv, &done, feature, this](Status status) {
311           bool ret;
312           if (!status.ok()) {
313             std::cout << "GetFeature rpc failed." << std::endl;
314             ret = false;
315           } else if (!feature->has_location()) {
316             std::cout << "Server returns incomplete feature." << std::endl;
317             ret = false;
318           } else if (feature->name().empty()) {
319             std::cout << "Found no feature at "
320                       << feature->location().latitude() / kCoordFactor_ << ", "
321                       << feature->location().longitude() / kCoordFactor_
322                       << std::endl;
323             ret = true;
324           } else {
325             std::cout << "Found feature called " << feature->name() << " at "
326                       << feature->location().latitude() / kCoordFactor_ << ", "
327                       << feature->location().longitude() / kCoordFactor_
328                       << std::endl;
329             ret = true;
330           }
331           std::lock_guard<std::mutex> lock(mu);
332           result = ret;
333           done = true;
334           cv.notify_one();
335         });
336     std::unique_lock<std::mutex> lock(mu);
337     cv.wait(lock, [&done] { return done; });
338     return result;
339   }
340 
341   const float kCoordFactor_ = 10000000.0;
342   std::unique_ptr<RouteGuide::Stub> stub_;
343   std::vector<Feature> feature_list_;
344 };
345 
main(int argc,char ** argv)346 int main(int argc, char** argv) {
347   // Expect only arg: --db_path=path/to/route_guide_db.json.
348   std::string db = routeguide::GetDbFileContent(argc, argv);
349   RouteGuideClient guide(
350       grpc::CreateChannel("localhost:50051",
351                           grpc::InsecureChannelCredentials()),
352       db);
353 
354   std::cout << "-------------- GetFeature --------------" << std::endl;
355   guide.GetFeature();
356   std::cout << "-------------- ListFeatures --------------" << std::endl;
357   guide.ListFeatures();
358   std::cout << "-------------- RecordRoute --------------" << std::endl;
359   guide.RecordRoute();
360   std::cout << "-------------- RouteChat --------------" << std::endl;
361   guide.RouteChat();
362 
363   return 0;
364 }
365