#include <string.h>
#include "Mgmt.h"
#include "Logger.h"
#include "Utils.h"
namespace ggk {
Mgmt::Mgmt(uint16_t controllerIndex)
: controllerIndex(controllerIndex)
{
HciAdapter::getInstance().sync(controllerIndex);
}
bool Mgmt::setName(std::string name, std::string shortName)
{
name = truncateName(name);
shortName = truncateShortName(shortName);
struct SRequest : HciAdapter::HciHeader
{
char name[249];
char shortName[11];
} __attribute__((packed));
SRequest request;
request.code = Mgmt::ESetLocalNameCommand;
request.controllerId = controllerIndex;
request.dataSize = sizeof(SRequest) - sizeof(HciAdapter::HciHeader);
memset(request.name, 0, sizeof(request.name));
snprintf(request.name, sizeof(request.name), "%s", name.c_str());
memset(request.shortName, 0, sizeof(request.shortName));
snprintf(request.shortName, sizeof(request.shortName), "%s", shortName.c_str());
if (!HciAdapter::getInstance().sendCommand(request))
{
Logger::warn(SSTR << " + Failed to set name");
return false;
}
return true;
}
bool Mgmt::setState(uint16_t commandCode, uint16_t controllerId, uint8_t newState)
{
struct SRequest : HciAdapter::HciHeader
{
uint8_t state;
} __attribute__((packed));
SRequest request;
request.code = commandCode;
request.controllerId = controllerId;
request.dataSize = sizeof(SRequest) - sizeof(HciAdapter::HciHeader);
request.state = newState;
if (!HciAdapter::getInstance().sendCommand(request))
{
Logger::warn(SSTR << " + Failed to set " << HciAdapter::kCommandCodeNames[commandCode] << " state to: " << static_cast<int>(newState));
return false;
}
return true;
}
bool Mgmt::setPowered(bool newState)
{
return setState(Mgmt::ESetPoweredCommand, controllerIndex, newState ? 1 : 0);
}
bool Mgmt::setBredr(bool newState)
{
return setState(Mgmt::ESetBREDRCommand, controllerIndex, newState ? 1 : 0);
}
bool Mgmt::setSecureConnections(uint8_t newState)
{
return setState(Mgmt::ESetSecureConnectionsCommand, controllerIndex, newState);
}
bool Mgmt::setBondable(bool newState)
{
return setState(Mgmt::ESetBondableCommand, controllerIndex, newState ? 1 : 0);
}
bool Mgmt::setConnectable(bool newState)
{
return setState(Mgmt::ESetConnectableCommand, controllerIndex, newState ? 1 : 0);
}
bool Mgmt::setLE(bool newState)
{
return setState(Mgmt::ESetLowEnergyCommand, controllerIndex, newState ? 1 : 0);
}
bool Mgmt::setAdvertising(uint8_t newState)
{
return setState(Mgmt::ESetAdvertisingCommand, controllerIndex, newState);
}
std::string Mgmt::truncateName(const std::string &name)
{
if (name.length() <= kMaxAdvertisingNameLength)
{
return name;
}
return name.substr(0, kMaxAdvertisingNameLength);
}
std::string Mgmt::truncateShortName(const std::string &name)
{
if (name.length() <= kMaxAdvertisingShortNameLength)
{
return name;
}
return name.substr(0, kMaxAdvertisingShortNameLength);
}
};