/****************************************************************************/
/**
* \file dcf77.c
*
* \brief Contains the routine for the time data extraction from a DCF77
*        module.
*
* \author   Michael Skutek
* \date	    11.09.2011
* \version  0.4
*
* Platform:    AVR ATmega (tested on ATmega168)
*
* Include Files:
*       - avr/io.h:             port accessing (part of avr-gcc)
*       - dcf77.h:              all internal definitions
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
****************************************************************************/



/******************************************
	\internal
	Include files
*******************************************/

#include <avr/io.h>

#include "dcf77.h"

#if RTC_LCD_DEBUG == 1
#include "lcd.h"
#endif



/****************************************************************************/
/**
* Synchronizes to DCF77 time data and must be called periodically with the
* given sample time. The sample time should be around 10 ms.\n
* The function has the following return values (which represent it's internal
* state):
*  - DCF77_STARTSYNC_SEARCH01: Looking for the first falling edge of the DCF77
*    input signal. This is a part of the search for the synchronization marker.
*  - DCF77_STARTSYNC_SEARCH02: Looking for the second falling edge of the DCF77
*    input signal. This is a part of the search for the synchronization marker.
*  - DCF77_STARTSYNC_COMPLETED: Synchronization marker was found. If this return
*    value is delivered, the second "01" is now synchronous to the DCF77 time.
*    However this marker should not be used to synchronize the clock, because
*    this may be detected sometimes also as a consequence of noise.
*  - DCF77_TIMESYNC_SEARCH01: Looking for the falling edge of the signal (start
*    of a pulse) during the receiving of the time data bit stream.
*  - DCF77_TIMESYNC_SEARCH02: Looking for the raising edge of the signal (end
*    of a pulse) during the receiving of the time data bit stream.
*  - DCF77_MINUTE_COMPLETED: The time data for the next minute was received
*    completely and thus the respective value of the real_time structure
*    (current_minute) was updated.
*  - DCF77_HOUR_COMPLETED: The time data for the current hour was received
*    completely and thus the respective value of the real_time structure
*    (current_hour) was updated.
*  - DCF77_DAY_COMPLETED: The date value for the current day was received
*    completely and thus the respective value of the real_time structure
*    (current_day) was updated.
*  - DCF77_WEEKDAY_COMPLETED: The value for the current weekday name was
*    received completely and thus the respective value of the real_time
*    structure (current_weekday) was updated.
*  - DCF77_MONTH_COMPLETED: The date value for the current month was received
*    completely and thus the respective value of the real_time structure
*    (current_month) was updated.
*  - DCF77_TIMESYNC_COMPLETED: The date value for the current day was received
*    completely and thus the respective value of the real_time structure
*    (current_day) was updated. The synchronization is now complete and the
*    internal clock can be synchonized with the received values (the
*    value for the current second is now 59.
*
*
*
* \param [in] dcf77_signal          input signal from DCF77 module
*                                   (Bit 0: 0x00 or 0x01)
* \param [in] logic_type            DCF77_ACTIVE_HIGH: input signal from DCF77
*                                   is "active high" \n
*                                   DCF77_ACTIVE_LOW:  input signal from DCF77
*                                   is "active low"
* \param [in] real_time             structure in which the function writes the
*                                   real time
* \param [in] sample_time           sample time (DCF77 signal) [ms * 10]
* \param [in] command               command: \n
*                                   DCF77_RESET_TIME: start a new sync cycle \n
*                                   DCF77_GET_TIME: normal operation during sync
*
* \return state of synchronization (see definitions for the internal states in
*                                   file dcf77.h)
*
* \date
* - Created 05.08.2010
* - Modified  28.09.2011
*
*
* \see dcf77.h
* \see port_definitions.h
*
*
* \author
*   Michael Skutek, michael@skutek.de
*/
/****************************************************************************/

