Device.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <sstream>
  2. #include <syslog.h>
  3. #include <boost/algorithm/string.hpp>
  4. #include "Util/JSON.h"
  5. #include "Functions.h"
  6. #include "Device.h"
  7. namespace PresenceDetection {
  8. namespace Bluetooth {
  9. Device::Device(const std::string& inventoryURL, const std::string& target) :
  10. m_target(target)
  11. {
  12. std::string devices = m_httpClient.GetUrlContents(inventoryURL);
  13. Util::JSON json = Util::JSON::parse(devices);
  14. for (auto& element : json)
  15. if (element["bluetooth"] != "")
  16. m_devices.push_back(element["bluetooth"]);
  17. Start();
  18. }
  19. Device::~Device()
  20. {
  21. }
  22. void Device::Start()
  23. {
  24. m_timer.StartContinuous(10000, static_cast<std::function<void()>>(std::bind(&Device::UpdatePresentDevices, this)));
  25. }
  26. void Device::Stop()
  27. {
  28. m_timer.Stop();
  29. }
  30. void Device::Wait()
  31. {
  32. m_timer.Wait();
  33. }
  34. void Device::UpdatePresentDevices()
  35. {
  36. std::vector<std::string> presentDevices;
  37. std::vector<std::string> addedDevices;
  38. std::vector<std::string> removedDevices;
  39. for (std::vector<std::string>::iterator it = m_devices.begin(); it != m_devices.end(); ++it)
  40. {
  41. if (Functions::Ping(*it))
  42. {
  43. if (std::find(m_presentDevices.begin(), m_presentDevices.end(), *it) == m_presentDevices.end())
  44. SendStateChange(true, *it);
  45. presentDevices.push_back(*it);
  46. }
  47. }
  48. for (std::vector<std::string>::iterator it = m_presentDevices.begin(); it != m_presentDevices.end(); ++it)
  49. if (std::find(presentDevices.begin(), presentDevices.end(), *it) == presentDevices.end())
  50. SendStateChange(false, *it);
  51. m_presentDevices.assign(presentDevices.begin(), presentDevices.end());
  52. }
  53. void Device::SendStateChange(bool present, const std::string& macAddress)
  54. {
  55. char sign;
  56. if (present)
  57. sign = '+';
  58. else
  59. sign = '-';
  60. std::stringstream ss;
  61. ss << "Bluetooth: " << sign << " " << macAddress;
  62. syslog(LOG_INFO, "%s", ss.str().c_str());
  63. std::stringstream url;
  64. url << m_target << "/Bluetooth/" << sign << "/" << macAddress;
  65. try
  66. {
  67. m_httpClient.GetUrlSilent(url.str());
  68. }
  69. catch (const std::exception& e)
  70. {
  71. std::stringstream ss;
  72. ss << "Bluetooth::Device::SendStateChange() - Error: " << e.what() << std::endl;
  73. syslog(LOG_ERR, "%s", ss.str().c_str());
  74. }
  75. }
  76. } // namespace Bluetooth
  77. } // namespace PresenceDetection