RTC Module Sources


rtc.c

/**
 *
 * @copyright © 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * ″This product uses parts of foxBMS®″
 *
 * ″This product includes parts of foxBMS®″
 *
 * ″This product is derived from foxBMS®″
 *
 */

/**
 * @file    rtc.c
 * @author  foxBMS Team
 * @date    20.10.2015 (date of creation)
 * @ingroup DRIVERS
 * @prefix  RTC
 *
 * @brief   Driver for the real time clock.
 *
 */



/*================== Includes =============================================*/
#include "rtc.h"

/*================== Macros and Definitions ===============================*/


/*================== Constant and Variable Definitions ====================*/
/* Days since the beginning of the year without the days in the current month and without leap days */
const int16_t days_since_newYearsEve[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
/*================== Function Prototypes ==================================*/


/*================== Function Implementations =============================*/
void RTC_Init(void) {
    /* Configure RTC clocks */
    HAL_RCC_OscConfig(&rtc_cfg.oscInitStruct);

    HAL_RCCEx_PeriphCLKConfig(&rtc_cfg.clkInitStruct);

    /* Enable RTC clock */
    __HAL_RCC_RTC_ENABLE();

    /* Initialize RTC */
    hrtc.Instance = RTC;
    hrtc.Init = rtc_cfg.initconfig;
    HAL_RTC_Init(&hrtc);

    /* Disable WakeUp-Timer */
    HAL_RTCEx_DeactivateWakeUpTimer(&hrtc);

    /* set time and date if not already initialized or V_BAT failed */
    if (!(hrtc.Instance->ISR & (uint32_t)RTC_ISR_INITS)) {
        RTC_DATAVALID_VARIABLE = 0;        /* invalidate rtc backup data */
        HAL_RTC_SetTime(&hrtc, &rtc_cfg.defaultTime, rtc_cfg.timeformat);

        HAL_RTC_SetDate(&hrtc, &rtc_cfg.defaultDate, rtc_cfg.timeformat);

        RTC_DATAVALID_VARIABLE = 1;            /* validate rtc backup data */
        RTC_BKPSRAM_DATAVALID_VARIABLE  = 0;   /* invalidate bkpsram data */
        RTC_BKPDIAG_DATAVALID_VARIABLE  = 0;   /* invalidate bkpsram diag data */
        RTC_NVMRAM_DATAVALID_VARIABLE   = 0;   /* invalidate non-volatile data backups */
    }
}

void RTC_setTime(RTC_Time_s * time) {
    HAL_RTC_SetTime(&hrtc, time, FORMAT_BIN);
}

void RTC_setDate(RTC_Date_s * date) {
    HAL_RTC_SetDate(&hrtc, date, FORMAT_BIN);
}

void RTC_getTime(RTC_Time_s * time) {
    HAL_RTC_GetTime(&hrtc, time, FORMAT_BIN);
}

void RTC_getDate(RTC_Date_s * date) {
    HAL_RTC_GetDate(&hrtc, date, FORMAT_BIN);
}

uint32_t RTC_getUnixTime(void) {
    uint32_t unixTime = 0;
    RTC_Time_s rtcTime;
    RTC_Date_s rtcDate;

    /* Get current time and date */
    RTC_getTime(&rtcTime);
    RTC_getDate(&rtcDate);

    /* Convert into unix time */
    unixTime = RTC_convertRTCtoUnixTime(&rtcTime, &rtcDate);

    return unixTime;
}

uint32_t RTC_convertRTCtoUnixTime(RTC_TimeTypeDef* time, RTC_DateTypeDef* date) {
    uint32_t unixTime = 0;
    uint32_t year = 0;
    uint32_t days = 0;
    uint32_t leapYears = 0;

    /* Year is saved as value between 0...99 */
    year = 2000 + date->Year;

    /* Number of leap years since 1970 without the possible ongoing leap year */
    leapYears = ((year-1)-1968)/4 - ((year-1)-1900)/100 + ((year-1)-1600)/400;

    /* Days since 1970 */
    days = ((year - 1970)*365) + leapYears + days_since_newYearsEve[date->Month - 1] + (date->Date - 1);

    /* Check if current year is a leap year, if so add one day */
    if ((date->Month > 2) && ((year % 4 == 0) && ((year%100 != 0) || (year%400!= 0)))) {
        days++;
    }

    /* Calculate unix time in seconds */
    unixTime = time->Seconds + (60*(time->Minutes + (60*(time->Hours + 24*days))));

    return unixTime;
}

rtc.h

/**
 *
 * @copyright © 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * ″This product uses parts of foxBMS®″
 *
 * ″This product includes parts of foxBMS®″
 *
 * ″This product is derived from foxBMS®″
 *
 */

/**
 * @file    rtc.h
 * @author  foxBMS Team
 * @date    20.10.2015 (date of creation)
 * @ingroup DRIVERS
 * @prefix  RTC
 *
 * @brief   Headers for the driver for the real time clock.
 *
 */

#ifndef RTC_H_
#define RTC_H_

/*================== Includes =============================================*/
#include "rtc_cfg.h"

/*================== Macros and Definitions ===============================*/

/**
 * Systemwide low level control, status Information of system
 */
typedef struct {
    RTC_Date_s date;    /*!< RCC clock control & status register at startup */
    RTC_Time_s time;    /*!<  state of Eeprom Driver State Machine          */
    /* uint32_t date;    !< RCC clock control & status register at startup */
    /* uint32_t time;    !<  state of Eeprom Driver State Machine          */
    uint32_t dummy[4];  /*!<                                                */
} RTC_RESETSOURCE_s;


/**
 * Systemwide low level control, status Information of system
 */
typedef struct {
    uint32_t CSR;                       /*!< RCC clock control & status register at startup */
    RTC_Date_s boot_rtcdate;            /*!< boot date                                      */
    RTC_Time_s boot_rtctime;            /*!< boot time                                      */
    RTC_Date_s terminate_rtcdate;       /*!< TODO                                           */
    RTC_Time_s terminate_rtctime;       /*!< TODO                                           */
    uint32_t dummy[4];                  /*!<                                                */
    RTC_RESETSOURCE_s resetsource[20]; /*!< in counts of 1ms                       */
} RTC_STATUS_s;

/*================== Constant and Variable Definitions ====================*/
extern RTC_HandleTypeDef hrtc;
extern RTC_STATUS_s main_state;

/*================== Function Prototypes ==================================*/

/**
 * @brief   initializes rtc module
 */
extern void RTC_Init(void);

/**
 * @brief   sets RTC time
 */
extern void RTC_setTime(RTC_TimeTypeDef* time);

/**
 * @brief   gets RTC time
 */
extern void RTC_getTime(RTC_TimeTypeDef* time);

/**
 * @brief   sets RTC date
 */
extern void RTC_setDate(RTC_DateTypeDef* date);

/**
 * @brief   gets RTC date
 */
extern void RTC_getDate(RTC_DateTypeDef* date);

/*
 * @brief gets current unix time
 */
extern uint32_t RTC_getUnixTime(void);

/*
 * @brief converts current RTC time into unix format
 */
extern uint32_t RTC_convertRTCtoUnixTime(RTC_TimeTypeDef* time, RTC_DateTypeDef* date);

/*================== Function Implementations =============================*/

#endif /* RTC_H_ */

rtc_cfg.c

/**
 *
 * @copyright &copy; 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * &Prime;This product uses parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product includes parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product is derived from foxBMS&reg;&Prime;
 *
 */

/**
 * @file    rtc_cfg.c
 * @author  foxBMS Team
 * @date    13.07.2016 (date of creation)
 * @ingroup DRIVERS_CONF
 * @prefix  RTC
 *
 * @brief   Configuration for the real time clock
 *
 */

/*================== Includes =============================================*/
#include "rtc_cfg.h"

/*================== Macros and Definitions ===============================*/

/*================== Constant and Variable Definitions ====================*/

/* Configuration with RTC clock source: LSE cyrstal */
RTC_CFG_s rtc_cfg = {
    .oscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE, /* MCU1: LSE (external 32 kHz oscillator), */
    .oscInitStruct.LSEState = RCC_LSE_ON,

    .clkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC,
    .clkInitStruct.RTCClockSelection   = RCC_RTCCLKSOURCE_LSE,   /* RTC Clocksourse is LSE */

    .initconfig.HourFormat     = RTC_HOURFORMAT_24,
    .initconfig.AsynchPrediv   = (128-1),                 /* LSI = 32.768kHz:    32.768kHz/(128*256) = 1Hz */
    .initconfig.SynchPrediv    = (256-1),                 /* Subsecond runs with 32.768kHzkHz/128 */
    .initconfig.OutPut         = RTC_OUTPUT_ALARMA,
    .initconfig.OutPutPolarity = RTC_OUTPUT_POLARITY_LOW,
    .initconfig.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN,

    .timeformat                 = FORMAT_BIN,
    .defaultTime.Hours          = 18,
    .defaultTime.Minutes        = 20,
    .defaultTime.Seconds        = 0,
    .defaultTime.SubSeconds     = 0,
    .defaultTime.TimeFormat     = RTC_HOURFORMAT12_PM,
    .defaultTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE,
    .defaultTime.StoreOperation = RTC_STOREOPERATION_RESET,

    .defaultDate.WeekDay        = RTC_WEEKDAY_TUESDAY,
    .defaultDate.Month          = RTC_MONTH_JULY,
    .defaultDate.Date           = 12,
    .defaultDate.Year           = 16,
};

RTC_HandleTypeDef hrtc;

/*================== Function Prototypes ===================================*/

/*================== Function Implementations ==============================*/

uint32_t RTC_getRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber) {
    uint32_t retval = 0;
    if (registerNumber == BKPREGISTER_DATA_VALID) {
        retval = RTC_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_VALID) {
        retval = RTC_BKPSRAM_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_DIAG_VALID) {
        retval = RTC_BKPDIAG_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_NVRAM_VALID) {
        retval = RTC_NVMRAM_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_WDG_RESETCOUNTER) {
        retval = RTC_WDG_RESETCOUNTER;
    } else {
        /* TODO: explain why empty else */
    }
    return retval;
}


