forked from doudar/SmartSpin2k
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebsocketAppender.cpp
84 lines (72 loc) · 2.09 KB
/
WebsocketAppender.cpp
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
/*
* Copyright (C) 2020 Anthony Doud & Joel Baranick
* All rights reserved
*
* SPDX-License-Identifier: GPL-2.0-only
*/
// see: https://github.com/gilmaimon/ArduinoWebsockets
#include "WebsocketAppender.h"
WebSocketAppender::WebSocketAppender() {
for (uint8_t index = 0; index < maxClients; index++) {
_clients[index] = NULL;
}
}
void WebSocketAppender::Initialize() { _webSocketsServer.listen(WebSocketAppender::port); }
void WebSocketAppender::Loop() {
// CheckConnectedClients();
if (WiFi.status() == WL_CONNECTED && GetClientsCount() < maxClients) {
if (_webSocketsServer.poll() == false) {
return;
}
// Serial.println("add websocket client.");
WebsocketsClient client = _webSocketsServer.accept();
AddClient(new WebsocketsClient(client));
}
}
void WebSocketAppender::Log(const char* message) {
// Serial.println("Log websocket.");
// Serial.printf("%d clients connected.\n", GetClientsCount());
for (uint8_t index = 0; index < maxClients; index++) {
WebsocketsClient* client = _clients[index];
if (client == NULL) {
continue;
}
if (!client->available() || !client->send(message)) {
_clients[index] = NULL;
// Serial.println("Remove disconnected websocket client from Log().");
client->close();
delete client;
}
}
}
uint8_t WebSocketAppender::GetClientsCount() {
uint8_t count = 0;
for (uint8_t index = 0; index < maxClients; index++) {
if (_clients[index] != NULL) {
count++;
}
}
return count;
}
void WebSocketAppender::AddClient(WebsocketsClient* client) {
for (uint8_t index = 0; index < maxClients; index++) {
if (_clients[index] == NULL) {
_clients[index] = client;
return;
}
}
}
void WebSocketAppender::CheckConnectedClients() {
for (uint8_t index = 0; index < maxClients; index++) {
WebsocketsClient* client = _clients[index];
if (client == NULL) {
continue;
}
if (!client->available()) {
// Serial.println("Remove disconnected websocket client.");
_clients[index] = NULL;
client->close();
delete client;
}
}
}