1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <grpc++/grpc++.h>
20 #include <module.h>
21 
22 #include <functional>
23 #include <vector>
24 
25 namespace bluetooth {
26 namespace grpc {
27 
28 class GrpcFacadeModule;
29 
30 class GrpcModule : public ::bluetooth::Module {
31  public:
32   static const ModuleFactory Factory;
33 
34   void StartServer(const std::string& address, int port);
35 
36   void StopServer();
37 
38   void Register(GrpcFacadeModule* facade);
39 
40   void Unregister(GrpcFacadeModule* facade);
41 
42   // Blocks for incoming gRPC requests
43   void RunGrpcLoop();
44 
45  protected:
46   void ListDependencies(ModuleList* list) override;
47 
48   void Start() override;
49 
50   void Stop() override;
51 
52   std::string ToString() const override;
53 
54  private:
55   bool started_;
56   std::unique_ptr<::grpc::Server> server_ = nullptr;
57   std::unique_ptr<::grpc::ServerCompletionQueue> completion_queue_ = nullptr;
58   std::vector<GrpcFacadeModule*> facades_;
59 };
60 
61 class GrpcFacadeModule : public ::bluetooth::Module {
62   friend GrpcModule;
63 
64  protected:
65   void ListDependencies(ModuleList* list) override;
66 
67   void Start() override;
68 
69   void Stop() override;
70 
71   virtual ::grpc::Service* GetService() const = 0;
72 
OnServerStarted()73   virtual void OnServerStarted() {}
74 
OnServerStopped()75   virtual void OnServerStopped() {}
76 
77   std::string ToString() const override;
78 };
79 
80 }  // namespace grpc
81 }  // namespace bluetooth
82