Fork of the excellent esp8266-react - https://github.com/rjwats/esp8266-react
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.4 KiB

  1. #include <LightStateService.h>
  2. LightStateService::LightStateService(AsyncWebServer* server,
  3. SecurityManager* securityManager,
  4. AsyncMqttClient* mqttClient,
  5. LightMqttSettingsService* lightMqttSettingsService) :
  6. _httpEndpoint(LightState::read,
  7. LightState::update,
  8. this,
  9. server,
  10. LIGHT_SETTINGS_ENDPOINT_PATH,
  11. securityManager,
  12. AuthenticationPredicates::IS_AUTHENTICATED),
  13. _mqttPubSub(LightState::haRead, LightState::haUpdate, this, mqttClient),
  14. _webSocket(LightState::read,
  15. LightState::update,
  16. this,
  17. server,
  18. LIGHT_SETTINGS_SOCKET_PATH,
  19. securityManager,
  20. AuthenticationPredicates::IS_AUTHENTICATED),
  21. _mqttClient(mqttClient),
  22. _lightMqttSettingsService(lightMqttSettingsService) {
  23. // configure led to be output
  24. pinMode(LED_PIN, OUTPUT);
  25. // configure MQTT callback
  26. _mqttClient->onConnect(std::bind(&LightStateService::registerConfig, this));
  27. // configure update handler for when the light settings change
  28. _lightMqttSettingsService->addUpdateHandler([&](const String& originId) { registerConfig(); }, false);
  29. // configure settings service update handler to update LED state
  30. addUpdateHandler([&](const String& originId) { onConfigUpdated(); }, false);
  31. }
  32. void LightStateService::begin() {
  33. _state.ledOn = DEFAULT_LED_STATE;
  34. onConfigUpdated();
  35. }
  36. void LightStateService::onConfigUpdated() {
  37. digitalWrite(LED_PIN, _state.ledOn ? LED_ON : LED_OFF);
  38. }
  39. void LightStateService::registerConfig() {
  40. if (!_mqttClient->connected()) {
  41. return;
  42. }
  43. String configTopic;
  44. String subTopic;
  45. String pubTopic;
  46. DynamicJsonDocument doc(256);
  47. _lightMqttSettingsService->read([&](LightMqttSettings& settings) {
  48. configTopic = settings.mqttPath + "/config";
  49. subTopic = settings.mqttPath + "/set";
  50. pubTopic = settings.mqttPath + "/state";
  51. doc["~"] = settings.mqttPath;
  52. doc["name"] = settings.name;
  53. doc["unique_id"] = settings.uniqueId;
  54. });
  55. doc["cmd_t"] = "~/set";
  56. doc["stat_t"] = "~/state";
  57. doc["schema"] = "json";
  58. doc["brightness"] = false;
  59. String payload;
  60. serializeJson(doc, payload);
  61. _mqttClient->publish(configTopic.c_str(), 0, false, payload.c_str());
  62. _mqttPubSub.configureTopics(pubTopic, subTopic);
  63. }