#include <Arduino.h>
#include <QNEthernet.h>

using namespace qindesign::network;

// Network config
IPAddress ip(192, 168, 1, 177);   // change to your network
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

EthernetUDP udp;
const uint16_t localPort = 2222;   // EtherNet/IP uses 2222 (good test)

void setup() {
    Serial.begin(115200);
    delay(2000);

    Serial.println("Starting Ethernet...");

    Ethernet.begin(ip, subnet, gateway);

    if (!Ethernet.linkStatus()) {
        Serial.println("Ethernet cable not connected!");
    }

    Serial.print("IP: ");
    Serial.println(Ethernet.localIP());

    udp.begin(localPort);

    Serial.print("Listening on UDP port: ");
    Serial.println(localPort);
}

void loop() {
    int packetSize = udp.parsePacket();

    if (packetSize) {
        Serial.print("Received packet: ");
        Serial.println(packetSize);

        char buffer[512];
        int len = udp.read(buffer, sizeof(buffer));

        if (len > 0) {
            buffer[len] = 0;
        }

        Serial.print("Data: ");
        Serial.println(buffer);

        // Echo back
        udp.beginPacket(udp.remoteIP(), udp.remotePort());
        udp.write((const uint8_t*)"ACK", 3);
        udp.endPacket();

        Serial.println("Sent ACK");
    }
}