/* Reflow Oven Controller
*
* Copyright (C) 2020  Mario Hüttel <mario.huettel@gmx.net>
*
* This file is part of the Reflow Oven Controller Project.
*
* The reflow oven controller is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* The Reflow Oven Control Firmware is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the reflow oven controller project.
* If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef __SAFETY_MEMORY_H__
#define __SAFETY_MEMORY_H__

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

/** @addtogroup safety-memory
 * @{
 */

/**
 * @brief Magic number to signal a valid safety memory header.
 */
#define SAFETY_MEMORY_MAGIC 0x12AA5CB7

/**
 * @brief Error memory NOP entry
 */
#define SAFETY_MEMORY_NOP_ENTRY 0xC1AA1222

/**
 * @brief Offset address for the safety_memory_header.
 * @note Any other value than 0UL doesn't really make sense. Therfore, this should not be changed.
 */
#define SAFETY_MEMORY_HEADER_ADDRESS 0UL

#define SAFETY_MEMORY_CONFIG_OVERRIDE_COUNT 32UL

/**
 * @brief Safety memory header
 */
struct safety_memory_header {
	uint32_t magic;			/**< @brief Magic. Set to @ref SAFETY_MEMORY_MAGIC */
	uint32_t boot_status_offset;	/**< @brief Offset of the safety_memory_boot_status struct (in 32 bit words)*/
	uint32_t config_overrides_offset; /**< @brief Offset address of override entries */
	uint32_t config_overrides_len;	/**< @brief Length of override entries in words */
	uint32_t err_memory_offset;	/**< @brief Offset of the error memory */
	uint32_t err_memory_end;	/**< @brief End of the error memory. This points to the word after the error memory, containing the CRC of the whole backup RAM. */
	uint32_t crc;		/**< @brief  CRC of the header */
};

struct safety_memory_boot_status {
	/**
	 * @brief Reboot into the bootloader
	 *
	 * When this flag is set, the controller will load the bootloader to
	 * memory and execute it.
	 */
	uint32_t reboot_to_bootloader;

	/**
	 * @brief Bootloader has updated the code
	 *
	 * This flag is set, if the firmware ahs been updated successfully
	 */
	uint32_t code_updated;

	/**
	 * @brief reset_from_panic
	 *
	 * This flag is set, when entering the panic mode.
	 * Because the panic mode is reset by a watchdog reset,
	 * this flag is needed, in order to ensure, that the panic is handled correcly after
	 * the watchdog reset.
	 */
	uint32_t reset_from_panic;
};

/**
 * @brief The state of the safety memory
 *
 * This is returned by certain functions in order to signal, if the header and CRC infos are valid.
 */
enum safety_memory_state {
	SAFETY_MEMORY_INIT_FRESH = 0,		/**< @brief Memory header not found */
	SAFETY_MEMORY_INIT_CORRUPTED = 1,	/**< @brief Header found, but corrupt memory */
	SAFETY_MEMORY_INIT_VALID_MEMORY = 2,	/**< @brief Valid header found and CRC check is valid */
};

/**
 * @brief Types of error memory entries
 */
enum safety_memory_error_entry_type {
	SAFETY_MEMORY_ERR_ENTRY_FLAG = 1,	/**< @brief Flag error entry. Logs a flag */
	SAFETY_MEMORY_ERR_ENTRY_NOP = 2,	/**< @brief NOP entry. Has no meaning, but will be treated as a valid entry */
};

/**
 * @brief Firmware internal representation of an error memory entry.
 */
struct error_memory_entry {
	enum safety_memory_error_entry_type type;
	uint8_t flag_num;
	uint16_t counter;
};

/**
 * @brief Types of conig override entries
 */
enum config_override_entry_type {
	SAFETY_MEMORY_CONFIG_OVERRIDE_WEIGHT = 1,
	SAFETY_MEMORY_CONFIG_OVERRIDE_PERSISTENCE = 2,
};

/**
 * @brief Weights of error flags.
 */