void RTC_setRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber, uint32_t value) {
    if (registerNumber == BKPREGISTER_DATA_VALID) {
        RTC_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_VALID) {
        RTC_BKPSRAM_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_DIAG_VALID) {
        RTC_BKPDIAG_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_NVRAM_VALID) {
        RTC_NVMRAM_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_WDG_RESETCOUNTER) {
        RTC_WDG_RESETCOUNTER = value;
    }
}

rtc_cfg.h

/**
 *
 * @copyright &copy; 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * &Prime;This product uses parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product includes parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product is derived from foxBMS&reg;&Prime;
 *
 */

/**
 * @file    rtc_cfg.h
 * @author  foxBMS Team
 * @date    02.10.2015 (date of creation)
 * @ingroup DRIVERS_CONF
 * @prefix  RTC
 *
 * @brief   Headers for the configuration for the real time clock
 *
 */

#ifndef RTC_CFG_H_
#define RTC_CFG_H_

/*================== Includes =============================================*/
#include "general.h"

#include "cpu_cfg.h"

/*================== Macros and Definitions ===============================*/
typedef RTC_InitTypeDef     RTC_INIT_s;
typedef RTC_TimeTypeDef     RTC_Time_s;
typedef RTC_DateTypeDef     RTC_Date_s;

