BulbStateUpdater.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. { }
  8. void BulbStateUpdater::enqueueUpdate(BulbId bulbId, GroupState& groupState) {
  9. // If can flush immediately, do so (avoids lookup of group state later).
  10. if (canFlush()) {
  11. flushGroup(bulbId, groupState);
  12. } else {
  13. staleGroups.push(bulbId);
  14. }
  15. }
  16. void BulbStateUpdater::loop() {
  17. while (canFlush() && staleGroups.size() > 0) {
  18. BulbId bulbId = staleGroups.shift();
  19. GroupState& groupState = stateStore.get(bulbId);
  20. if (groupState.isMqttDirty()) {
  21. flushGroup(bulbId, groupState);
  22. groupState.clearMqttDirty();
  23. }
  24. }
  25. }
  26. inline void BulbStateUpdater::flushGroup(BulbId bulbId, GroupState& state) {
  27. char buffer[200];
  28. StaticJsonBuffer<200> jsonBuffer;
  29. JsonObject& message = jsonBuffer.createObject();
  30. state.applyState(message);
  31. message.printTo(buffer);
  32. mqttClient.sendState(
  33. *MiLightRemoteConfig::fromType(bulbId.deviceType),
  34. bulbId.deviceId,
  35. bulbId.groupId,
  36. buffer
  37. );
  38. lastFlush = millis();
  39. }
  40. inline bool BulbStateUpdater::canFlush() const {
  41. return (millis() > (lastFlush + settings.mqttStateRateLimit));
  42. }