enum config_weight {
	SAFETY_FLAG_CONFIG_WEIGHT_NONE = 0, /**< @brief This flag has no global error consequence, but might be respected by certain software modules. */
	SAFETY_FLAG_CONFIG_WEIGHT_PID = 1, /**< @brief This flag will force a stop of the temperature PID controller */
	SAFETY_FLAG_CONFIG_WEIGHT_PANIC = 2, /**< @brief This flag will trigger the panic mode */
};

/**
 * @brief representation of a config override memory entry
 */
struct config_override {
	enum config_override_entry_type type;
	union {
		struct {
			uint8_t flag;
			enum config_weight weight;
		} weight_override;
		struct {
			uint8_t flag;
			bool persistence;
		} persistence_override;
	} entry;
};

/**
 * @brief First time init the safety memory. This requests all clocks etc.
 *
 * The error memory is always vlaid after this function. At least, if it returns without error.
 * The \p found_state output tells the caller, in which state the memory was found. If it was uninitialized,
 * or corrupted, it is completely wiped and a fresh memory structure is written.
 *
 * @param[out] found_state State the error memory was found in
 * @return 0 if successful
 * @warning Also check @ref safety_memory_reinit
 */
int safety_memory_init(enum safety_memory_state *found_state);

/**
 * @brief Same as @ref safety_memory_init, but without specifically requesting the clock modules.
 *
 * Use this, if a call to @ref safety_memory_init has already been done.
 *
 * @param[out] found_state State the error memory was found in
 * @return 0 if successful
 */
int safety_memory_reinit(enum safety_memory_state *found_state);

/**
 * @brief Get the boot status structure from safety memory
 * @param[out] status Status read from memory.
 * @return 0 if successful
 */
int safety_memory_get_boot_status(struct safety_memory_boot_status *status);

/**
 * @brief Write the boot status structure to safety memory
 * @param[in] status Status to write
 * @return 0 if successful
 */
int safety_memory_set_boot_status(const struct safety_memory_boot_status *status);

/**
 * @brief Get the amout of error entries in the error memory. This also includes NOP entries.
 * @param[out] count Count
 * @return 0 if successful
 */
int safety_memory_get_error_entry_count(uint32_t *count);

/**
 * @brief Check the header and CRC of the safety memory.
 * @return 0 if all checks pass
 */
int safety_memory_check(void);

/**
 * @brief Read an error entry from the error memory
 * @param idx Index of the entry
 * @param[out] entry Error entry
 * @return 0 if successful
 */
int safety_memory_get_error_entry(uint32_t idx, struct error_memory_entry *entry);

/**
 * @brief Insert an error entry
 *
 * This function inserts an error entry on the first NOP entry found in the error memory.
 * If an entry is found with the same flag number, its counter is incremented by the counter value of the
 * element to insert.
 *
 * If there are no NOPs or fitting entries in the error memory, error memory is expanded until it hits the memory
 * boundary.
 *
 * @param entry Error entry to insert
 * @returns 0 if successful, -3 if out of memory, and other negative error codes
 */
int safety_memory_insert_error_entry(struct error_memory_entry *entry);

/**
 * @brief Insert a config override entry at the first free location.
 *
 * Free locations are entries containing 0x00000000
 *
 * @param config_override Config to write
 * @return 0 if successful
 */
int safety_memory_insert_config_override(struct config_override *config_override);

/**
 * @brief Get count of config overrides
 * @param[out] count Number of overrides
 * @return 0 if successful
 */
int safety_memory_get_config_override_count(uint32_t *count);

/**
 * @brief Get a config ovveide entry
 * @param idx Index of the requested entry
 * @param[out] config_override READ override
 * @return 0 if successful
 */
int safety_memory_get_config_override(uint32_t idx, struct config_override *config_override);

/**
 * @brief Get a base64 dump of the whole safety memory.
 * @param[out] buffer Buffer to write the base 64 dump into.
 * @param buffsize Size of buffer. Must be large enough to hold the data plus a '\0' terminator
 * @param[out] used_size Number of written bytes including the '\0' terminator. May be NULL.
 * @return 0 if successful
 */
int safety_memory_dump_base64(char *buffer, size_t buffsize, size_t *used_size);

#endif /* __SAFETY_MEMORY_H__ */

/** @} */