/* backup size of the registers 80 Byte */
#define RTC_DATAVALID_VARIABLE              (hrtc.Instance->BKP0R)  /* rtc backup register valid */
#define RTC_BKPSRAM_DATAVALID_VARIABLE      (hrtc.Instance->BKP1R)  /* bkpsram data valid */
#define RTC_BKPDIAG_DATAVALID_VARIABLE      (hrtc.Instance->BKP2R)  /* bpksram diag data valid */
#define RTC_NVMRAM_DATAVALID_VARIABLE       (hrtc.Instance->BKP3R)  /* non-volatile data backups valid */
#define RTC_WDG_RESETCOUNTER                (hrtc.Instance->BKP5R)  /* wdg resetcounter */
#define RTC_DEEP_DISCHARGE_DETECTED         (hrtc.Instance->BKP6R)  /* deep-discharge detected - only clearable over CAN */

/**
 * struct for the initialization and configuration of RTC
 */
typedef struct {
    RCC_OscInitTypeDef          oscInitStruct;  /*!< clock configuration of RTCs clock source */
    RCC_PeriphCLKInitTypeDef    clkInitStruct;  /*!< clock source of RTC:  RTCClk can be derived from HSE (ext. crystal), LSE (ext. crystal), LSI (internal RC oscillator) */
    RTC_INIT_s                  initconfig;     /*!< RTC configuration: hour format, prescaler,... */
    uint8_t                     timeformat;     /*!< date and time format configuration (binary or BCD) */
    RTC_Time_s                  defaultTime;    /*!< default time configuration */
    RTC_Date_s                  defaultDate;    /*!< default date configuration */
} RTC_CFG_s;


