Repository navigation
Expand file tree
/
Copy pathPanelStreamer.cpp
More file actions
383 lines (303 loc) · 12.5 KB
/
Copy pathPanelStreamer.cpp
File metadata and controls
383 lines (303 loc) · 12.5 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#include "PanelStreamer.hpp"
#include "MultiLogger.hpp"
#include <ArduinoJson.h>
// Static instance for callback
PanelStreamer* PanelStreamer::_instance = nullptr;
// Constants for streaming
#define PANEL_STREAM_FPS 4
#define PANEL_STREAM_INTERVAL_MS (1000 / PANEL_STREAM_FPS)
#define MAX_CLIENTS 2
PanelStreamer::PanelStreamer(PanelManager* panelManager)
: _panelManager(panelManager), _wsServer(nullptr), _taskHandle(nullptr),
_running(false), _panelBuffer(nullptr), _compressedBuffer(nullptr) {
Log.println("[PanelStreamer] Constructor starting...");
_instance = this;
_controlMutex = xSemaphoreCreateMutex();
if (!_controlMutex) {
Log.println("[PanelStreamer] FATAL: Failed to create control mutex!");
}
// Calculate buffer sizes
_panelBufferSize = FULL_WIDTH * FULL_HEIGHT;
_compressedBufferSize = _panelBufferSize * 3; // Worst case: control byte + 2 bytes per pixel
Log.printf("[PanelStreamer] Allocating buffers: Panel=%d bytes, Compressed=%d bytes\n",
_panelBufferSize * sizeof(uint16_t), _compressedBufferSize);
// Allocate buffers in PSRAM
_panelBuffer = (uint16_t*)ps_malloc(_panelBufferSize * sizeof(uint16_t));
_compressedBuffer = (uint8_t*)ps_malloc(_compressedBufferSize);
if (!_panelBuffer || !_compressedBuffer) {
Log.println("[PanelStreamer] FATAL: Failed to allocate buffers in PSRAM!");
Log.println("[PanelStreamer] FATAL: Failed to allocate buffers in PSRAM!");
} else {
Log.printf("[PanelStreamer] Buffers allocated successfully\n");
Log.printf("[PanelStreamer] Buffers allocated: Panel=%d bytes, Compressed=%d bytes\n",
_panelBufferSize * sizeof(uint16_t), _compressedBufferSize);
}
// Create WebSocket server on port 81
Log.println("[PanelStreamer] Creating WebSocket server on port 81...");
_wsServer = new WebSocketsServer(81);
if (!_wsServer) {
Log.println("[PanelStreamer] FATAL: Failed to create WebSocket server!");
return;
}
_wsServer->onEvent(webSocketEvent);
_wsServer->begin();
// Enable keepalive/ping to detect stale connections
// Ping interval: 15 seconds, timeout: 3 pings (45 seconds total)
_wsServer->enableHeartbeat(15000, 3000, 3);
Log.println("[PanelStreamer] WebSocket server started successfully");
Log.println("[PanelStreamer] WebSocket server started on port 81 with keepalive enabled");
}
PanelStreamer::~PanelStreamer() {
stop();
if (_wsServer) {
delete _wsServer;
}
if (_panelBuffer) {
free(_panelBuffer);
}
if (_compressedBuffer) {
free(_compressedBuffer);
}
if (_controlMutex) {
vSemaphoreDelete(_controlMutex);
}
_instance = nullptr;
}
void PanelStreamer::begin() {
Log.println("[PanelStreamer::begin] Starting...");
if (_running) {
Log.println("[PanelStreamer::begin] Already running, skipping");
return;
}
if (xSemaphoreTake(_controlMutex, portMAX_DELAY) == pdTRUE) {
_running = true;
xSemaphoreGive(_controlMutex);
}
// Determine which core to use (opposite of Arduino core)
BaseType_t app_core = xPortGetCoreID();
BaseType_t stream_core = (app_core == 0) ? 1 : 0;
Log.printf("[PanelStreamer::begin] Creating task on core %d (Arduino core: %d)\n", stream_core, app_core);
// Create task pinned to non-Arduino core
BaseType_t result = xTaskCreatePinnedToCore(
streamerTaskWrapper,
"PanelStreamer",
8192, // Stack size
this,
1, // Priority
&_taskHandle,
stream_core
);
if (result != pdPASS) {
Log.printf("[PanelStreamer::begin] FATAL: Failed to create task, result=%d\n", result);
_running = false;
return;
}
Log.printf("[PanelStreamer::begin] Task created successfully, handle=%p\n", _taskHandle);
Log.printf("[PanelStreamer] Task started on core %d (Arduino core: %d)\n", stream_core, app_core);
}
void PanelStreamer::stop() {
if (!_running) return;
if (xSemaphoreTake(_controlMutex, portMAX_DELAY) == pdTRUE) {
_running = false;
xSemaphoreGive(_controlMutex);
}
if (_taskHandle) {
vTaskDelete(_taskHandle);
_taskHandle = nullptr;
}
Log.println("[PanelStreamer] Task stopped");
}
uint8_t PanelStreamer::getClientCount() {
if (!_wsServer) return 0;
uint8_t count = 0;
for (uint8_t i = 0; i < MAX_CLIENTS; i++) {
if (_wsServer->clientIsConnected(i)) {
count++;
}
}
return count;
}
void PanelStreamer::streamerTaskWrapper(void* param) {
PanelStreamer* streamer = static_cast<PanelStreamer*>(param);
streamer->streamerTask();
}
void PanelStreamer::streamerTask() {
Log.printf("[PanelStreamer::streamerTask] Task running on core %d\n", xPortGetCoreID());
Log.printf("[PanelStreamer] Task running on core %d\n", xPortGetCoreID());
unsigned long lastPanelStreamMs = 0;
unsigned long lastDebugMs = 0;
unsigned long loopCount = 0;
Log.println("[PanelStreamer::streamerTask] Entering main loop");
while (_running) {
loopCount++;
// Process WebSocket events
if (_wsServer) {
_wsServer->loop();
} else {
Log.println("[PanelStreamer::streamerTask] ERROR: _wsServer is NULL!");
}
// Check if any clients are connected
uint8_t clientCount = getClientCount();
// Debug output every 10 seconds
unsigned long now = millis();
if (now - lastDebugMs >= 10000) {
Log.printf("[PanelStreamer::streamerTask] Running, loops=%lu, clients=%d\n", loopCount, clientCount);
// Also log individual client status for debugging
if (clientCount > 0) {
for (uint8_t i = 0; i < 8; i++) { // Check first 8 slots
if (_wsServer->clientIsConnected(i)) {
Log.printf("[PanelStreamer::streamerTask] - Client #%d connected\n", i);
}
}
}
lastDebugMs = now;
}
if (clientCount == 0) {
// No clients, sleep longer
vTaskDelay(pdMS_TO_TICKS(500));
continue;
}
// Only log when actually streaming (every 10 seconds when clients are connected)
if (now - lastDebugMs >= 10000) {
Log.printf("[PanelStreamer::streamerTask] Clients connected: %d\n", clientCount);
}
// Stream log messages
sendLogMessages();
// Stream panel snapshot at defined FPS
if (now - lastPanelStreamMs >= PANEL_STREAM_INTERVAL_MS) {
sendPanelSnapshot();
lastPanelStreamMs = now;
}
// Small delay to prevent task hogging
vTaskDelay(pdMS_TO_TICKS(50));
}
Log.println("[PanelStreamer::streamerTask] Task exiting");
Log.println("[PanelStreamer] Task exiting");
vTaskDelete(nullptr);
}
void PanelStreamer::sendPanelSnapshot() {
if (!_panelManager || !_panelBuffer || !_compressedBuffer || !_wsServer) {
return;
}
// Copy panel buffer (thread-safe)
if (!_panelManager->copyFullPanelBuffer(_panelBuffer, _panelBufferSize)) {
return;
}
// Compress with RLE
size_t compressedSize = compressRLE(_panelBuffer, _panelBufferSize,
_compressedBuffer, _compressedBufferSize);
if (compressedSize > 0) {
// Send as binary WebSocket message to all connected clients
_wsServer->broadcastBIN(_compressedBuffer, compressedSize);
}
}
void PanelStreamer::sendLogMessages() {
if (!_wsServer) {
// Use Serial directly to avoid recursive logging
Serial.println("[PanelStreamer::sendLogMessages] No WebSocket server!");
return;
}
// Get new log lines
PsramVector<PsramString> newLines;
size_t count = Log.getNewLines(newLines);
if (count == 0) return;
// Use Serial directly to avoid recursive logging (these debug messages would create infinite loop)
// Serial.printf("[PanelStreamer::sendLogMessages] Sending %d log lines\n", count);
// Send each line as JSON text message using PSRAM allocator
struct SpiRamAllocator : ArduinoJson::Allocator {
void* allocate(size_t size) override { return ps_malloc(size); }
void deallocate(void* pointer) override { free(pointer); }
void* reallocate(void* ptr, size_t new_size) override { return ps_realloc(ptr, new_size); }
};
for (const auto& line : newLines) {
// Create JSON wrapper with PSRAM allocator
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
doc["type"] = "log";
doc["data"] = line.c_str();
// Use stack buffer for serialization
char jsonBuffer[512];
size_t len = serializeJson(doc, jsonBuffer, sizeof(jsonBuffer));
if (len > 0 && len < sizeof(jsonBuffer)) {
// Send as text message to all connected clients
_wsServer->broadcastTXT(jsonBuffer, len);
}
}
}
size_t PanelStreamer::compressRLE(const uint16_t* input, size_t inputSize,
uint8_t* output, size_t outputMaxSize) {
if (!input || !output || inputSize == 0 || outputMaxSize == 0) {
return 0;
}
size_t outPos = 0;
size_t inPos = 0;
while (inPos < inputSize && outPos < outputMaxSize - 5) {
uint16_t pixel = input[inPos];
// Skip black pixels (0x0000) - they stay dark in the visualization
// We need to track position, so we'll encode skips too
if (pixel == 0x0000) {
// Count consecutive black pixels
uint16_t skipCount = 0;
while (inPos < inputSize && input[inPos] == 0x0000 && skipCount < 65535) {
skipCount++;
inPos++;
}
// If we have skips, encode them: [0x00][skip_count_high][skip_count_low]
if (skipCount > 0) {
output[outPos++] = 0x00; // Marker for skip
output[outPos++] = (skipCount >> 8) & 0xFF;
output[outPos++] = skipCount & 0xFF;
}
continue;
}
// Count consecutive same-colored pixels (max 255)
uint8_t count = 1;
while (inPos + count < inputSize &&
input[inPos + count] == pixel &&
input[inPos + count] != 0x0000 && // Don't include blacks
count < 255) {
count++;
}
// Encode: [count][high_byte][low_byte]
output[outPos++] = count;
output[outPos++] = (pixel >> 8) & 0xFF; // High byte
output[outPos++] = pixel & 0xFF; // Low byte
inPos += count;
}
return outPos;
}
void PanelStreamer::webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
Log.printf("[WebSocket] Event received: type=%d, num=%u\n", type, num);
switch (type) {
case WStype_DISCONNECTED:
Log.printf("[WebSocket] Client #%u disconnected\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = _instance->_wsServer->remoteIP(num);
Log.printf("[WebSocket] Client #%u connected from %d.%d.%d.%d\n",
num, ip[0], ip[1], ip[2], ip[3]);
// Check max clients
if (_instance->getClientCount() > MAX_CLIENTS) {
Log.printf("[WebSocket] Max clients reached, disconnecting #%u\n", num);
_instance->_wsServer->disconnect(num);
}
}
break;
case WStype_TEXT:
// Client sent text message (could be control commands in future)
Log.printf("[WebSocket] Client #%u sent: %s\n", num, payload);
break;
case WStype_BIN:
// Binary messages not expected from client
break;
case WStype_PING:
Log.printf("[WebSocket] Client #%u ping\n", num);
break;
case WStype_PONG:
Log.printf("[WebSocket] Client #%u pong\n", num);
break;
default:
break;
}
}