Posted in

Photo transfer via cassette tape – ePaper v1

This is the code for the first version of the ePaper.
See here for the full write-up of the project at this stage

#include <Arduino.h>
#include <WiFi.h>
#include <Seeed_GFX.h>

Seeed_GFX display(Seeed_Product::Seeed_ePaper_13INCH3_C);

// 📶 ACCESS POINT CONFIGURATION (Must match the Receiver exactly!)
const char* ap_ssid     = "Cassette_ePaper";
const char* ap_password = "RetroOverdracht80"; // Minimum of 8 characters required

// Start a raw TCP server on port 8080 (bypasses the HTTP webserver layer)
WiFiServer tcpServer(8080);

// 📐 SCREEN AND BUFFER SIZE
const int IMG_WIDTH  = 400;
const int IMG_HEIGHT = 300;
const size_t EXPECTED_DATA_SIZE = (IMG_WIDTH * IMG_HEIGHT) / 2; // 2 nibbles per byte
const int offsetX = (1600 - (IMG_WIDTH * 2)) / 2;
const int offsetY = (1200 - (IMG_HEIGHT * 2)) / 2;

// Pointers and variables for PSRAM memory management
uint8_t* psramBuffer = nullptr;
const size_t MAX_BUFFER_SIZE = 960000; // Your limit of 960,000 bytes

const uint16_t EPD_COLORS[] = {
    TFT_WHITE, TFT_BLACK, TFT_RED, TFT_YELLOW, TFT_GREEN, TFT_BLUE
};

// =========================================================================
// Renders the received 4-bit array directly onto the ePaper display canvas
// =========================================================================
void drawBufferToEPaper(uint8_t* buffer) {
    Serial.println("🎨 [ePaper] Filling screen with data received from Tape-Receiver...");
    display.fillScreen(TFT_WHITE);

    // Draw a frame if the photo is smaller than the screen canvas area
    display.fillRoundRect(offsetX-10, offsetY-10, (IMG_WIDTH*2)+20, (IMG_HEIGHT*2)+20, 2, TFT_RED);
    display.fillRoundRect(offsetX-8, offsetY-8, (IMG_WIDTH*2)+16, (IMG_HEIGHT*2)+16, 2, TFT_WHITE);

    int byteIdx = 0;
    for (int y = 0; y < IMG_HEIGHT; y++) {
        for (int x = 0; x < IMG_WIDTH; x += 2) {
            // Unpack 2 pixels (4-bit nibbles) from a single 8-bit byte
            uint8_t dataByte = buffer[byteIdx++];
            uint8_t p1Idx = (dataByte >> 4) & 0x0F;
            uint8_t p2Idx = dataByte & 0x0F;

            // Boundary check: Out of range color indices fallback to TFT_BLACK (1)
            if (p1Idx > 5) p1Idx = 1;
            if (p2Idx > 5) p2Idx = 1;

            // Draw Pixel 1 (Upscaled to a 2x2 block) at native 1200x1600 resolution
            int epdX1 = (x * 2) + offsetX;
            int epdY1 = (y * 2) + offsetY;
            display.drawPixel(epdX1,     epdY1,     EPD_COLORS[p1Idx]);
            display.drawPixel(epdX1 + 1, epdY1,     EPD_COLORS[p1Idx]);
            display.drawPixel(epdX1,     epdY1 + 1, EPD_COLORS[p1Idx]);
            display.drawPixel(epdX1 + 1, epdY1 + 1, EPD_COLORS[p1Idx]);

            // Draw Pixel 2 (Upscaled to a 2x2 block)
            int epdX2 = ((x + 1) * 2) + offsetX;
            display.drawPixel(epdX2,     epdY1,     EPD_COLORS[p2Idx]);
            display.drawPixel(epdX2 + 1, epdY1,     EPD_COLORS[p2Idx]);
            display.drawPixel(epdX2,     epdY1 + 1, EPD_COLORS[p2Idx]);
            display.drawPixel(epdX2 + 1, epdY1 + 1, EPD_COLORS[p2Idx]);        }
    }

    Serial.println("🎨 [ePaper] Physical refresh cycle started...");
    display.update();
    Serial.println("✅ [ePaper] Successfully updated!");
}

// =========================================================================
// Callback function: Triggered when a station establishes a CONNECTION
// =========================================================================
void onStationConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
    Serial.print("📡 [WiFi] Client connected! MAC Address: ");

    // Print the unique hardware MAC address of the connecting device
    for (int i = 0; i < 6; i++) {
        Serial.printf("%02X", info.wifi_ap_staconnected.mac[i]);
        if (i < 5) Serial.print(":");
    }
    Serial.println();
}

// =========================================================================
// Callback function: Triggered when a station DISCONNECTS
// =========================================================================
void onStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
    Serial.print("📡 [WiFi] Client disconnected! MAC Address: ");

    for (int i = 0; i < 6; i++) {
        Serial.printf("%02X", info.wifi_ap_stadisconnected.mac[i]);
        if (i < 5) Serial.print(":");
    }
    Serial.println();
}

