#include "Arduino.h"
#include "esp_task_wdt.h"

// https://forum.arduino.cc/t/esp32-c3-watch-dog-timer-wdt/1308760/4

void testTask(void* parms);

void setup() {
  Serial.begin(115200);
  vTaskDelay(200);
  Serial.println("Starting");

  esp_task_wdt_config_t twdt_config = {
    .timeout_ms = 10000,
    .idle_core_mask = (1 << configNUM_CORES) - 1,  // Bitmask of all cores,
    .trigger_panic = true,
  };
  ESP_ERROR_CHECK(esp_task_wdt_reconfigure(&twdt_config));
  xTaskCreatePinnedToCore(testTask, "Test Task", 2000, NULL, 5, NULL, ARDUINO_RUNNING_CORE);
}

void loop() {
  vTaskDelete(NULL);
}

void testTask(void* parms) {
  int64_t prevMicros = esp_timer_get_time();
  const int64_t watchDogResetTime = 2000000;
  bool resetWdt = true;

  ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
  ESP_ERROR_CHECK(esp_task_wdt_status(NULL));

  for (;;) {
    int64_t currentMicros = esp_timer_get_time();
    if ((resetWdt) && (currentMicros - prevMicros > watchDogResetTime)) {
      prevMicros = currentMicros;
      Serial.println("Resetting Watchdog");
      esp_task_wdt_reset();
    }

    if (Serial.read() == 's') {
      Serial.println("Halting Watch Dog Resets");
      resetWdt = false;
    }

    vTaskDelay(100);  // Allow Idle Task to run and reset its watch dog
  }
}
