Home | History | Annotate | Download | only in bluetooth
      1 //
      2 // Copyright 2017 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 #include "hci_protocol.h"
     18 
     19 #define LOG_TAG "android.hardware.bluetooth-hci-hci_protocol"
     20 #include <android-base/logging.h>
     21 #include <assert.h>
     22 #include <fcntl.h>
     23 #include <utils/Log.h>
     24 
     25 namespace {
     26 
     27 const size_t preamble_size_for_type[] = {
     28     0, HCI_COMMAND_PREAMBLE_SIZE, HCI_ACL_PREAMBLE_SIZE, HCI_SCO_PREAMBLE_SIZE,
     29     HCI_EVENT_PREAMBLE_SIZE};
     30 const size_t packet_length_offset_for_type[] = {
     31     0, HCI_LENGTH_OFFSET_CMD, HCI_LENGTH_OFFSET_ACL, HCI_LENGTH_OFFSET_SCO,
     32     HCI_LENGTH_OFFSET_EVT};
     33 
     34 size_t HciGetPacketLengthForType(HciPacketType type, const uint8_t* preamble) {
     35   size_t offset = packet_length_offset_for_type[type];
     36   if (type != HCI_PACKET_TYPE_ACL_DATA) return preamble[offset];
     37   return (((preamble[offset + 1]) << 8) | preamble[offset]);
     38 }
     39 
     40 }  // namespace
     41 
     42 namespace android {
     43 namespace hardware {
     44 namespace bluetooth {
     45 namespace hci {
     46 
     47 size_t HciProtocol::WriteSafely(int fd, const uint8_t* data, size_t length) {
     48   size_t transmitted_length = 0;
     49   while (length > 0) {
     50     ssize_t ret =
     51         TEMP_FAILURE_RETRY(write(fd, data + transmitted_length, length));
     52 
     53     if (ret == -1) {
     54       if (errno == EAGAIN) continue;
     55       ALOGE("%s error writing to UART (%s)", __func__, strerror(errno));
     56       break;
     57 
     58     } else if (ret == 0) {
     59       // Nothing written :(
     60       ALOGE("%s zero bytes written - something went wrong...", __func__);
     61       break;
     62     }
     63 
     64     transmitted_length += ret;
     65     length -= ret;
     66   }
     67 
     68   return transmitted_length;
     69 }
     70 
     71 }  // namespace hci
     72 }  // namespace bluetooth
     73 }  // namespace hardware
     74 }  // namespace android
     75