/*This file is prepared for Doxygen automatic documentation generation.*/
//! \file *********************************************************************
//!
//! \brief This file manages the Mouse task.
//!
//! - Compiler:           IAR EWAVR and GNU GCC for AVR
//! - Supported devices:  ATmega32U4
//!
//! \author               Atmel Corporation: http://www.atmel.com \n
//!                       Support and FAQ: http://support.atmel.no/
//!
//! ***************************************************************************

/* Copyright (c) 2009 Atmel Corporation. All rights reserved.
 *
 * 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. The name of Atmel may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an Atmel
 * AVR product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY AND
 * SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
 */

//_____  I N C L U D E S ___________________________________________________

#include "config.h"
#include "conf_usb.h"

#include "mouse_task.h"
#include "usb_descriptors.h"

#include "lib_mcu/usb/usb_drv.h"
#include "lib_mcu/wdt/wdt_drv.h"
#include "lib_mcu/power/power_drv.h"
#include "lib_mcu/pll/pll_drv.h"
#include "lib_mcu/util/start_boot.h"
#include "lib_mcu/flash/flash_drv.h"
#include "lib_mcu/cal_inter_rc/cal_inter_rc.h"
#include "modules/usb/device_chap9/usb_standard_request.h"


//_____ M A C R O S ________________________________________________________

//! @defgroup mouse_report_fill Macro to fill mouse report array
//! @{
#define  Hid_mouse_report_up()            (g_hid_mouse_report[2]-=MOUSE_SPEED)
#define  Hid_mouse_report_down()          (g_hid_mouse_report[2]+=MOUSE_SPEED)
#define  Hid_mouse_report_left()          (g_hid_mouse_report[1]-=MOUSE_SPEED)
#define  Hid_mouse_report_right()         (g_hid_mouse_report[1]+=MOUSE_SPEED)

#define  Hid_mouse_report_scroll_up()     (g_hid_mouse_report[3]+=MOUSE_SPEED)
#define  Hid_mouse_report_scroll_down()   (g_hid_mouse_report[3]-=MOUSE_SPEED)

#define  Hid_mouse_report_click_left()    (g_hid_mouse_report[0] |= 0x01)
#define  Hid_mouse_report_click_right()   (g_hid_mouse_report[0] |= 0x02)
#define  Hid_mouse_report_click_middle()  (g_hid_mouse_report[0] |= 0x04)


#define  Hid_mouse_report_reset()         (g_hid_mouse_report[0]=0,g_hid_mouse_report[1]=0,g_hid_mouse_report[2]=0,g_hid_mouse_report[3]=0)
//! @}

//! @defgroup mouse_board_interface Macro to link board with mouse event
//! @{
#define Is_mouse_left_event()             Is_switch_3()
#define Is_mouse_right_event()            Is_switch_2()
#define Is_mouse_up_event()               Is_switch_1()
#define Is_mouse_down_event()             Is_switch_0()

#define Is_mouse_scroll_up_event()        FALSE
#define Is_mouse_scroll_down_event()      FALSE

#define Is_mouse_click_left_event()       Is_switch_6()
#define Is_mouse_click_middle_event()     Is_switch_5()
#define Is_mouse_click_right_event()      Is_switch_4()
//! @}


//_____ D E C L A R A T I O N S ____________________________________________

bit   is_mouse_event(void);

//! Used to flag a report ready to send
Bool  g_b_send_report;
//! Used to flag a ack report ready to send
Bool  g_b_send_ack_report;
//! Used to store the HID mouse report
U8    g_hid_mouse_report[4];
//! Used to count the number of SOF and create a timer counter
volatile U8 g_u8_cpt_sof;
volatile int g_int_cpt_cal_update;


//! This function initializes the hardware/software resources required for mouse task.
//!
void mouse_task_init(void)
{
   // Init SOF
   g_u8_cpt_sof=0;
   Usb_enable_sof_interrupt();

   // Init interface board
   Switches_init();
   Leds_init();
   Led7_on();
   Led6_off();

   // Send a ack report at startup
   g_b_send_report      = FALSE;
   g_b_send_ack_report  = TRUE;

   // Init the internal OSC calibration counter
   g_int_cpt_cal_update = 0;
}


