route_guide_callback_client.cc 11 KB

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