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