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.

71 lines
1.8 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 BLINK_LED 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 serialize(LightState& settings, JsonObject& root) {
  27. root["led_on"] = settings.ledOn;
  28. }
  29. static void deserialize(JsonObject& root, LightState& settings) {
  30. settings.ledOn = root["led_on"] | DEFAULT_LED_STATE;
  31. }
  32. static void haSerialize(LightState& settings, JsonObject& root) {
  33. root["state"] = settings.ledOn ? ON_STATE : OFF_STATE;
  34. }
  35. static void haDeserialize(JsonObject& root, LightState& settings) {
  36. String state = root["state"];
  37. settings.ledOn = strcmp(ON_STATE, state.c_str()) ? false : true;
  38. }
  39. };
  40. class LightStateService : public StatefulService<LightState> {
  41. public:
  42. LightStateService(AsyncWebServer* server,
  43. SecurityManager* securityManager,
  44. AsyncMqttClient* mqttClient,
  45. LightMqttSettingsService* lightMqttSettingsService);
  46. void begin();
  47. private:
  48. HttpEndpoint<LightState> _httpEndpoint;
  49. MqttPubSub<LightState> _mqttPubSub;
  50. WebSocketTxRx<LightState> _webSocket;
  51. AsyncMqttClient* _mqttClient;
  52. LightMqttSettingsService* _lightMqttSettingsService;
  53. void registerConfig();
  54. void onConfigUpdated();
  55. };
  56. #endif