BulbStateUpdater.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <BulbStateUpdater.h>
  2. BulbStateUpdater::BulbStateUpdater(Settings& settings, MqttClient& mqttClient, GroupStateStore& stateStore)
  3. : settings(settings),
  4. mqttClient(mqttClient),
  5. stateStore(stateStore),
  6. lastFlush(0),
  7. enabled(true)
  8. { }
  9. void BulbStateUpdater::enable() {
  10. this->enabled = true;
  11. }
  12. void BulbStateUpdater::disable() {
  13. this->enabled = false;
  14. }
  15. void BulbStateUpdater::enqueueUpdate(BulbId bulbId, GroupState& groupState) {
  16. // If can flush immediately, do so (avoids lookup of group state later).
  17. if (canFlush()) {
  18. flushGroup(bulbId, groupState);
  19. } else {
  20. staleGroups.push(bulbId);
  21. }
  22. }
  23. void BulbStateUpdater::loop() {
  24. while (canFlush() && staleGroups.size() > 0) {
  25. BulbId bulbId = staleGroups.shift();
  26. GroupState* groupState = stateStore.get(bulbId);
  27. if (groupState->isMqttDirty()) {
  28. flushGroup(bulbId, *groupState);
  29. groupState->clearMqttDirty();
  30. }
  31. }
  32. }
  33. inline void BulbStateUpdater::flushGroup(BulbId bulbId, GroupState& state) {
  34. char buffer[200];
  35. StaticJsonBuffer<200> jsonBuffer;
  36. JsonObject& message = jsonBuffer.createObject();
  37. state.applyState(message, bulbId, settings.groupStateFields, settings.numGroupStateFields);
  38. message.printTo(buffer);
  39. mqttClient.sendState(
  40. *MiLightRemoteConfig::fromType(bulbId.deviceType),
  41. bulbId.deviceId,
  42. bulbId.groupId,
  43. buffer
  44. );
  45. lastFlush = millis();
  46. }
  47. inline bool BulbStateUpdater::canFlush() const {
  48. return enabled && (millis() > (lastFlush + settings.mqttStateRateLimit));
  49. }