
#include <Preferences.h>

Preferences preferences;

#include "Adafruit_CCS811.h"

Adafruit_CCS811 ccs;

void setup()
{
  Serial.begin(9600);

  Serial.println("CCS811 test");
  Wire.begin(25, 21);

  // Удаляем отдельный ключ
  //preferences.remove("counter");
  // Удаляем все настройки под заданным пространством имён
  //preferences.clear();

  if (!ccs.begin())
  {
    Serial.println("Failed to start sensor! Please check your wiring.");
    while (1)
      ;
  }

  // Wait for the sensor to be ready
  while (!ccs.available())
    ;
}

void loop()
{
  if (ccs.available())
  {
    if (!ccs.readData())
    {

      unsigned long timenow = millis();
      
      if (timenow >= 43200000 && timenow <= 43240000)
      {
        preferences.begin("airdata", false);
            preferences.putUInt("co2", ccs.geteCO2());
            preferences.putUInt("tvoc", ccs.getTVOC());
            preferences.putUInt("baseline", ccs.getBaseline());
            preferences.end();
            Serial.println("Write data in preferenses - OK");   
        preferences.end();
      }

      Serial.println("----- ");
      Serial.println(timenow);
      Serial.println(getMacAddress());
      Serial.println("----- ");

      Serial.print("NOW CO2: ");
      Serial.println(ccs.geteCO2());

      Serial.print("NOW  ppm, TVOC: ");
      Serial.println(ccs.getTVOC());

      Serial.print("NOW  aseline: ");
      Serial.println(ccs.getBaseline());

      Serial.println("=================");

      preferences.begin("airdata", false);
          Serial.print("Preferenses CO2: ");
          Serial.println(preferences.getUInt("co2", 0));

          Serial.print("Preferenses TVOC: ");
          Serial.println(preferences.getUInt("tvoc", 0));

          Serial.print("Preferenses Baseline: ");
          Serial.println(preferences.getUInt("baseline", 0));
          Serial.println("=============================================");
      preferences.end();
    }
    else
    {
      Serial.println("ERROR!");
    }
  }
  delay(5000);
}

String getMacAddress()
{
  uint8_t baseMac[6];
  esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
  char baseMacChr[18] = {0};
  sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
  return String(baseMacChr);
}