typedef enum {
    BKPREGISTER_DATA_VALID          = 0,
    BKPREGISTER_BKPSRAM_VALID       = 1,
    BKPREGISTER_BKPSRAM_DIAG_VALID  = 2,
    BKPREGISTER_NVRAM_VALID         = 3,
    BKPREGISTER_WDG_RESETCOUNTER    = 5,
} RTC_BKPREGISTER_e;


typedef enum {
    BKPREGISTER_NOT_VALID = 0,
    BKPREGISTER_VALID = 1,
}RTC_BKPREGISTER_VALIDSTATE_e;

/*================== Constant and Variable Definitions ====================*/
extern RTC_CFG_s rtc_cfg;
extern RTC_HandleTypeDef hrtc;

/*================== Function Prototypes ===================================*/

/**
 * @brief   get backup register value
 */
uint32_t RTC_getRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber);

/**
 * @brief   set backup register value
 */
void RTC_setRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber, uint32_t value);

/*================== Function Implementations ==============================*/

#endif /* RTC_CFG_H_ */

rtc_cfg.c

/**
 *
 * @copyright &copy; 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * &Prime;This product uses parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product includes parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product is derived from foxBMS&reg;&Prime;
 *
 */

/**
 * @file    rtc_cfg.c
 * @author  foxBMS Team
 * @date    13.07.2016 (date of creation)
 * @ingroup DRIVERS_CONF
 * @prefix  RTC
 *
 * @brief   Configuration for the real time clock
 *
 */

/*================== Includes =============================================*/
#include "rtc_cfg.h"

/*================== Macros and Definitions ===============================*/

/*================== Constant and Variable Definitions ====================*/