uint8_t dcf77_sync(uint8_t dcf77_signal, uint8_t logic_type, real_time_data *real_time,
                   uint8_t sample_time, uint8_t command) {


  static uint8_t time_count = 0;
  static uint8_t bit_counter = 0;
  static uint8_t parity_counter = 0;
  static uint8_t tmp_value = 0;
  static uint8_t state = DCF77_STARTSYNC_SEARCH01;

  static uint8_t prev_dcf77_signal = DCF77_UNINIT_VALUE;


  /***************************************************************************
  \internal
  reset all internal values at start (required before every start of a new
                                      sync!)
  ***************************************************************************/
  if (command == DCF77_RESET_TIME) {

    time_count = 0;
    bit_counter = 0;
    parity_counter = 0;
    tmp_value = 0;
    state = DCF77_STARTSYNC_SEARCH01;
    prev_dcf77_signal = DCF77_UNINIT_VALUE;      //this initial value indicates an uninitialized previuos signal

    return state;

  }


  /***************************************************************************
  \internal
  normal operation --> time synchronization --> function has to be called
  cyclical until state (return value) is "DCF77_TIMESYNC_COMPLETED"
  ***************************************************************************/

  //invert input signal if "active high"
  if (logic_type == DCF77_ACTIVE_HIGH) {
    dcf77_signal = dcf77_signal ^ 1;          //XOR
  }

  //set previous DCF77 signal to current value if uninitialized
  if (prev_dcf77_signal == DCF77_UNINIT_VALUE) {
    prev_dcf77_signal = dcf77_signal;
  }


  /***************************************************************************
  \internal
  state machine to get DCF77 time...
  ***************************************************************************/
  switch (state) {

    // synchronization from second 59 to 00/01:
    //
    //           (1)                                    (2)
    //_____________        _______________________________         _____________
    //            |        |                             |         |
    //            |        |                             |         |
    //            |        |                             |         |
    //            |________|                             |_________|
    //                                 2 sec
    //            |<------------------------------------>|

  case DCF77_STARTSYNC_SEARCH01:

    if ((prev_dcf77_signal == 1) && (dcf77_signal == 0)) {   //wait for rising edge (1), signal is inverted!

#if RTC_LCD_DEBUG == 1
      lcd_set_cursor(15, 0);
      lcd_send_string("#", FALSE);               //for blinking cursor
#endif

      time_count = 0;
      state = DCF77_STARTSYNC_SEARCH02;
    }

    break;


    // synchronization from second 59 to 00/01:
    //
    //           (1)                                    (2)
    //_____________        _______________________________         _____________
    //            |        |                             |         |
    //            |        |                             |         |
    //            |        |                             |         |
    //            |________|                             |_________|
    //                                 2 sec
    //            |<------------------------------------>|


  case DCF77_STARTSYNC_SEARCH02:

    if ((prev_dcf77_signal == 1) && (dcf77_signal == 0)) {     //wait for rising edge (2),  signal is inverted!

#if RTC_LCD_DEBUG == 1
      lcd_set_cursor(15, 0);
      lcd_send_string(" ", FALSE);
#endif

      if ((time_count >= DCF77_SYNC_START_MIN) && (time_count <= DCF77_SYNC_START_MAX)) { //arrived during correct time window?
        time_count = 0;
        bit_counter = 0;
        state = DCF77_STARTSYNC_COMPLETED;            //synchronized! --> read in bits to get minutes, hours...
      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    } else {
      if (time_count < DCF77_SYNC_START_MAX) {        //max time exceed? --> try it next time again...
        time_count = time_count + sample_time;
      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    }

    break;


    // reading bit (falling edge):
    //
    //           (1)    "1"    (2)                  (1)  "0"   (2)
    //_____________            _______________________         _____________
    //            |            |                     |         |
    //            |  200 msec  |                     | 100 msec|
    //            |<---------->|                     |<------->|
    //            |____________|                     |_________|
    //                               1 sec
    //            |<-------------------------------->|


  case DCF77_STARTSYNC_COMPLETED:
  case DCF77_MINUTE_COMPLETED:
  case DCF77_HOUR_COMPLETED:
  case DCF77_DAY_COMPLETED:
  case DCF77_MONTH_COMPLETED:
  case DCF77_YEAR_COMPLETED:
  case DCF77_WEEKDAY_COMPLETED:
  case DCF77_TIMESYNC_SEARCH01:

    //set state to deactivate indicators (other COMPLETED-states)
    state = DCF77_TIMESYNC_SEARCH01;

    //wait for (next) falling edge (signal is inverted!)
    if ((prev_dcf77_signal == 1) && (dcf77_signal == 0)) {
      if ((time_count >= DCF77_SYNC_MIN) && (time_count <= DCF77_SYNC_MAX)) { //arrived during correct time window?

        time_count = 0;
        state = DCF77_TIMESYNC_SEARCH02;        //falling edge found ---> wait for rising edge
      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    } else {
      if (time_count < DCF77_SYNC_MAX) {        //max time exceed? --> try it next time again...
        time_count = time_count + sample_time;
      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    }

    break;


    // reading bit (falling edge):
    //
    //           (1)    "1"    (2)                  (1)  "0"   (2)
    //_____________            _______________________         _____________
    //            |            |                     |         |
    //            |  200 msec  |                     | 100 msec|
    //            |<---------->|                     |<------->|
    //            |____________|                     |_________|
    //                               1 sec
    //            |<-------------------------------->|


  case DCF77_TIMESYNC_SEARCH02:

    //wait for (next) rising edge (signal is inverted!)
    if ((prev_dcf77_signal == 0) && (dcf77_signal == 1)) {
      if ((time_count >= DCF77_LOW_MIN) && (time_count <= DCF77_LOW_MAX)) { //arrived during correct time window?

        state = DCF77_TIMESYNC_SEARCH01;        //rising edge arrived in specified time window

        /******************************************
        \internal
        decoding - logical "0"
        *******************************************/

        //for minutes
        if (bit_counter == 20) {
          tmp_value = 0;
          parity_counter = 0;
        } else if (bit_counter == 26) {

          //check parity bit
        } else if (bit_counter == 27) {

          if ((parity_counter % 2) == 0) {            //even parity (parity bit == 0)
            real_time->current_minute = tmp_value;
            state = DCF77_MINUTE_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        //for hours
        if (bit_counter == 28) {
          tmp_value = 0;
          parity_counter = 0;
        } else if (bit_counter == 34) {

          //check parity bit
          if ((parity_counter % 2) == 0) {            //even parity (parity bit == 0)
            real_time->current_hour = tmp_value;
            state = DCF77_HOUR_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        //for day
        if (bit_counter == 35) {
          tmp_value = 0;
          parity_counter = 0;
        } else if (bit_counter == 40) {    //do not reset the parity counter (will be done after year)
          real_time->current_day = tmp_value;
          state = DCF77_DAY_COMPLETED;
        }

        //for weekday
        if (bit_counter == 41) {
          tmp_value = 0;
        } else if (bit_counter == 43) {    //do not reset the parity counter (will be done after year)
          real_time->current_weekday = tmp_value;
          state = DCF77_WEEKDAY_COMPLETED;
        }

        //for month
        if (bit_counter == 44) {
          tmp_value = 0;
        } else if (bit_counter == 48) {    //do not reset the parity counter (will be done after year)
          real_time->current_month = tmp_value;
          state = DCF77_MONTH_COMPLETED;
        }

        //for year
        if (bit_counter == 49) {
          tmp_value = 0;
        } else if (bit_counter == 57) {

          //check parity bit
          if ((parity_counter % 2) == 0) {            //even parity (parity bit == 0)
            real_time->current_year = tmp_value;
            state = DCF77_YEAR_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        bit_counter++;

        if (bit_counter > 57) {
          state = DCF77_TIMESYNC_COMPLETED;
        }

      } else if ((time_count >= DCF77_HIGH_MIN) && (time_count <= DCF77_HIGH_MAX)) { //arrived during correct time window?

        state = DCF77_TIMESYNC_SEARCH01;     //rising edge arrived in specified time window

        /******************************************
        \internal
        decoding - logical "1"
        *******************************************/

        //minutes
        if (bit_counter == 20) {
          tmp_value = 1;
          parity_counter = 1;
        } else if (bit_counter == 21) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 22) {
          tmp_value = tmp_value + 4;
          parity_counter++;
        } else if (bit_counter == 23) {
          tmp_value = tmp_value + 8;
          parity_counter++;
        } else if (bit_counter == 24) {
          tmp_value = tmp_value + 10;
          parity_counter++;
        } else if (bit_counter == 25) {
          tmp_value = tmp_value + 20;
          parity_counter++;
        } else if (bit_counter == 26) {
          tmp_value = tmp_value + 40;
          parity_counter++;


          //check parity bit
        } else if (bit_counter == 27) {

          if ((parity_counter % 2) > 0) {            //even parity (odd without parity bit)
            real_time->current_minute = tmp_value;
            state = DCF77_MINUTE_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        //hours
        if (bit_counter == 28) {
          tmp_value = 1;
          parity_counter = 1;
        } else if (bit_counter == 29) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 30) {
          tmp_value = tmp_value + 4;
          parity_counter++;
        } else if (bit_counter == 31) {
          tmp_value = tmp_value + 8;
          parity_counter++;
        } else if (bit_counter == 32) {
          tmp_value = tmp_value + 10;
          parity_counter++;
        } else if (bit_counter == 33) {
          tmp_value = tmp_value + 20;
          parity_counter++;
        } else if (bit_counter == 34) {

          if ((parity_counter % 2) > 0) {            //even parity (odd without parity bit)
            real_time->current_hour = tmp_value;
            state = DCF77_HOUR_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        //day of month
        if (bit_counter == 35) {
          tmp_value = 1;
          parity_counter = 1;
        } else if (bit_counter == 36) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 37) {
          tmp_value = tmp_value + 4;
          parity_counter++;
        } else if (bit_counter == 38) {
          tmp_value = tmp_value + 8;
          parity_counter++;
        } else if (bit_counter == 39) {
          tmp_value = tmp_value + 10;
          parity_counter++;
        } else if (bit_counter == 40) {   //do not reset the parity counter (will be done after year)
          tmp_value = tmp_value + 20;
          parity_counter++;
          real_time->current_day = tmp_value;
          state = DCF77_DAY_COMPLETED;
        }

        //weekday
        if (bit_counter == 41) {
          tmp_value = 1;
          parity_counter++;
        } else if (bit_counter == 42) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 43) {   //do not reset the parity counter (will be done after year)
          tmp_value = tmp_value + 4;
          parity_counter++;
          real_time->current_weekday = tmp_value;
          state = DCF77_WEEKDAY_COMPLETED;
        }

        //month
        if (bit_counter == 44) {
          tmp_value = 1;
          parity_counter++;
        } else if (bit_counter == 45) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 46) {
          tmp_value = tmp_value + 4;
          parity_counter++;
        } else if (bit_counter == 47) {
          tmp_value = tmp_value + 8;
          parity_counter++;
        } else if (bit_counter == 48) {   //do not reset the parity counter (will be done after year)
          tmp_value = tmp_value + 10;
          parity_counter++;
          real_time->current_month = tmp_value;
          state = DCF77_MONTH_COMPLETED;
        }

        //year
        if (bit_counter == 49) {
          tmp_value = 1;
          parity_counter++;
        } else if (bit_counter == 50) {
          tmp_value = tmp_value + 2;
          parity_counter++;
        } else if (bit_counter == 51) {
          tmp_value = tmp_value + 4;
          parity_counter++;
        } else if (bit_counter == 52) {
          tmp_value = tmp_value + 8;
          parity_counter++;
        } else if (bit_counter == 53) {
          tmp_value = tmp_value + 10;
          parity_counter++;
        } else if (bit_counter == 54) {
          tmp_value = tmp_value + 20;
          parity_counter++;
        } else if (bit_counter == 55) {
          tmp_value = tmp_value + 40;
          parity_counter++;
        } else if (bit_counter == 56) {
          tmp_value = tmp_value + 80;
          parity_counter++;
        } else if (bit_counter == 57) {

          if ((parity_counter % 2) > 0) {            //even parity (odd without parity bit)
            real_time->current_year = tmp_value;
            state = DCF77_YEAR_COMPLETED;
          } else {
            state = DCF77_STARTSYNC_SEARCH01;
          }

        }

        bit_counter++;

        if (bit_counter > 57) {
          state = DCF77_TIMESYNC_COMPLETED;
        }

      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    } else {
      if (time_count < DCF77_HIGH_MAX) {        //max time exceed? --> try it next time again...
        time_count = time_count + sample_time;
      } else {
        state = DCF77_STARTSYNC_SEARCH01;
      }
    }

    break;



  default:
    break;

  }


  //save signal value
  prev_dcf77_signal = dcf77_signal;


  return state;

}

