#include <ZsutEthernet.h>
#include <ZsutEthernetUdp.h>
#include <ZsutFeatures.h>

#define MAX_BUFFER 256

byte mac[] = {
  0x01, 0xFF, 0xAA, 0x12, 0x34, 0x02
};
ZsutEthernetUDP Udp;
ZsutIPAddress address_ip=ZsutIPAddress(192,168,56,101);
unsigned int localPort = 9993;
unsigned int remotePort = 9998;

unsigned char packetBuffer[MAX_BUFFER];

unsigned char getResultBuffer[MAX_BUFFER] = "\x0F\0\0\0\4\x0Btemperature\1\x84";
int len=0;

int num_up = 0;
int num_down = 0;

void setup() {
  ZsutPinMode(ZSUT_PIN_D4, OUTPUT);
  while (!Serial) {
  }

  ZsutEthernet.begin(mac);
  Serial.println(ZsutEthernet.localIP());
  Serial.println(localPort);
  Udp.begin(localPort);
  
  ZsutDigitalWrite(ZSUT_PIN_D4, LOW);
}

int i = 0;

void loop() { 
  ++i; 
  len = 19;
  Udp.beginPacket(address_ip, remotePort);
  int r=Udp.write(getResultBuffer, len);
  Udp.endPacket();

  delay(10);
  
  int packetSize=Udp.parsePacket();
  if(packetSize){
    int r=Udp.read(packetBuffer, MAX_BUFFER);
    int packet_len = packetBuffer[0] | (packetBuffer[1] << 8);
    if(packet_len == 0) {
    }
    else {
      num_up += packetBuffer[18] == 1;
      num_down += packetBuffer[18] == 0;
    }
  }
  if(i == 50) { // wykonywanie około co sekundę
    Serial.print("Liczba aktywacji alarmu: ");
    Serial.println(num_up);
    Serial.print("Liczba dezaktywacji alarmu: ");
    Serial.println(num_down);
    i = 0;
  }
  delay(10);
}