#if 0       /* Configuration with RTC clock source: LSI oscillator */
RTC_CFG_s rtc_cfg = {
    .oscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI,      /* MCU1: LSE (external 32 kHz oscillator) not implemented, */
    .oscInitStruct.LSIState      = RCC_LSI_ON,                   /* so use LSI (Internal low-speed oscillator) */

    .clkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC,
    .clkInitStruct.RTCClockSelection   = RCC_RTCCLKSOURCE_LSI,   /* RTC Clocksourse is LSI */

    .initconfig.HourFormat     = RTC_HOURFORMAT_24,
    .initconfig.AsynchPrediv   = (125-1),                 /* LSI = 32kHz:    32kHz/(125*256) = 1Hz */
    .initconfig.SynchPrediv    = (256-1),                 /* Subsecond runs with 32kHz/125 */
    .initconfig.OutPut         = RTC_OUTPUT_ALARMA,
    .initconfig.OutPutPolarity = RTC_OUTPUT_POLARITY_LOW,
    .initconfig.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN,

    .timeformat                 = FORMAT_BIN,
    .defaultTime.Hours          = 18,
    .defaultTime.Minutes        = 20,
    .defaultTime.Seconds        = 0,
    .defaultTime.SubSeconds     = 0,
    .defaultTime.TimeFormat     = RTC_HOURFORMAT12_PM,
    .defaultTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE,
    .defaultTime.StoreOperation = RTC_STOREOPERATION_RESET,

    .defaultDate.WeekDay        = RTC_WEEKDAY_TUESDAY,
    .defaultDate.Month          = RTC_MONTH_JULY,
    .defaultDate.Date           = 12,
    .defaultDate.Year           = 16,
};
#endif

/* Configuration with RTC clock source: HSE cyrstal */
RTC_CFG_s rtc_cfg = {
    .oscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE,      /* MCU1: LSE (external 32 kHz oscillator) not implemented, */
    .oscInitStruct.HSEState      = RCC_HSE_ON,                   /* so use HSE 8 MHz (external high-speed oscillator) */

    .clkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC,
    .clkInitStruct.RTCClockSelection   = RCC_RTCCLKSOURCE_HSE_DIV16,   /* RTC Clocksourse is HSE, HSE_RTC = 8MHz/16 = 500kHz */

    .initconfig.HourFormat     = RTC_HOURFORMAT_24,
    .initconfig.AsynchPrediv   = (125-1),                 /* HSE_RTC = 500kHz:    500kHz/(125*4000) = 1Hz */
    .initconfig.SynchPrediv    = (4000-1),                /* Subsecond runs with 500kHz/125 = 250us */
    .initconfig.OutPut         = RTC_OUTPUT_ALARMA,
    .initconfig.OutPutPolarity = RTC_OUTPUT_POLARITY_LOW,
    .initconfig.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN,

    .timeformat                 = FORMAT_BIN,
    .defaultTime.Hours          = 18,
    .defaultTime.Minutes        = 20,
    .defaultTime.Seconds        = 0,
    .defaultTime.SubSeconds     = 0,
    .defaultTime.TimeFormat     = RTC_HOURFORMAT12_PM,
    .defaultTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE,
    .defaultTime.StoreOperation = RTC_STOREOPERATION_RESET,

    .defaultDate.WeekDay        = RTC_WEEKDAY_TUESDAY,
    .defaultDate.Month          = RTC_MONTH_JULY,
    .defaultDate.Date           = 12,
    .defaultDate.Year           = 16,
};

RTC_HandleTypeDef hrtc;

/*================== Function Prototypes ===================================*/

/*================== Function Implementations ==============================*/

uint32_t RTC_getRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber) {
    uint32_t retval = 0;
    if (registerNumber == BKPREGISTER_DATA_VALID) {
        retval = RTC_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_VALID) {
        retval = RTC_BKPSRAM_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_DIAG_VALID) {
        retval = RTC_BKPDIAG_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_NVRAM_VALID) {
        retval = RTC_NVMRAM_DATAVALID_VARIABLE;
    } else if (registerNumber == BKPREGISTER_WDG_RESETCOUNTER) {
        retval = RTC_WDG_RESETCOUNTER;
    } else {
        /* TODO: explain why empty else */
    }
    return retval;
}


void RTC_setRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber, uint32_t value) {
    if (registerNumber == BKPREGISTER_DATA_VALID) {
        RTC_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_VALID) {
        RTC_BKPSRAM_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_BKPSRAM_DIAG_VALID) {
        RTC_BKPDIAG_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_NVRAM_VALID) {
        RTC_NVMRAM_DATAVALID_VARIABLE = value;
    } else if (registerNumber == BKPREGISTER_WDG_RESETCOUNTER) {
        RTC_WDG_RESETCOUNTER = value;
    }
}

