1 /* 2 * Copyright 2016 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 <cstdint> 20 #include <queue> 21 #include <string> 22 #include <vector> 23 24 #include "async_manager.h" 25 #include "device.h" 26 27 #include "hci/include/hci_hal.h" 28 29 namespace test_vendor_lib { 30 31 // Model the connection of a device to the controller. 32 class Connection { 33 public: 34 Connection(std::shared_ptr<Device> dev, uint16_t handle) 35 : dev_(dev), handle_(handle), connected_(true), encrypted_(false) {} 36 37 virtual ~Connection() = default; 38 39 // Return a string representing the connection for logging. 40 const std::string ToString(); 41 42 // Return a pointer to the device in the connection. 43 std::shared_ptr<Device> GetDevice() { return dev_; } 44 45 // Return true if the handle matches and the device is connected. 46 inline bool operator==(uint16_t handle) { 47 return (handle_ == handle) && connected_; 48 } 49 50 // Return true if the handle doesn't match or the device is not connected. 51 inline bool operator!=(uint16_t handle) { 52 return (handle_ != handle) || !connected_; 53 } 54 55 void Disconnect() { connected_ = false; }; 56 bool Connected() { return connected_; }; 57 58 void Encrypt() { encrypted_ = true; }; 59 bool Encrypted() { return encrypted_; }; 60 61 // Add an action to the connection queue. 62 void AddAction(const TaskCallback& task); 63 64 // Execute the next action in the connection queue to simulate packet 65 // exchange. 66 void SendToDevice(); 67 68 // Add a message from the device. 69 void AddMessage(const std::vector<uint8_t>& message); 70 71 // Receive data from the device to simulate packet exchange. 72 bool ReceiveFromDevice(std::vector<uint8_t>& data); 73 74 private: 75 // A shared pointer to the connected device 76 std::shared_ptr<Device> dev_; 77 78 // The connection handle 79 uint16_t handle_; 80 81 // State variables 82 bool connected_; 83 bool encrypted_; 84 85 // Actions for the next packet exchange. 86 std::queue<TaskCallback> actions_; 87 88 // Messages from the device for the next packet exchange. 89 std::queue<std::vector<uint8_t>> messages_; 90 }; 91 92 } // namespace test_vendor_lib 93