#include <WiFi.h>;
#include <WiFiUdp.h>;
#include <coap-simple.h>;

#define THRESHOLD_AVERAGE 50
#define PIN_LED 18

//const char* ssidWifi = "Rete di Antonio";
//const char* passwordWifi = "7EKZ48UYZ";
int msgid = 0;
double reader = 0;
const int numberReaders = 20;
double listReaders[numberReaders];
int i = 0;
double minimum = 0;
double maximum = 0;
double sumValue = 0;
double meanValue = 0;
WiFiUDP udp;
Coap coap(udp);

void connectWifi(){
  //WiFi.begin(ssidWifi,passwordWifi);
  WiFi.begin("Wokwi-GUEST","",6);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connection attempt...");
    delay(500);
  }
  Serial.print("WiFi connected with the ip address ");
  Serial.println(WiFi.localIP());
}

//callback execute when the esp32 receive a response from the server
void callbackResponse(CoapPacket &packet,IPAddress ip,int port){
  Serial.println("Received a packet on the coap connection");
  char p[packet.payloadlen + 1];
  memcpy(p,packet.payload,packet.payloadlen);
  p[packet.payloadlen] = NULL;
  String message(p);
  coap.sendResponse(ip,port,packet.messageid,"ACKmessage");
  reader = (double)(message);
  if(i < numberReaders){
    Serial.println(reader);
    listReaders[i] = reader;
    i++;
  }else{
    for(int j = 0;j < numberReaders;j++){
      if(maximum < listReaders[j]){
        maximum = listReaders[j];
      }
      if(minimum > listReaders[j]){
        minimum = listReaders[j];
      }
      sumValue += listReaders[j];
    }
    meanValue = sumValue / numberReaders;
    Serial.print("Maximum: ");
    Serial.println(maximum);
    Serial.print("Minimum: ");
    Serial.println(minimum);
    Serial.print("Mean: ");
    Serial.println(meanValue);
    if(meanValue < THRESHOLD_AVERAGE){
      digitalWrite(PIN_LED,HIGH);
    }else{
      digitalWrite(PIN_LED,LOW);
    }
    for(int j = 0;j < numberReaders;j++){
      listReaders[j] = 0;
    }
    i = 0;
    minimum = 0;
    maximum = 0;
    sumValue = 0;
    meanValue = 0;
  }
}

//callback execute when the esp32 is a client and send a request
void callbackClient(CoapPacket &packet,IPAddress ip,int port){
  Serial.println("Sended a packet on the coap connection");
  char p[packet.payloadlen + 1];
  memcpy(p,packet.payload,packet.payloadlen);
  p[packet.payloadlen] = NULL;
  Serial.println(p);
}

void setup(){
  pinMode(PIN_LED, OUTPUT);
  Serial.begin(9600);
  connectWifi();
  coap.server(callbackResponse,"light");
  coap.response(callbackClient);
  coap.start();
}

void loop(){
  Serial.println("Send a request to the coap server");
  msgid = coap.get(IPAddress(130,136,2,70),5683,"time");
  Serial.print("Request with the id ");
  Serial.print(msgid);
  Serial.println(" sended correctly.");
  delay(100);
  coap.loop();
}
$abcdeabcde151015202530354045505560fghijfghij