#include <Wire.h>
#include <Adafruit_SGP40.h>
#include <WiFiS3.h>
#include <WiFiUdp.h>
Adafruit_SGP40 sgp;
WiFiUDP Udp;
char ssid[] = "SSID";
char pass[] = "password";
IPAddress remoteIP(192, 168, 2, 101);
const int remotePort = 50007;
const int listenPort = 50008;
const float A = 0.0013141075651;
const float B = 0.000088450246618;
const float C = 0.00000066945071114;
const int analogPin = A0;
const float Vcc = 5.0;
const float R_fixed = 1000.0;
bool isCounting = false;
unsigned long N = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  pinMode(11, OUTPUT); 
  digitalWrite(11, LOW);
  analogReadResolution(10);
  Wire1.begin();
  if (!sgp.begin(&Wire1)) {
    Serial.println("SGP40 初期化失敗");
    while (1);
  }
  WiFi.begin(ssid, pass);
  unsigned long timeout = millis() + 10000;
  while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
    delay(1000);
    Serial.println("Trying to connect...");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Wi-Fi接続完了");
    Serial.print("Arduino IP: ");
    Serial.println(WiFi.localIP());
  }
  Udp.begin(listenPort);
}

void loop() {
  int packetSize = Udp.parsePacket(); 
  if (packetSize > 0) {
    char command[20];
    int len = Udp.read(command, sizeof(command));
    command[len] = '\0';

    if (strcmp(command, "START") == 0) {
      isCounting = true; 
      N = 0;
      Serial.println("カウント開始");
    }
  }

  int raw = analogRead(analogPin); 
  float voltage = raw * (Vcc / 1023.0);
  float R_thermistor = R_fixed * ((Vcc - voltage) / voltage);
  float lnR = log(R_thermistor);
  float invT = A + B * lnR + C * pow(lnR, 3);
  float tempK = 1.0 / invT;
  float tempC = tempK - 273.15;
  uint16_t sraw = sgp.measureRaw(25.0, 50.0); 
  char buffer[100];  // データ送信
  snprintf(buffer, sizeof(buffer), "SRAW:%u,TEMP:%.2f,N:%lu", sraw, tempC, N);
  Udp.beginPacket(remoteIP, remotePort);
  Udp.write(buffer);
  Udp.endPacket();
  Serial.print("送信 → ");
  Serial.println(buffer);

  if (isCounting) { 
    N++;

    if (N == 50) {
      digitalWrite(11, HIGH);
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("N = 50 → D11 HIGH & LED ON");
    } else if (N == 170) {
      digitalWrite(11, LOW);
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("N = 170 → D11 LOW & LED OFF");
    }

    if (N >= 300) {
     isCounting = false;
     Serial.println("N = 500 到達 → LED_OFF＆カウント停止");
   }
  }
  delay(1000);
}
