#include "TCP.h" #include "SPIFFS.h" #include // Constructor TCP::TCP(const char* ssid, const char* password, const char* host, uint16_t port) : ssid(ssid), password(password), host(host), port(port) { } // Connect to WiFi void TCP::connectWiFi(TFT_eSPI& tf) { // Set pointer to tft tft = &tf; tft->setCursor(0, 0, 2); tft->setTextColor(TFT_WHITE,TFT_BLACK); tft->println("Connecting to: "); tft->print(ssid); delay(1000); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED ) { delay(1000); } tft->println("\n\nConnected to WiFi!"); delay(1000); tft->println(WiFi.localIP()); delay(1000); } void TCP::testConnection(){ tft->println("\nPolling server.."); int yPos = tft->getCursorY(); // Store the current Y position while (!client.connected()) { tft->setCursor(0, yPos); tft->fillRect(0, yPos, tft->width(), 32, TFT_BLACK); delay(50); if (client.connect(host, port)) { tft->setTextColor(TFT_GREEN); tft->print("\nCONNECTED"); delay(2000); tft->fillScreen(TFT_BLACK); } else { tft->setTextColor(TFT_RED); tft->println("\nFAILED"); delay(250); } } } // Send array of floats void TCP::sendData(float& potData, int& emoteIndex) { if(client.connect(host, port)){ // 1 float & 1 integer = 4 + 4 bytes (32-bit) // Create buffer uint8_t data[8]; // Convert values to bytes memcpy(&data[0], &potData, sizeof(float)); memcpy(&data[4], &emoteIndex, sizeof(int)); // Send bytes to server size_t bytesSent = client.write(data, sizeof(data)); } else { tft->setTextColor(TFT_BLACK, TFT_RED); tft->drawCentreString("LOST", 62, 80, 1); delay(1000); return; } } void TCP::receiveImage() { client.setTimeout(500); uint8_t* imageData = new uint8_t[w * h * 3]; // Allocate memory for a 64x80 image // Read bytes from the client and store the count of bytes received size_t bytesRead = client.readBytes(imageData, w * h * 3); if (bytesRead == w * h * 3) { Serial.println("Image data received."); // Create a buffer for RGB565 line data uint16_t* lineBuffer = new uint16_t[w]; // Buffer to hold one line of RGB565 data // Loop through height (80) for (int y = 0; y < h; y++) { // Loop through width (64) for (int x = 0; x < w; x++) { // Calculate the index in the imageData array int index = (y * w + x) * 3; // Each pixel has 3 bytes (RGB) uint8_t r = imageData[index]; // Red channel uint8_t g = imageData[index + 1]; // Green channel uint8_t b = imageData[index + 2]; // Blue channel // Convert RGB to RGB565 uint16_t rgb565 = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); // Swap bytes rgb565 = (rgb565 >> 8) | (rgb565 << 8); // Set the pixel in the line buffer lineBuffer[x] = rgb565; } // Push the converted line to the TFT display tft->pushImage(0, y, w, 1, lineBuffer); } // Clean up allocated line buffer delete[] lineBuffer; } else { Serial.print("Error: Expected "); } delete[] imageData; // Clean up }