/*
 * sleep.h
 *
 *  Created on: Jan 24, 2014
 *      Author: rob
 *  Thom Maughan, MBARI 2018
 */

#ifndef PHFETSOS_SLEEP_H_
#define PHFETSOS_SLEEP_H_

#include <stdint.h>
#include <stdbool.h>

// Delay time for menus before they should sleep, in seconds
extern const uint32_t MENU_TIMEOUT_SEC;
extern const uint32_t TIMEOUT_EXEC_MAIN_SEC;
extern const uint32_t DEPLOY_DELAY_SEC;
extern const uint32_t CONFIG_MENU_TIMEOUT_SEC;

// read HIB RTCC and handle errata
uint32_t read_hib_rtcc();
// read HIB RTCC/RTCSS and handle errata
void read_hib_rtcc_rtcss(uint32_t* const out_hib_rtcc, uint32_t* const out_hib_rtccss);

// read HIB RTCC and handle errata and subtract offset so it is seconds since unix epoch instead of ti epoch
uint32_t read_hib_rtcc_unix(void);

// Wait for hib ctl WRC to be set, which means the write is complete
void wait_for_hib_wrc(void);

// Set wake source and avoid an error in Tiva
// wake_flags may be bit-or of HIB_CTL_RTCWEN, HIB_CTL_PINWEN, HIB_CTL_BATWKEN
void hib_set_wake_source(const uint32_t wake_flags);

// returns true if hib initialized
// may reset hib if init fails
bool init_hib_module(bool* out_was_por);

// returns true if hib data has valid crc
// uses less stack than get_hib_data. get_hib_data also verifys crc, so use that if you also want the data anyway.
bool is_hib_data_valid();
// zeros word[0..14] and writes a valid crc to word[15]
void clear_hib_data();
// writes word[0..14] to hib data and writes a valid crc to word[15]
void set_hib_data(const uint32_t data[15]);
// returns hib data word[0..14] and returns true if crc is valid
bool get_hib_data(uint32_t data[15]);

// return true if hib is ready for write
// may return false due to errata HIB#19 on TM4C129
bool wait_for_hib_ready();

// wait for hib, enable LFIOSC, wait for hib
bool set_hib_LFIOSC();

// wait for hib, enable extosc, wait for hib
bool set_hib_extclk();

void sleep(deploy_state state, uint32_t wake_time);
uint32_t wake_handler(void);

#define WAKE_NOTSET         0
#define WAKE_CONSOLE        1
#define WAKE_RTC            2
#define WAKE_RESET          3
#define WAKE_GPIO           4

#endif /* PHFETSOS_SLEEP_H_ */
