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.

88 lines
2.3 KiB

  1. #ifndef LightStateService_h
  2. #define LightStateService_h
  3. #include <LightMqttSettingsService.h>
  4. #include <HttpEndpoint.h>
  5. #include <MqttPubSub.h>
  6. #include <WebSocketTxRx.h>
  7. #define LED_PIN 2
  8. #define PRINT_DELAY 5000
  9. #define DEFAULT_LED_STATE false
  10. #define OFF_STATE "OFF"
  11. #define ON_STATE "ON"
  12. // Note that the built-in LED is on when the pin is low on most NodeMCU boards.
  13. // This is because the anode is tied to VCC and the cathode to the GPIO 4 (Arduino pin 2).
  14. #ifdef ESP32
  15. #define LED_ON 0x1
  16. #define LED_OFF 0x0
  17. #elif defined(ESP8266)
  18. #define LED_ON 0x0
  19. #define LED_OFF 0x1
  20. #endif
  21. #define LIGHT_SETTINGS_ENDPOINT_PATH "/rest/lightState"
  22. #define LIGHT_SETTINGS_SOCKET_PATH "/ws/lightState"
  23. class LightState {
  24. public:
  25. bool ledOn;
  26. static void read(LightState& settings, JsonObject& root) {
  27. root["led_on"] = settings.ledOn;
  28. }
  29. static StateUpdateResult update(JsonObject& root, LightState& lightState) {
  30. boolean newState = root["led_on"] | DEFAULT_LED_STATE;
  31. if (lightState.ledOn != newState) {
  32. lightState.ledOn = newState;
  33. return StateUpdateResult::CHANGED;
  34. }
  35. return StateUpdateResult::UNCHANGED;
  36. }
  37. static void haRead(LightState& settings, JsonObject& root) {
  38. root["state"] = settings.ledOn ? ON_STATE : OFF_STATE;
  39. }
  40. static StateUpdateResult haUpdate(JsonObject& root, LightState& lightState) {
  41. String state = root["state"];
  42. // parse new led state
  43. boolean newState = false;
  44. if (state.equals(ON_STATE)) {
  45. newState = true;
  46. } else if (!state.equals(OFF_STATE)) {
  47. return StateUpdateResult::ERROR;
  48. }
  49. // change the new state, if required
  50. if (lightState.ledOn != newState) {
  51. lightState.ledOn = newState;
  52. return StateUpdateResult::CHANGED;
  53. }
  54. return StateUpdateResult::UNCHANGED;
  55. }
  56. };
  57. class LightStateService : public StatefulService<LightState> {
  58. public:
  59. LightStateService(AsyncWebServer* server,
  60. SecurityManager* securityManager,
  61. AsyncMqttClient* mqttClient,
  62. LightMqttSettingsService* lightMqttSettingsService);
  63. void begin();
  64. private:
  65. HttpEndpoint<LightState> _httpEndpoint;
  66. MqttPubSub<LightState> _mqttPubSub;
  67. WebSocketTxRx<LightState> _webSocket;
  68. AsyncMqttClient* _mqttClient;
  69. LightMqttSettingsService* _lightMqttSettingsService;
  70. void registerConfig();
  71. void onConfigUpdated();
  72. };
  73. #endif