1 /****************************************************************************** 2 * 3 * Copyright (C) 2014 Google, Inc. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at: 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 ******************************************************************************/ 18 19 #include <base/logging.h> 20 #include <ctype.h> 21 #include <stdio.h> 22 #include <string.h> 23 24 #include "btcore/include/bdaddr.h" 25 26 bool bdaddr_is_empty(const bt_bdaddr_t* addr) { 27 CHECK(addr != NULL); 28 29 uint8_t zero[sizeof(bt_bdaddr_t)] = {0}; 30 return memcmp(addr, &zero, sizeof(bt_bdaddr_t)) == 0; 31 } 32 33 bool bdaddr_equals(const bt_bdaddr_t* first, const bt_bdaddr_t* second) { 34 CHECK(first != NULL); 35 CHECK(second != NULL); 36 37 return memcmp(first, second, sizeof(bt_bdaddr_t)) == 0; 38 } 39 40 bt_bdaddr_t* bdaddr_copy(bt_bdaddr_t* dest, const bt_bdaddr_t* src) { 41 CHECK(dest != NULL); 42 CHECK(src != NULL); 43 44 return (bt_bdaddr_t*)memcpy(dest, src, sizeof(bt_bdaddr_t)); 45 } 46 47 const char* bdaddr_to_string(const bt_bdaddr_t* addr, char* string, 48 size_t size) { 49 CHECK(addr != NULL); 50 CHECK(string != NULL); 51 52 if (size < 18) return NULL; 53 54 const uint8_t* ptr = addr->address; 55 snprintf(string, size, "%02x:%02x:%02x:%02x:%02x:%02x", ptr[0], ptr[1], 56 ptr[2], ptr[3], ptr[4], ptr[5]); 57 return string; 58 } 59 60 bool string_is_bdaddr(const char* string) { 61 CHECK(string != NULL); 62 63 size_t len = strlen(string); 64 if (len != 17) return false; 65 66 for (size_t i = 0; i < len; ++i) { 67 // Every 3rd char must be ':'. 68 if (((i + 1) % 3) == 0 && string[i] != ':') return false; 69 70 // All other chars must be a hex digit. 71 if (((i + 1) % 3) != 0 && !isxdigit(string[i])) return false; 72 } 73 return true; 74 } 75 76 bool string_to_bdaddr(const char* string, bt_bdaddr_t* addr) { 77 CHECK(string != NULL); 78 CHECK(addr != NULL); 79 80 bt_bdaddr_t new_addr; 81 uint8_t* ptr = new_addr.address; 82 bool ret = sscanf(string, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", 83 &ptr[0], &ptr[1], &ptr[2], &ptr[3], &ptr[4], &ptr[5]) == 6; 84 85 if (ret) memcpy(addr, &new_addr, sizeof(bt_bdaddr_t)); 86 87 return ret; 88 } 89