#include <SPI.h>
#include <Ethernet3.h>

// Configure MAC address and IP:
byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};

// the real one IPAddress ip(10, 11, 1, 22); // Static IP


// Define CS and RST pins:
#define W5500_CS_PIN 10 // 8 in E LEGO
#define W5500_RST_PIN 9 //10 in E LEGO

IPAddress serverIP(169, 254, 246, 15);  // Computer
IPAddress W5500_ip(169, 254, 246, 16); // Change the last digit

// Don't change
const int port = 5005;

// Definitions for interrupt sequence
int interrupt_pin = 2; // 24 in E LEGO
volatile int interrupt_flag;

EthernetClient client;

void setup() {
  Serial.begin(9600);
  
  // Reset W5500 
  pinMode(W5500_RST_PIN, OUTPUT);
  digitalWrite(W5500_RST_PIN, HIGH);
  delay(250);
  digitalWrite(W5500_RST_PIN, LOW);
  delay(250);
  digitalWrite(W5500_RST_PIN, HIGH);
  delay(1000);

  // Initialize Ethernet:
  Ethernet.init(W5500_CS_PIN);
  Ethernet.begin(mac, W5500_ip);
  delay (1500);

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

  // Send a message through socket
  if (client.connect (serverIP, port)) {
    client.write("test");
    client.stop();
    Serial.print("Test Message sent");
  } else {
    Serial.print ("Connection failed");
   }


  // Interrupt sequence
  pinMode(interrupt_pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interrupt_pin), ISR_button, CHANGE);
}

void loop() {
  // put your main code here, to run repeatedly:

  if (interrupt_flag) {
      interrupt_flag = 0;

      if (client.connect(serverIP, port)) {
        client.println("Leak");
        client.stop();
        Serial.println("Leak update sent to server.");
      } else {
        Serial.println("Connection failed.");
      }
  }

  delay(10);
}

void ISR_button () {
  interrupt_flag = 1;
}