thing_manager.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "thing_manager.h"
  2. #include <esp_log.h>
  3. #define TAG "ThingManager"
  4. namespace iot {
  5. void ThingManager::AddThing(Thing* thing) {
  6. things_.push_back(thing);
  7. }
  8. std::string ThingManager::GetDescriptorsJson() {
  9. std::string json_str = "[";
  10. for (auto& thing : things_) {
  11. json_str += thing->GetDescriptorJson() + ",";
  12. }
  13. if (json_str.back() == ',') {
  14. json_str.pop_back();
  15. }
  16. json_str += "]";
  17. return json_str;
  18. }
  19. bool ThingManager::GetStatesJson(std::string& json, bool delta) {
  20. if (!delta) {
  21. last_states_.clear();
  22. }
  23. bool changed = false;
  24. json = "[";
  25. // 枚举thing,获取每个thing的state,如果发生变化,则更新,保存到last_states_
  26. // 如果delta为true,则只返回变化的部分
  27. for (auto& thing : things_) {
  28. std::string state = thing->GetStateJson();
  29. if (delta) {
  30. // 如果delta为true,则只返回变化的部分
  31. auto it = last_states_.find(thing->name());
  32. if (it != last_states_.end() && it->second == state) {
  33. continue;
  34. }
  35. changed = true;
  36. last_states_[thing->name()] = state;
  37. }
  38. json += state + ",";
  39. }
  40. if (json.back() == ',') {
  41. json.pop_back();
  42. }
  43. json += "]";
  44. return changed;
  45. }
  46. void ThingManager::Invoke(const cJSON* command) {
  47. auto name = cJSON_GetObjectItem(command, "name");
  48. for (auto& thing : things_) {
  49. if (thing->name() == name->valuestring) {
  50. thing->Invoke(command);
  51. return;
  52. }
  53. }
  54. }
  55. } // namespace iot