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 #define LOG_TAG "packet" 18 19 #include "packet.h" 20 21 #include <algorithm> 22 23 #include <base/logging.h> 24 #include "osi/include/log.h" 25 26 using std::vector; 27 28 namespace test_vendor_lib { 29 30 Packet::Packet(serial_data_type_t type, vector<uint8_t> header) 31 : type_(type), header_(std::move(header)) { 32 payload_ = {0}; 33 } 34 35 bool Packet::AddPayloadOctets(size_t octets, const vector<uint8_t>& bytes) { 36 if (GetPayloadSize() + octets > kMaxPayloadOctets) return false; 37 38 if (octets != bytes.size()) return false; 39 40 payload_.insert(payload_.end(), bytes.begin(), bytes.end()); 41 payload_[0] = payload_.size() - 1; 42 43 return true; 44 } 45 46 bool Packet::AddPayloadOctets(size_t octets, uint64_t value) { 47 vector<uint8_t> val_vector; 48 49 uint64_t v = value; 50 51 if (octets > sizeof(uint64_t)) return false; 52 53 for (size_t i = 0; i < octets; i++) { 54 val_vector.push_back(v & 0xff); 55 v = v >> 8; 56 } 57 58 if (v != 0) return false; 59 60 return AddPayloadOctets(octets, val_vector); 61 } 62 63 bool Packet::AddPayloadBtAddress(const BtAddress& address) { 64 if (GetPayloadSize() + BtAddress::kOctets > kMaxPayloadOctets) return false; 65 66 address.ToVector(payload_); 67 68 payload_[0] = payload_.size() - 1; 69 70 return true; 71 } 72 73 bool Packet::IncrementPayloadCounter(size_t index) { 74 if (payload_.size() < index - 1) return false; 75 76 payload_[index]++; 77 return true; 78 } 79 80 bool Packet::IncrementPayloadCounter(size_t index, uint8_t max_val) { 81 if (payload_.size() < index - 1) return false; 82 83 if (payload_[index] + 1 > max_val) return false; 84 85 payload_[index]++; 86 return true; 87 } 88 89 const vector<uint8_t>& Packet::GetHeader() const { 90 // Every packet must have a header. 91 CHECK(GetHeaderSize() > 0); 92 return header_; 93 } 94 95 uint8_t Packet::GetHeaderSize() const { return header_.size(); } 96 97 size_t Packet::GetPacketSize() const { 98 // Add one for the type octet. 99 return 1 + header_.size() + payload_.size(); 100 } 101 102 const vector<uint8_t>& Packet::GetPayload() const { return payload_; } 103 104 size_t Packet::GetPayloadSize() const { return payload_.size(); } 105 106 serial_data_type_t Packet::GetType() const { return type_; } 107 108 } // namespace test_vendor_lib 109