#include #include #include #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_inventoryURL(inventoryURL), m_target(target) { UpdateDevicesFromInventory(); Start(); } Device::~Device() { } void Device::Start() { m_deviceTimer.StartContinuous(10000, static_cast>(std::bind(&Device::UpdatePresentDevices, this))); m_inventoryTimer.StartContinuous(300000, static_cast>(std::bind(&Device::UpdateDevicesFromInventory, this))); } void Device::Stop() { m_deviceTimer.Stop(); } void Device::Wait() { m_deviceTimer.Wait(); } void Device::UpdateDevicesFromInventory() { try { std::string devices = m_httpClient.GetUrlContents(m_inventoryURL); Util::JSON json = Util::JSON::parse(devices); m_devices.clear(); for (auto& element : json) if (element["bluetooth"] != "") { std::string bluetooth = element["bluetooth"]; std::transform(bluetooth.begin(), bluetooth.end(), bluetooth.begin(), ::tolower); m_devices.push_back(bluetooth); } } catch (const std::exception& e) { std::stringstream ss; ss << "Bluetooth::Device::GetDevicesFromInventory() - Error: " << e.what() << std::endl; syslog(LOG_ERR, "%s", ss.str().c_str()); } } void Device::UpdatePresentDevices() { std::vector presentDevices; std::vector addedDevices; std::vector removedDevices; for (std::vector::iterator it = m_devices.begin(); it != m_devices.end(); ++it) { try { if (Functions::Ping(*it)) { if (std::find(m_presentDevices.begin(), m_presentDevices.end(), *it) == m_presentDevices.end()) SendStateChange(true, *it); presentDevices.push_back(*it); } } catch (const std::exception& e) { std::stringstream ss; ss << "Bluetooth::Device::UpdatePresentDevices() - Error: " << e.what() << std::endl; syslog(LOG_ERR, "%s", ss.str().c_str()); } } for (std::vector::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