// SashSense Developer Kit - ESP32-WROOM breadboard edition. USB serial, 115200 baud.
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <Adafruit_VL53L0X.h>

Adafruit_VL53L0X distanceSensor;
Adafruit_SHT31 climateSensor;
bool hasDistance;
bool hasClimate;
const int reedPin = 25;  // Connect the magnetic contact between GPIO25 and GND.
const unsigned long samplePauseMs = 500;
int closedDistanceMm = -1;

void setup() {
  Serial.begin(115200);
  pinMode(reedPin, INPUT_PULLUP);
  Wire.begin();  // Uses the pins assigned by the selected ESP32 board.
  delay(250);
  hasDistance = distanceSensor.begin();
  hasClimate = climateSensor.begin(0x44) || climateSensor.begin(0x45);
  Serial.println("Close the model sash and send z to set zero.");
}

void loop() {
  bool setZero = false;
  while (Serial.available()) {
    if (Serial.read() == 'z') setZero = true;
  }

  VL53L0X_RangingMeasurementData_t reading{};
  bool valid = hasDistance &&
               distanceSensor.rangingTest(&reading) == VL53L0X_ERROR_NONE &&
               reading.RangeStatus == 0;
  if (setZero && valid) {
    closedDistanceMm = reading.RangeMilliMeter;
    Serial.println("Zero saved for this session.");
  } else if (setZero) {
    Serial.println("Zero failed. Align the card and try z again.");
  }

  if (!hasDistance) {
    Serial.print("VL53L0X missing");
  } else if (!valid) {
    Serial.print("distance unknown | opening unknown");
  } else {
    Serial.printf("distance %u mm | ", (unsigned)reading.RangeMilliMeter);
    if (closedDistanceMm >= 0) {
      float openingCm = (closedDistanceMm - (int)reading.RangeMilliMeter) / 10.0f;
      Serial.printf("opening %.1f cm", openingCm);
    } else {
      Serial.print("close sash and send z");
    }
  }

  float temp = NAN, humidity = NAN;
  if (hasClimate && climateSensor.readBoth(&temp, &humidity)) {
    Serial.printf(" | %.1f C | %.1f %%RH", temp, humidity);
  } else {
    Serial.print(" | SHT31 reading unavailable");
  }
  bool contactClosed = digitalRead(reedPin) == LOW;
  Serial.println(contactClosed ? " | contact closed" : " | contact open");
  delay(samplePauseMs);
}
