Files
nearby/cpp/platform/base/bluetooth_utils.cc
T
Alexey Polyudov 2155b3ddeb Roll forward to cl/338482889
Signed-off-by: Alexey Polyudov <apolyudov@google.com>
Change-Id: I9850950db8bd84f0904ea1a413151887f52098cf
2020-10-22 10:47:34 -07:00

62 lines
1.9 KiB
C++

#include "platform/base/bluetooth_utils.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
namespace location {
namespace nearby {
std::string BluetoothUtils::ToString(const ByteArray& bluetooth_mac_address) {
std::string colon_delimited_string;
if (bluetooth_mac_address.size() != kBluetoothMacAddressLength)
return colon_delimited_string;
if (IsBluetoothMacAddressUnset(bluetooth_mac_address))
return colon_delimited_string;
for (auto byte : std::string(bluetooth_mac_address)) {
if (!colon_delimited_string.empty())
absl::StrAppend(&colon_delimited_string, ":");
absl::StrAppend(&colon_delimited_string, absl::StrFormat("%02X", byte));
}
return colon_delimited_string;
}
ByteArray BluetoothUtils::FromString(absl::string_view bluetooth_mac_address) {
std::string bt_mac_address(bluetooth_mac_address);
// Remove the colon delimiters.
bt_mac_address.erase(
std::remove(bt_mac_address.begin(), bt_mac_address.end(), ':'),
bt_mac_address.end());
// If the bluetooth mac address is invalid (wrong size), return a null byte
// array.
if (bt_mac_address.length() != kBluetoothMacAddressLength * 2) {
return ByteArray();
}
// Convert to bytes. If MAC Address bytes are unset, return a null byte array.
auto bt_mac_address_string(absl::HexStringToBytes(bt_mac_address));
auto bt_mac_address_bytes =
ByteArray(bt_mac_address_string.data(), bt_mac_address_string.size());
if (IsBluetoothMacAddressUnset(bt_mac_address_bytes)) {
return ByteArray();
}
return bt_mac_address_bytes;
}
bool BluetoothUtils::IsBluetoothMacAddressUnset(
const ByteArray& bluetooth_mac_address_bytes) {
for (int i = 0; i < bluetooth_mac_address_bytes.size(); i++) {
if (bluetooth_mac_address_bytes.data()[i] != 0) {
return false;
}
}
return true;
}
} // namespace nearby
} // namespace location