pitrix/src/websockets.cpp

55 lines
1.4 KiB
C++

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include "config.h"
#include "websockets.h"
#include "my_fastled.h"
#include "functions.h"
#include "effects.h"
WebSocketsServer ws = WebSocketsServer(81);
void ws_event(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
if (type == WStype_CONNECTED) {
LOGln("Websockets * Client connected.");
} else if (type == WStype_DISCONNECTED) {
LOGln("Websockets * Client disconnected.");
} else if (type == WStype_TEXT) {
String msg = String((char*)payload);
LOGln("Websockets * Received: %s", msg.c_str());
if (msg.startsWith("E:")) {
change_current_effect(msg.substring(2));
}
}
}
void websocket_setup() {
ws.begin();
ws.onEvent(ws_event);
}
void send_data() {
uint16_t _size = LED_WIDTH * LED_HEIGHT * 3 + 4;
uint8_t* _buffer = new uint8_t[_size];
_buffer[0] = LED_WIDTH;
_buffer[1] = LED_HEIGHT;
_buffer[2] = 255;
for (uint8_t y=0; y<LED_HEIGHT; y++) for(uint8_t x=0; x<LED_WIDTH; x++) {
uint16_t index = XYsafe(x, y);
CRGB pixel = leds[index];
_buffer[3 + (y*LED_WIDTH + x)*3 + 0] = (pixel.r==255 ? 254 : pixel.r);
_buffer[3 + (y*LED_WIDTH + x)*3 + 1] = (pixel.g==255 ? 254 : pixel.g);
_buffer[3 + (y*LED_WIDTH + x)*3 + 2] = (pixel.b==255 ? 254 : pixel.b);
}
_buffer[_size - 1] = 255;
ws.broadcastBIN(_buffer, _size);
delete _buffer;
}
void websocket_loop() {
if (ws.connectedClients()>0) {
send_data();
}
ws.loop();
}