#include <stdio.h>
#include <string.h>
#include "ulp.h"
#include "ulp-activity.h"
#include "acquisition-activity.h"

static int variation_limit = 16;

static float time_to_sleep = 30;

extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
extern const uint8_t ulp_main_bin_end[]   asm("_binary_ulp_main_bin_end");

void ulp_config(){
    esp_err_t err = ulp_load_binary(0, ulp_main_bin_start,
            (ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t));
    ESP_ERROR_CHECK(err);

    /* Configure ADC channel */
    /* Note: when changing channel here, also change 'adc_channel' constant
       in adc.S */
    adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11);
    adc1_config_width(ADC_WIDTH_BIT_12);
    adc1_ulp_enable();

    /* Set low and high thresholds, approx. 1.35V - 1.75V*/
    ulp_low_thr = 0;
    ulp_high_thr = 2000;

    /* Set ULP wake up period to 20ms */
    ulp_set_wakeup_period(0, 20000);

    /* Disconnect GPIO12 and GPIO15 to remove current drain through
     * pullup/pulldown resistors.
     * GPIO12 may be pulled high to select flash voltage.
     */
    rtc_gpio_isolate(GPIO_NUM_12);
    rtc_gpio_isolate(GPIO_NUM_15);
    esp_deep_sleep_disable_rom_logging(); // suppress boot messages
}

void start_ulp_program(void)
{
    /* Reset sample counter */
    ulp_sample_counter = 0;

    /* Start the program */
    esp_err_t err = ulp_run(&ulp_entry - RTC_SLOW_MEM);
    ESP_ERROR_CHECK(err);
}


void ulp_activity(){

    static RTC_DATA_ATTR int last_value;
    printf("ULP did %d measurements since last reset\n", ulp_sample_counter & UINT16_MAX);
    ulp_last_result &= UINT16_MAX;
    printf("Value=%d\n", ulp_last_result);
    printf("Entering deep sleep\n\n");
    ulp_sample_counter = 0;
    last_value = get_pressure_raw();
    ulp_last_result = last_value;
    //ulp_sleep(time_to_sleep);
}

void ulp_sleep(){
    esp_sleep_enable_ulp_wakeup();
    esp_deep_sleep(20*1000*1000);
}

/* Get functions */
uint32_t get_time_to_sleep(){
    return time_to_sleep;
}
/* End of get functions */

/* Set functions */
void set_time_to_sleep(float time_to_sleep_to_set){
    time_to_sleep = time_to_sleep_to_set;
}
/* End of set functions */
