/* Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */

/** @file
* @defgroup nrf_qdec_example main.c
* @{
* @ingroup nrf_qdec_example
* @brief QDEC example application main file.
*
* This is an example quadrature decoder application.
* The example requires that the QDEC A,B inputs are connected with the QENC A,B outputs and
* the QDEC LED output is connected with the QDEC LED input.
*
* The example uses the software quadrature encoder simulator QENC.
* The quadrature encoder simulator uses one channel of the GPIOTE module.
* The state of the encoder changes on the inactive edge of the sampling clock generated by the LED output.
*
* In an infinite loop, QENC produces a variable number of positive and negative pulses
* synchronously with bursts of clock impulses generated by QDEC at the LED output.
* The pulses are counted by QDEC operating in a REPORT mode.
* The pulses counted by QDEC are compared with the pulses generated by QENC.
* The test stops if there is a difference between the number of pulses counted and generated.
*
*/

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

#include "nrf.h"
#include "bsp.h"
#include "nrf_delay.h"
#include "nrf_drv_qdec.h"
#include "app_uart.h"
#include "nrf_error.h"
#include "app_error.h"
#include "qenc_sim.h"
#include "nordic_common.h"


#define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 1   /**< UART RX buffer size. */

static volatile bool m_report_ready_flag = false;
static volatile bool m_first_report_flag = true;
static volatile uint32_t m_accdblread;
static volatile int32_t m_accread;

static void uart_error_handle(app_uart_evt_t * p_event)
{
    if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}

static void qdec_event_handler(nrf_drv_qdec_event_t event)
{
    if (event.type == NRF_QDEC_EVENT_REPORTRDY)
    {
        m_accdblread = event.data.report.accdbl;
        m_accread = event.data.report.acc;
        m_report_ready_flag = true;
        nrf_drv_qdec_disable();
    }
}

static void wait_for_uart_idle(void)
{
    /* There is no function in the UART library that provides functionality 
     * to wait for a transfer to finish. Therefore, wait some time - not elegant.
     * To be changed when the UART library gets the required functionality. */
    nrf_delay_ms(500);
}

void check_report(int32_t expected)
{
    // only first run is specific...
    if ((expected > 0) && m_first_report_flag)
    {
       expected = expected-1;
    }
    else if ((expected < 0) && m_first_report_flag)
    {
       expected = expected+1;
    }

    // Error checking and printing
    if( m_accdblread != 0 )
    {
        printf("\nERROR: m_accdblread was expected to have value 0 but is %u\n", (unsigned int)m_accdblread);
        UNUSED_VARIABLE(fflush(stdout));
        wait_for_uart_idle();
        APP_ERROR_HANDLER(0);
    }
    if( m_accread != expected )
    {
        printf("\nERROR: m_accread should be %d but is %d\n", (int)expected, (int)m_accread);
        UNUSED_VARIABLE(fflush(stdout));
        wait_for_uart_idle();
        APP_ERROR_HANDLER(0);
    }
    m_first_report_flag = false;  // clear silently after first run

}

int main(void)
{
    uint32_t err_code;
    bool forever = true;
    uint32_t  number_of_pulses;
    uint32_t  min_number_of_pulses = 2;
    uint32_t  max_number_of_pulses = 0;
    int32_t   pulses;
    int32_t   sign = 1;

    // Initialize UART
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_ENABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_error_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);

    APP_ERROR_CHECK(err_code);

    // Initialize hardware
    err_code = nrf_drv_qdec_init(NULL, qdec_event_handler);
    APP_ERROR_CHECK(err_code);
    
    max_number_of_pulses = nrf_qdec_reportper_to_value(QDEC_CONFIG_REPORTPER);

    // Initialize quadrature encoder simulator
    qenc_init((nrf_qdec_ledpol_t)nrf_qdec_ledpol_get());

    printf("QDEC testing started\n");

    while (forever)
    {
      // change a number and sign of pulses produced by simulator in a loop
      for (number_of_pulses=min_number_of_pulses; number_of_pulses<= max_number_of_pulses; number_of_pulses++ )
      {
        pulses = sign*number_of_pulses;      // pulses have sign
        qenc_pulse_count_set(pulses);        // set pulses to be produced by encoder
        nrf_drv_qdec_enable();               // start burst sampling clock, clock will be stopped by REPORTRDY event
        while (! m_report_ready_flag)                         // wait for a report
        {
          __WFE();
        }
        printf("*");
        UNUSED_VARIABLE(fflush(stdout));
        m_report_ready_flag = false;
        check_report(pulses);                 // check if pulse count is as expected, assert otherwise
      }
      min_number_of_pulses = 1;               // only first run is specific, for 1 there would be no call back...
      sign = -sign;                           // change sign of pulses in a loop
    }
    return -1;                                // this should never happen
}

/** @} */
