#include <SPI.h>
#include <Ethernet.h>
#include "Adafruit_SHT31.h"

Adafruit_SHT31 sht31 = Adafruit_SHT31();

#define SHT31_RST_PIN 16

void reset_SHT31() {
  pinMode(SHT31_RST_PIN, OUTPUT);
  digitalWrite(SHT31_RST_PIN, LOW);
  delay(10);
  digitalWrite(SHT31_RST_PIN, HIGH);
  delay(10);
}

// MAC and IP configuration
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 11, 1, 46);
IPAddress gateway(10, 11, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Server to connect to
IPAddress server(10, 44, 1, 238);
const int serverPort = 5005; // Change to the port your server listens on

EthernetClient client;

char T[8];
char H[8];
char message[20];

void setup() {

  // Initialize Ethernet
  Serial.begin(9600);
  while (!Serial); // Wait for Serial (only needed for native USB boards)

  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  delay(1000); // Give Ethernet shield time to initialize

  Serial.println("Connecting to server");

  if (client.connect(server, serverPort)) {
    client.write("Connection check");
    Serial.println("Connection successful");
    client.stop();
  } else {
    Serial.println("Connection failed");
  }


  // Initialize SHT31
  if (!sht31.begin(0X44)) {
    Serial.println("Couldn't find SHT31");
    while (1) delay(100);
  }
  Serial.println("SHT31 Found");

}



void loop() {
  // put your main code here, to run repeatedly:
  // Measure temp. and humidity every 30 seconds
  delay(15000);
  float t = sht31.readTemperature();
  float h = sht31.readHumidity();

  // Report temperature to Eilon's computer
  if (client.connect(server, serverPort)) {
    client.write("Temp");
    client.stop();
  } else {
    Serial.println("Connection failed");
  }

  if (client.connect(server, serverPort)) {
    if (!isnan(t)) {
      dtostrf(t, 6, 2, T);
      snprintf(message, sizeof(message), "T %s", T);
      client.write(T);
      client.stop();
    }
  } else {
    Serial.println("Connection failed");
  }

  // Report humidity to Eilon's computer
  delay(15000);
  if (client.connect(server, serverPort)) {
    client.write("Humidity");
    client.stop();
  } else {
    Serial.println("Connection failed");
  }
  
  if (client.connect(server, serverPort)) {
    if (!isnan(h)) {
      dtostrf(h, 6, 2, H);
      snprintf(message, sizeof(message), "H %s", H);
      client.write(H);
      client.stop();
      Serial.println("message sent");
    }
  } else {
    Serial.println("Connection failed");
  }

}
