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 #include "bluetooth_address.h" 18 19 #include <android-base/logging.h> 20 #include <cutils/properties.h> 21 #include <fcntl.h> 22 #include <utils/Log.h> 23 24 namespace android { 25 namespace hardware { 26 namespace bluetooth { 27 namespace V1_0 { 28 namespace dragon { 29 30 void BluetoothAddress::bytes_to_string(const uint8_t* addr, char* addr_str) { 31 sprintf(addr_str, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], 32 addr[3], addr[4], addr[5]); 33 } 34 35 bool BluetoothAddress::string_to_bytes(const char* addr_str, uint8_t* addr) { 36 if (addr_str == NULL) return false; 37 if (strnlen(addr_str, kStringLength) != kStringLength) return false; 38 unsigned char trailing_char = '\0'; 39 40 return (sscanf(addr_str, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx%1c", 41 &addr[0], &addr[1], &addr[2], &addr[3], &addr[4], &addr[5], 42 &trailing_char) == kBytes); 43 } 44 45 bool BluetoothAddress::get_local_address(uint8_t* local_addr) { 46 char property[PROPERTY_VALUE_MAX] = {0}; 47 48 // No factory BDADDR found. Look for a previously stored BDA. 49 if (property_get(PERSIST_BDADDR_PROPERTY, property, NULL) && 50 string_to_bytes(property, local_addr)) { 51 return true; 52 } 53 54 // Look for an the WiFi MAC from an AzureWave module. 55 int wifi_mac_fd = open(AZW_WIFI_MAC_PATH, O_RDONLY); 56 if (wifi_mac_fd != -1) { 57 int bytes_read = read(wifi_mac_fd, property, kStringLength); 58 close(wifi_mac_fd); 59 if (bytes_read != kStringLength) return false; 60 61 // Null terminate the string. 62 property[kStringLength] = '\0'; 63 64 // Zero last bit to calculate the Bluetooth address. This works because the 65 // WiFi address is always odd (never ending in 0x0 or 0xa). 66 property[kStringLength - 1] = property[kStringLength - 1] - 1; 67 68 ALOGD("%s: Got BDA from WiFi MAC %s", __func__, property); 69 return string_to_bytes(property, local_addr); 70 } 71 72 return false; 73 } 74 75 } // namespace dragon 76 } // namespace V1_0 77 } // namespace bluetooth 78 } // namespace hardware 79 } // namespace android 80