rtc_cfg.h

/**
 *
 * @copyright &copy; 2010 - 2020, Fraunhofer-Gesellschaft zur Foerderung der
 *  angewandten Forschung e.V. All rights reserved.
 *
 * BSD 3-Clause License
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * We kindly request you to use one or more of the following phrases to refer
 * to foxBMS in your hardware, software, documentation or advertising
 * materials:
 *
 * &Prime;This product uses parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product includes parts of foxBMS&reg;&Prime;
 *
 * &Prime;This product is derived from foxBMS&reg;&Prime;
 *
 */

/**
 * @file    rtc_cfg.h
 * @author  foxBMS Team
 * @date    02.10.2015 (date of creation)
 * @ingroup DRIVERS_CONF
 * @prefix  RTC
 *
 * @brief   Headers for the configuration for the real time clock
 *
 */

#ifndef RTC_CFG_H_
#define RTC_CFG_H_

/*================== Includes =============================================*/
#include "general.h"

#include "cpu_cfg.h"

/*================== Macros and Definitions ===============================*/
typedef RTC_InitTypeDef     RTC_INIT_s;
typedef RTC_TimeTypeDef     RTC_Time_s;
typedef RTC_DateTypeDef     RTC_Date_s;

/* backup size of the registers 80 Byte */
#define RTC_DATAVALID_VARIABLE              (hrtc.Instance->BKP0R)  /* rtc backup register valid */
#define RTC_BKPSRAM_DATAVALID_VARIABLE      (hrtc.Instance->BKP1R)  /* bkpsram data valid */
#define RTC_BKPDIAG_DATAVALID_VARIABLE      (hrtc.Instance->BKP2R)  /* bpksram diag data valid */
#define RTC_NVMRAM_DATAVALID_VARIABLE       (hrtc.Instance->BKP3R)  /* non-volatile data backups valid */
#define RTC_WDG_RESETCOUNTER                (hrtc.Instance->BKP5R)  /* wdg resetcounter */

/**
 * struct for the initialization and configuration of RTC
 */
typedef struct {
    RCC_OscInitTypeDef          oscInitStruct;  /*!< clock configuration of RTCs clock source */
    RCC_PeriphCLKInitTypeDef    clkInitStruct;  /*!< clock source of RTC:  RTCClk can be derived from HSE (ext. crystal), LSE (ext. crystal), LSI (internal RC oscillator) */
    RTC_INIT_s                  initconfig;     /*!< RTC configuration: hour format, prescaler,... */
    uint8_t                     timeformat;     /*!< date and time format configuration (binary or BCD) */
    RTC_Time_s                  defaultTime;    /*!< default time configuration */
    RTC_Date_s                  defaultDate;    /*!< default date configuration */
} RTC_CFG_s;


typedef enum {
    BKPREGISTER_DATA_VALID          = 0,
    BKPREGISTER_BKPSRAM_VALID       = 1,
    BKPREGISTER_BKPSRAM_DIAG_VALID  = 2,
    BKPREGISTER_NVRAM_VALID         = 3,
    BKPREGISTER_WDG_RESETCOUNTER    = 5,
} RTC_BKPREGISTER_e;


typedef enum {
    BKPREGISTER_NOT_VALID = 0,
    BKPREGISTER_VALID = 1,
}RTC_BKPREGISTER_VALIDSTATE_e;

/*================== Constant and Variable Definitions ====================*/
extern RTC_CFG_s rtc_cfg;
extern RTC_HandleTypeDef hrtc;

/*================== Function Prototypes ===================================*/

/**
 * @brief   get backup register value
 */
uint32_t RTC_getRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber);

/**
 * @brief   set backup register value
 */
void RTC_setRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber, uint32_t value);

/*================== Function Implementations ==============================*/

#endif /* RTC_CFG_H_ */