#include <ESP8266React.h>
/*
#include <LightMqttSettingsService.h>
#include <LightStateService.h>
*/
#include <FanStateService.h>

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS              14
#define SERIAL_BAUD_RATE          115200
#define PWM_PROBE_MS              5000

OneWire oneWire1(ONE_WIRE_BUS);
DallasTemperature sensor_intake(&oneWire1);
AsyncWebServer server(80);

ESP8266React    esp8266React(&server);
FanStateService fanStateService = FanStateService(&server,esp8266React.getFS(),esp8266React.getSecurityManager());


struct fanMonitor {
  unsigned long last_poll;
  unsigned int  rpmcount;
  unsigned int  last_time;    
  };

void ICACHE_RAM_ATTR handleInterrupt( struct fanMonitor &fm ) {
  fm.rpmcount++;
  if( fm.rpmcount > 100 ) {
    fm.rpmcount=0;
    Serial.println("100 RPM");
  }
}

fanMonitor fm;

void setup() {
  // start serial and filesystem
  Serial.begin(SERIAL_BAUD_RATE);

  // start the framework and demo project
  esp8266React.begin();

  // load the initial light settings
  fanStateService.begin();
  sensor_intake.begin();

//  Serial.println(" FAN GPIO = " + fanStateService.fan);

/*
  // start the light service
  lightMqttSettingsService.begin();
*/

  // start the server
  server.begin();

  fm.last_poll=millis();

  pinMode(14,INPUT); // 14 = D5
  // attachInterrupt(digitalPinToInterrupt(14), handleInterrupt, RISING);
  // attachInterrupt(14,handleInterrupt,RISING);
  
}



void loop() {
  // run the framework's loop function

  if( ( millis() - fm.last_poll ) > PWM_PROBE_MS ) {
    fm.last_poll = millis();
    Serial.print((String) fm.last_poll + " - Compute");
    sensor_intake.requestTemperatures();
    float T1 = sensor_intake.getTempCByIndex(0);
    float T2 = sensor_intake.getTempCByIndex(1);
    Serial.print("Intake: " + (String) T1 + " - " + (String) T2 + "\n");
    
    }

  esp8266React.loop();
}
