Files
PresenceDetection/Bluetooth/Device.cpp
T

96 lines
2.1 KiB
C++

#include <sstream>
#include <syslog.h>
#include <boost/algorithm/string.hpp>
#include "Util/JSON.h"
#include "Functions.h"
#include "Device.h"
namespace PresenceDetection {
namespace Bluetooth {
Device::Device(const std::string& inventoryURL, const std::string& target) :
m_target(target)
{
std::string devices = m_httpClient.GetUrlContents(inventoryURL);
Util::JSON json = Util::JSON::parse(devices);
for (auto& element : json)
if (element["bluetooth"] != "")
m_devices.push_back(element["bluetooth"]);
Start();
}
Device::~Device()
{
}
void Device::Start()
{
m_timer.StartContinuous(10000, static_cast<std::function<void()>>(std::bind(&Device::UpdatePresentDevices, this)));
}
void Device::Stop()
{
m_timer.Stop();
}
void Device::Wait()
{
m_timer.Wait();
}
void Device::UpdatePresentDevices()
{
std::vector<std::string> presentDevices;
std::vector<std::string> addedDevices;
std::vector<std::string> removedDevices;
for (std::vector<std::string>::iterator it = m_devices.begin(); it != m_devices.end(); ++it)
{
if (Functions::Ping(*it))
{
if (std::find(m_presentDevices.begin(), m_presentDevices.end(), *it) == m_presentDevices.end())
SendStateChange(true, *it);
presentDevices.push_back(*it);
}
}
for (std::vector<std::string>::iterator it = m_presentDevices.begin(); it != m_presentDevices.end(); ++it)
if (std::find(presentDevices.begin(), presentDevices.end(), *it) == presentDevices.end())
SendStateChange(false, *it);
m_presentDevices.assign(presentDevices.begin(), presentDevices.end());
}
void Device::SendStateChange(bool present, const std::string& macAddress)
{
char sign;
if (present)
sign = '+';
else
sign = '-';
std::stringstream ss;
ss << "Bluetooth: " << sign << " " << macAddress;
syslog(LOG_INFO, "%s", ss.str().c_str());
std::stringstream url;
url << m_target << "/Bluetooth/" << sign << "/" << macAddress;
try
{
m_httpClient.GetUrlSilent(url.str());
}
catch (const std::exception& e)
{
std::stringstream ss;
ss << "Bluetooth::Device::SendStateChange() - Error: " << e.what() << std::endl;
syslog(LOG_ERR, "%s", ss.str().c_str());
}
}
} // namespace Bluetooth
} // namespace PresenceDetection