-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path92_sse.ino
260 lines (238 loc) · 7.53 KB
/
92_sse.ino
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
void startSSE()
{
replyOK();
handleSensors(true);
TickerSen.setLastTime(millis());
handleActors(true);
TickerAct.setLastTime(millis());
inductionSSE(true);
TickerInd.setLastTime(millis());
miscSSE();
}
void inductionSSE(bool val)
{
// val true: init
// val false: only updates
JsonDocument ssedoc;
ssedoc["enabled"] = (int)inductionCooker.getIsEnabled();
ssedoc["power"] = 0;
if (inductionCooker.getIsEnabled())
{
ssedoc["relayOn"] = inductionCooker.getisRelayon();
ssedoc["power"] = inductionCooker.getPower();
ssedoc["state"] = inductionCooker.getInductionState();
if (inductionCooker.getisPower())
{
ssedoc["powerLevel"] = inductionCooker.getCMD_CUR();
}
else
{
ssedoc["powerLevel"] = max(0, inductionCooker.getCMD_CUR() - 1);
}
}
else
val = false;
ssedoc["topic"] = inductionCooker.getTopic();
ssedoc["pl"] = inductionCooker.getPowerLevelOnError();
if (!val)
{
if (inductionCooker.getOldPower() != inductionCooker.getPower())
{
inductionCooker.setOldPower();
val = true;
}
else if (inductionCooker.getoldisRelayon() != inductionCooker.getisRelayon())
{
inductionCooker.setoldisRelayon();
val = true;
}
else if (inductionCooker.getoldisInduon() != inductionCooker.getisInduon())
{
inductionCooker.setoldisInduon();
val = true;
}
}
if (val)
{
char response[measureJson(ssedoc) + 2];
serializeJson(ssedoc, response, sizeof(response));
if (measureJson(ssedoc) > 2 && inductionCooker.getIsEnabled())
SSEBroadcastJson(response, 2);
}
}
void miscSSE()
{
JsonDocument ssedoc;
ssedoc["host"] = mqtthost;
ssedoc["port"] = mqttport;
ssedoc["s_mqtt"] = mqtt_state;
ssedoc["display"] = useDisplay;
ssedoc["lang"] = selLang;
if (startMDNS)
ssedoc["mdns"] = nameMDNS;
else
ssedoc["mdns"] = 0;
char response[measureJson(ssedoc) + 2];
serializeJson(ssedoc, response, sizeof(response));
SSEBroadcastJson(response, 3);
}
void handleChannel()
{
uint8_t channel;
for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot
{
if (!subscription[channel].clientIP)
{
break;
}
}
subscription[channel].clientIP = server.client().remoteIP(); // get IP address of client
subscription[channel].check = true;
String SSEurl = F("http://");
SSEurl += WiFi.localIP().toString();
SSEurl += F(":");
SSEurl += PORT;
SSEurl += F("/rest/events/");
SSEurl += channel;
server.send_P(200, "text/plain", SSEurl.c_str());
}
void SSEKeepAlive()
{
for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++)
{
if (!(subscription[i].clientIP))
{
continue;
}
if (subscription[i].client.connected())
{
// subscription[i].client.println("data: { \"TYPE\":\"KEEP-ALIVE\" }\n"); // Extra newline required by SSE standard
String alive = "event: alive\ndata: { \"type\":\"keep alive\", \"ip\":\"" + IPtoString(subscription[i].clientIP) + "\", \"channel\":\"" + i + "\"}\n";
subscription[i].client.println(alive);
}
else
{
subscription[i].keepAliveTimer.detach();
subscription[i].client.flush();
subscription[i].client.stop();
subscription[i].clientIP = INADDR_NONE;
subscriptionCount--;
}
}
}
void SSEHandler(uint8_t channel)
{
IPAddress clientIP = server.client().remoteIP(); // get IP address of client
if (subscription[channel].check == true)
{
if (clientIP == subscription[channel].clientIP)
{
subscription[channel].client = server.client();
subscription[channel].keepAliveTimer = Ticker();
subscription[channel].check = false;
subscriptionCount++;
}
}
WiFiClient client = server.client();
SSESubscription &s = subscription[channel];
if (s.clientIP != client.remoteIP())
{ // IP addresses don't match, reject this client
return handleNotFound();
}
client.setNoDelay(true);
s.client = client; // capture SSE server client connection
server.setContentLength(CONTENT_LENGTH_UNKNOWN); // the payload can go on forever
server.sendContent_P(PSTR("HTTP/1.1 200 OK\nContent-Type: text/event-stream\nConnection: keep-alive\nCache-Control: no-cache\nAccess-Control-Allow-Origin: *\n\n"));
s.keepAliveTimer.attach(15.0, SSEKeepAlive); // Refresh time every 15s
initialSSE(channel);
}
void SSEBroadcastJson(const char *jsonValue, uint8_t typ)
{
for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++)
{
if (!(subscription[i].clientIP))
continue;
WiFiClient client = subscription[i].client;
String IPaddrstr = IPAddress(subscription[i].clientIP).toString();
if (client)
{
char response[strlen(jsonValue) + 60];
if (typ == 0) // sensors
{
sprintf_P(response, PSTR("event: sensors\ndata: %s\nid: %lu\nretry: 5000\n\n"), jsonValue, millis());
}
else if (typ == 1) // actors
{
sprintf_P(response, PSTR("event: actors\ndata: %s\nid: %lu\nretry: 5000\n\n"), jsonValue, millis());
}
else if (typ == 2) // induction
{
sprintf_P(response, PSTR("event: ids\ndata: %s\nid: %lu\nretry: 5000\n\n"), jsonValue, millis());
}
else if (typ == 3) // misc System
{
sprintf_P(response, PSTR("event: misc\ndata: %s\nid: %lu\nretry: 5000\n\n"), jsonValue, millis());
}
else
{
DEBUG_ERROR("SYS", "unknown SSE broadcast type %d", typ);
continue;
}
DEBUG_VERBOSE("SYS", "%s", response);
client.print(response);
}
}
}
void handleNotFound()
{
if (loadFromLittlefs(server.uri()))
{
return;
}
String message = "Handle Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++)
{
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
replyNotFound(message);
}
void handleAll()
{
const char *uri = server.uri().c_str();
const char *restEvents = PSTR("/rest/events/");
if (strncmp_P(uri, restEvents, strlen_P(restEvents)))
{
return handleNotFound();
}
uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number
unsigned int channel = atoi(uri);
if (channel < SSE_MAX_CHANNELS)
SSEHandler(channel);
else
handleNotFound();
}
void checkAliveSSE()
{
IPAddress clientIP = server.client().remoteIP(); // get IP address of client
for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++)
{
if (clientIP == subscription[i].clientIP)
{
replyResponse("1");
return;
}
}
replyResponse("-1");
}
void initialSSE(uint8_t val)
{
String alive = "event: alive\ndata: { \"type\":\"new SSE\", \"ip\":\"" + subscription[val].clientIP.toString() + "\", \"channel\":\"" + val + "\"}\n";
subscription[val].client.println(alive);
}