xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/route_guide/route_guide_callback_client.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 <chrono>
20 #include <condition_variable>
21 #include <iostream>
22 #include <memory>
23 #include <mutex>
24 #include <random>
25 #include <string>
26 #include <thread>
27 
28 #include "helper.h"
29 
30 #include <grpc/grpc.h>
31 #include <grpcpp/alarm.h>
32 #include <grpcpp/channel.h>
33 #include <grpcpp/client_context.h>
34 #include <grpcpp/create_channel.h>
35 #include <grpcpp/security/credentials.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 { NextWrite(); }
247       void OnReadDone(bool ok) override {
248         if (ok) {
249           std::cout << "Got message " << server_note_.message() << " at "
250                     << server_note_.location().latitude() << ", "
251                     << server_note_.location().longitude() << std::endl;
252           StartRead(&server_note_);
253         }
254       }
255       void OnDone(const Status& s) override {
256         std::unique_lock<std::mutex> l(mu_);
257         status_ = s;
258         done_ = true;
259         cv_.notify_one();
260       }
261       Status Await() {
262         std::unique_lock<std::mutex> l(mu_);
263         cv_.wait(l, [this] { return done_; });
264         return std::move(status_);
265       }
266 
267      private:
268       void NextWrite() {
269         if (notes_iterator_ != notes_.end()) {
270           const auto& note = *notes_iterator_;
271           std::cout << "Sending message " << note.message() << " at "
272                     << note.location().latitude() << ", "
273                     << note.location().longitude() << std::endl;
274           StartWrite(&note);
275           notes_iterator_++;
276         } else {
277           StartWritesDone();
278         }
279       }
280       ClientContext context_;
281       const std::vector<RouteNote> notes_;
282       std::vector<RouteNote>::const_iterator notes_iterator_;
283       RouteNote server_note_;
284       std::mutex mu_;
285       std::condition_variable cv_;
286       Status status_;
287       bool done_ = false;
288     };
289 
290     Chatter chatter(stub_.get());
291     Status status = chatter.Await();
292     if (!status.ok()) {
293       std::cout << "RouteChat rpc failed." << std::endl;
294     }
295   }
296 
297  private:
GetOneFeature(const Point & point,Feature * feature)298   bool GetOneFeature(const Point& point, Feature* feature) {
299     ClientContext context;
300     bool result;
301     std::mutex mu;
302     std::condition_variable cv;
303     bool done = false;
304     stub_->async()->GetFeature(
305         &context, &point, feature,
306         [&result, &mu, &cv, &done, feature, this](Status status) {
307           bool ret;
308           if (!status.ok()) {
309             std::cout << "GetFeature rpc failed." << std::endl;
310             ret = false;
311           } else if (!feature->has_location()) {
312             std::cout << "Server returns incomplete feature." << std::endl;
313             ret = false;
314           } else if (feature->name().empty()) {
315             std::cout << "Found no feature at "
316                       << feature->location().latitude() / kCoordFactor_ << ", "
317                       << feature->location().longitude() / kCoordFactor_
318                       << std::endl;
319             ret = true;
320           } else {
321             std::cout << "Found feature called " << feature->name() << " at "
322                       << feature->location().latitude() / kCoordFactor_ << ", "
323                       << feature->location().longitude() / kCoordFactor_
324                       << std::endl;
325             ret = true;
326           }
327           std::lock_guard<std::mutex> lock(mu);
328           result = ret;
329           done = true;
330           cv.notify_one();
331         });
332     std::unique_lock<std::mutex> lock(mu);
333     cv.wait(lock, [&done] { return done; });
334     return result;
335   }
336 
337   const float kCoordFactor_ = 10000000.0;
338   std::unique_ptr<RouteGuide::Stub> stub_;
339   std::vector<Feature> feature_list_;
340 };
341 
main(int argc,char ** argv)342 int main(int argc, char** argv) {
343   // Expect only arg: --db_path=path/to/route_guide_db.json.
344   std::string db = routeguide::GetDbFileContent(argc, argv);
345   RouteGuideClient guide(
346       grpc::CreateChannel("localhost:50051",
347                           grpc::InsecureChannelCredentials()),
348       db);
349 
350   std::cout << "-------------- GetFeature --------------" << std::endl;
351   guide.GetFeature();
352   std::cout << "-------------- ListFeatures --------------" << std::endl;
353   guide.ListFeatures();
354   std::cout << "-------------- RecordRoute --------------" << std::endl;
355   guide.RecordRoute();
356   std::cout << "-------------- RouteChat --------------" << std::endl;
357   guide.RouteChat();
358 
359   return 0;
360 }
361