//! Task which links mouse events with the USB HID mouse device
//!
void mouse_task(void)
{
   if(!Is_device_enumerated())
      return;  // Device not ready

#if (USB_LOW_SPEED_DEVICE==DISABLE)
   // The SOF is used to schedule the task at the same frequency that Endpoint Interrupt frequency
   // This check allow to win a CPU time
   if(g_u8_cpt_sof<NB_IDLE_POLLING_SOF)
      return;  // Wait a delay
   g_u8_cpt_sof=0;
#endif

   if(!g_b_send_report)
   {
      // No report sending on going then check mouse event to eventualy fill a new report
      if(is_mouse_event())
      {
         // Enable sending of report
         g_b_send_report      = TRUE;
      }
   }

   if((!g_b_send_report)&&(!g_b_send_ack_report))
      return;  // No report and ack to send

   //** A report or ack must be send
   Usb_select_endpoint(EP_MOUSE_IN);
   if(!Is_usb_write_enabled())
      return;  // Endpoint no free

   Led6_on();
   if( g_b_send_report )
   {
      g_b_send_report      = FALSE;
      // Send an ack after a "clic" report only
      g_b_send_ack_report = (0!=g_hid_mouse_report[0]);
   }
   else
   {
      Hid_mouse_report_reset();     // Reset report to have a ack report
      g_b_send_ack_report  = FALSE;
   }
   // Send report
   Usb_write_byte(g_hid_mouse_report[0]);
   Usb_write_byte(g_hid_mouse_report[1]);
   Usb_write_byte(g_hid_mouse_report[2]);
   Usb_write_byte(g_hid_mouse_report[3]);
   Usb_ack_in_ready();
   Led6_off();
}


//! This function checks the board interface and fill the HID mouse report
//!
//! @return TRUE if an event occurs. In this case, the HID mouse report is filled
//! @return FALSE if not event
//!
bit is_mouse_event(void)
{
   Hid_mouse_report_reset();

   // Check Click events
   if(Is_mouse_click_left_event()) {
      Hid_mouse_report_click_left();
   }
   if(Is_mouse_click_middle_event()) {
      Hid_mouse_report_click_middle();
   }
   if(Is_mouse_click_right_event()) {
      Hid_mouse_report_click_right();
   }

   // Check Mouve events
   if (Is_mouse_left_event()) {
      Hid_mouse_report_left();
   }
   if (Is_mouse_right_event()) {
      Hid_mouse_report_right();
   }
   if (Is_mouse_up_event()) {
      Hid_mouse_report_up();
   }
   if (Is_mouse_down_event()) {
      Hid_mouse_report_down();
   }
   if (Is_mouse_scroll_up_event()) {
      Hid_mouse_report_scroll_up();
   }
   if (Is_mouse_scroll_down_event()) {
      Hid_mouse_report_scroll_down();
   }

   // Check report
   if((0==g_hid_mouse_report[0])
   && (0==g_hid_mouse_report[1])
   && (0==g_hid_mouse_report[2])
   && (0==g_hid_mouse_report[3]))
   {
      return FALSE;  // No event
   }
   return TRUE;      // Event(s) occurs
}


//! This function increments the SOF counter each times
//!
//! @verbatim
//! the USB Start Of Frame interrupt subroutine is executed (1ms)
//! Usefull to manage time delays
//! @endverbatim
//!
void sof_action()
{
   g_u8_cpt_sof++;

}
//! This function update the OSCCAL value each 30s
//!
//! @verbatim
//! The calibration of the internal OSC each 30s
//! @endverbatim
//!
void update_osc_cal_task()
{
  g_int_cpt_cal_update++;
  if(g_int_cpt_cal_update > 3000)
 {
   g_int_cpt_cal_update = 0;
   calibrate_inter_osc(vcc_5);
 }
}

//! This function enables switches interruptions and enters the CPU in power down mode.
//!
//! @verbatim
//! This function is executed when a suspend is received.
//! @endverbatim
//!
void suspend_action(void)
{
#if (USB_REMOTE_WAKEUP_FEATURE == ENABLED)
   if (remote_wakeup_feature == ENABLED)
   {
      Switches_enable_it();
   }
   Led7_off();
   Enable_interrupt();
   Enter_power_down_mode();
   Led7_on();
#endif
}


#if (USB_REMOTE_WAKEUP_FEATURE == ENABLED)
//! This function exits the CPU of the power down mode and disables switches interruptions
//!
//! @verbatim
//! This function is executed when a switche interruption is received
//! @endverbatim
//!
#ifdef __GNUC__
 ISR(PCINT0_vect)
#else
#pragma vector = PCINT0_vect
__interrupt void switch_event_int()
#endif
{
   Switches_disable_it();
   usb_generate_remote_wakeup();
}
#endif

