Device.cpp 2.0 KB

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