#include <Arduino.h>
#include <Wire.h>
#include <AlashAHT.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

constexpr int SDA_PIN = 21;
constexpr int SCL_PIN = 22;
constexpr uint32_t I2C_HZ = 100000;
constexpr uint8_t OLED_ADDRESS = 0x3C;
constexpr unsigned long UPDATE_INTERVAL_MS = 8000;

AlashAHT sensor;
Adafruit_SSD1306 oled(128, 32, &Wire, -1, I2C_HZ, I2C_HZ);
bool oledReady = false;
bool sensorReady = false;

void setup() {
  Serial.begin(115200);
  Wire.begin(SDA_PIN, SCL_PIN, I2C_HZ);
  delay(100);

  Wire.beginTransmission(OLED_ADDRESS);
  oledReady = Wire.endTransmission() == 0 &&
              oled.begin(SSD1306_SWITCHCAPVCC, OLED_ADDRESS, false, false);
  if (oledReady) {
    oled.setTextSize(2);
    oled.setTextColor(SSD1306_WHITE);
    oled.setTextWrap(false);
  } else {
    Serial.println(F("OLED did not start. Check the wiring and address."));
  }

  sensor.setLanguage(AlashAHT::LANG_EN);
}

void loop() {
  if (!sensorReady) {
    sensorReady = sensor.begin(Wire, false);
  }

  if (sensorReady && sensor.update()) {
    const float temperature = sensor.temperature();
    const float humidity = sensor.humidity();

    Serial.print(temperature, 1);
    Serial.print(F(" C, "));
    Serial.print(humidity, 1);
    Serial.println(F(" %RH"));

    if (oledReady) {
      oled.clearDisplay();
      oled.setCursor(0, 0);
      oled.print(F("T "));
      oled.print(temperature, 1);
      oled.println(F(" C"));
      oled.print(F("RH "));
      oled.print(humidity, 1);
      oled.println('%');
      oled.display();
    }
  } else {
    sensorReady = false;
    Serial.println(sensor.errorText());
    if (oledReady) {
      oled.clearDisplay();
      oled.setCursor(0, 0);
      oled.println(F("AHT30"));
      oled.println(F("Check wire"));
      oled.display();
    }
  }
  delay(UPDATE_INTERVAL_MS);
}