// =========================================================================
// Receives the Raw TCP Stream
// =========================================================================
void handleTcpStream() {
    WiFiClient client = tcpServer.available();

    if (client) {
        Serial.println("\n🌐 [Server] Upload Connection initiated, Client connected via TCP socket!");
        
        // 1. Read the incoming Content-Length prefix sent by the client as 4 raw bytes (uint32_t)
        uint32_t totalLength = 0;
        unsigned long startTime = millis();
        
        while (client.connected() && client.available() < 4) {
            if (millis() - startTime > 3000) {
                Serial.println("❌ [Server] Timeout while reading incoming data size configuration.");
                client.stop();
                return;
            }
            delay(1);
        }
        
        client.read((uint8_t*)&totalLength, 4);
        Serial.printf("📥 [Server] Expected data payload size: %d bytes\n", totalLength);

        if (totalLength > MAX_BUFFER_SIZE || totalLength == 0) {
            Serial.println("❌ [Server] Invalid data payload size window.");
            client.stop();
            return;
        }

        // 2. Dynamically allocate required memory buffer inside the PSRAM space
        if (psramBuffer != nullptr) { free(psramBuffer); psramBuffer = nullptr; }
        psramBuffer = (uint8_t*)ps_malloc(totalLength + 1);
        
        if (psramBuffer == nullptr) {
            Serial.println("❌ [Server] PSRAM allocation routine failed!");
            client.stop();
            return;
        }

        // 3. Stream data sequentially from the active connection block by block
        size_t bytesRead = 0;
        unsigned long lastDataTime = millis();
        
        while (bytesRead < totalLength && (client.connected() || client.available())) {
            int availableBytes = client.available();
            if (availableBytes > 0) {
                size_t toRead = availableBytes;
                if (bytesRead + toRead > totalLength) {
                    toRead = totalLength - bytesRead;
                }

                size_t actualRead = client.read(psramBuffer + bytesRead, toRead);
                bytesRead += actualRead;
                lastDataTime = millis();
            } else {
                if (millis() - lastDataTime > 5000) {
                    Serial.println("❌ [Server] Timeout encountered during active stream!");
                    break;
                }
                delay(1);
            }
        }

        // 4. Validate output completion and transmit completion acknowledgement feedback to client
        if (bytesRead == totalLength) {
            Serial.printf("✅ [Server] Total successfully received: %d bytes.\n", bytesRead);
            psramBuffer[bytesRead] = '\0'; // Inject null-terminator for safety strings processing
            
            // Send back a clean success verification byte status indicator to client
            client.write((uint8_t)0x01); 
            
        } else {
            Serial.printf("❌ [Server] Incomplete transmission. Received %d out of %d bytes.\n", bytesRead, totalLength);
            client.write((uint8_t)0x00); // Send failure byte indicator back to client
            free(psramBuffer);
            psramBuffer = nullptr;
        }
        
        delay(1);
        client.stop();
        Serial.println("🌐 [Server] Connection with client safely closed.");
        delay(10);

        if (bytesRead == totalLength) {
            // =========================================================================
            // DATA PROCESSING ZONE
            // =========================================================================
            for(int i=0; i<totalLength; i++) {
                // Print exclusively the 2 hex characters of the byte (e.g., "01" or "50")
                // Start a clean new terminal line log trace structure after every 40 bytes
                if (i % 40 == 0) {
                    Serial.printf("\n➡️ [%06d] ", i);
                }
                Serial.printf("%02X ", psramBuffer[i]);
            }
            Serial.println();

            drawBufferToEPaper(psramBuffer);

            // =========================================================================
            // Crucial: Always perform free(psramBuffer); psramBuffer = nullptr; here!
            // =========================================================================
            free(psramBuffer);
            psramBuffer = nullptr;
        }
    }
}

// =========================================================================
// 🚀 Initialization (SETUP)
// =========================================================================
void setup() {
    Serial.begin(115200);
    delay(1000);
    Serial.println("\nSystem booting...");

    psramInit();

    if (!display.begin()) {
        Serial.println(display.lastResult().message);
        return;
    }

    Serial.println("✅ [ePaper] Setup complete!");
    Serial.println("🎨 [ePaper] Filling screen canvas with welcome display layout...");

    // Apply software-packed rotation BEFORE clearing or allocating canvas layers
    // 0: Default Portrait mode (1200 x 1600)
    // 1: Standard Landscape mode (1600 x 1200)
    // 2: Inverted Portrait mode (1200 x 1600)
    // 3: Inverted Landscape mode (1600 x 1200)
    display.setRotation(3);
	
	Serial.println("\n📡 [WiFi] Initializing Access Point hosting routine...");

	// Register the Wi-Fi asynchronous event callbacks BEFORE activating the access point infrastructure
	WiFi.onEvent(onStationConnected, ARDUINO_EVENT_WIFI_AP_STACONNECTED);
	WiFi.onEvent(onStationDisconnected, ARDUINO_EVENT_WIFI_AP_STADISCONNECTED);

	// Configure the ESP32 into a dedicated Access Point topology structure
	WiFi.mode(WIFI_AP);
	if (!WiFi.softAP(ap_ssid, ap_password)) {
		Serial.println("❌ [WiFi] Soft AP creation failed.");
		while (1);
	}
	WiFi.setTxPower(WIFI_POWER_8_5dBm);
	WiFi.setSleep(false);
	
	Serial.print("✅ [WiFi] Access Point is online!");
	Serial.print(" SSID: "); Serial.print(ap_ssid);
	Serial.print(", IP Address: http://"); Serial.println(WiFi.softAPIP()); // This will default to 192.168.4.1

	tcpServer.begin();
}

// =========================================================================
// 🔄 Main program (LOOP)
// =========================================================================
void loop() {
	handleTcpStream(); // Continuously poll and intercept incoming raw TCP network connections
	delay(5);
}

Leave a Reply

Your email address will not be published. Required fields are marked *