Files
nearby/cpp/platform_v2/base/bluetooth_utils.cc
T
Alexey Polyudov c673bf6ac0 Roll forward to cl/328359974
Change-Id: If2b57ecc852aecf7dea454648f485fd7c08e72a9
2020-08-25 11:27:27 -07:00

62 lines
1.9 KiB
C++

#include "platform_v2/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