#include <Arduino.h>
#include <WF100DPZ.h>

// Wire these pins to your sensor module.
static constexpr int PIN_CSB = 10;   // Chip select
static constexpr int PIN_SDA = 11;   // Sensor "SDA" pin (shared SPI data line)
static constexpr int PIN_CLK = 12;  // SPI clock

// Create one sensor object using those pins.
static WF100DPZ sensor(PIN_CSB, PIN_SDA, PIN_CLK);
static bool is_ready = false;
static WF100DPZ::Sample s;
static WF100DPZ::StatusCode st = WF100DPZ::StatusCode::Ok;


void setup() {
  Serial.begin(115200);
  delay(200);

  // Initialize the sensor once at startup.
  if (!sensor.begin(&st)) {
    Serial.printf("begin failed: %s\n", sensor.statusString(st));
    return;
  }

  Serial.println("=== WF100DPZ NonBlockingRead ===");
  Serial.println("Flow: start -> ready -> getResult");

  // Start the first non-blocking conversion.
  if (!sensor.start(WF100DPZ::Mode::Combined, &st)) {
    Serial.printf("start failed: %s\n", sensor.statusString(st));
    while (true) delay(1000);
  }
}

void loop() {

  // Poll completion state for the active one-shot conversion.
  is_ready = sensor.ready(&st);
  if (st != WF100DPZ::StatusCode::Ok) {
    Serial.printf("ready failed: %s\n", sensor.statusString(st));
    delay(1000);
    return;
  }

  // If the conversion isn't ready, delay and try again.
  if (!is_ready) {
    delay(2);
    return;
  }

  // Read the completed non-blocking sample.
  s = sensor.getResult(&st);
  if (st != WF100DPZ::StatusCode::Ok) {
    Serial.printf("getResult failed: %s\n", sensor.statusString(st));
    delay(1000);
    return;
  }
  Serial.printf("T=%.2f C P=%.3f kPa elapsed=%lu us\n", s.temp_c, s.pressure_kpa, (unsigned long)s.elapsed_us);

  // Immediately queue the next conversion.
  if (!sensor.start(WF100DPZ::Mode::Combined, &st)) {
    Serial.printf("start failed: %s\n", sensor.statusString(st));
    delay(1000);
    return;
  }

  delay(250);
}
