1 /*
2  * Copyright 2015 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 <functional>  // for function
20 #include <memory>      // for shared_ptr
21 #include <string>      // for string
22 #include <vector>      // for vector
23 
24 #include "net/async_data_channel.h"  // for AsyncDataChannel
25 #include "net/async_data_channel_server.h"  // for AsyncDataChannelServer (ptr only), Con...
26 
27 namespace rootcanal {
28 
29 using android::net::AsyncDataChannel;
30 using android::net::AsyncDataChannelServer;
31 using android::net::ConnectCallback;
32 
33 // Manages communications between test channel and the controller. Mirrors the
34 // HciTransport for the test channel.
35 class TestChannelTransport {
36  public:
TestChannelTransport()37   TestChannelTransport() {}
38 
~TestChannelTransport()39   ~TestChannelTransport() {}
40 
41   // Opens a port and returns and starts listening for incoming connections.
42   bool SetUp(std::shared_ptr<AsyncDataChannelServer> server,
43              ConnectCallback connection_callback);
44 
45   // Closes the port (if succesfully opened in SetUp).
46   void CleanUp();
47 
48   // Sets the callback that fires when data is read in WatchFd().
49   void RegisterCommandHandler(
50       const std::function<void(const std::string&,
51                                const std::vector<std::string>&)>& callback);
52 
53   // Send data back to the test channel.
54   static void SendResponse(std::shared_ptr<AsyncDataChannel> socket,
55                            const std::string& response);
56 
57   void OnCommandReady(AsyncDataChannel* socket,
58                       std::function<void(void)> unwatch);
59 
60  private:
61   std::function<void(const std::string&, const std::vector<std::string>&)>
62       command_handler_;
63   std::function<void(std::shared_ptr<AsyncDataChannel>)> connection_callback_;
64   std::shared_ptr<AsyncDataChannelServer> socket_server_;
65 
66   TestChannelTransport(const TestChannelTransport& cmdPckt) = delete;
67   TestChannelTransport& operator=(const TestChannelTransport& cmdPckt) = delete;
68 };
69 
70 }  // namespace rootcanal
71