/*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:  AT90USB1287, AT90USB1286, AT90USB647, AT90USB646
//!
//! \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 "device_mouse_task.h"
#include "usb_descriptors.h"

#include "lib_mcu/usb/usb_drv.h"
#include "lib_mcu/adc/adc_drv.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_joy_left()
#define Is_mouse_right_event()            Is_joy_right()
#define Is_mouse_up_event()               Is_joy_up()
#define Is_mouse_down_event()             Is_joy_down()

#define SCROLL_STEP      10
#define Is_mouse_scroll_up_event()        ((g_u16_pos_scroll+SCROLL_STEP) < Get_adc_pot_val())
#define Is_mouse_scroll_down_event()      ((g_u16_pos_scroll-SCROLL_STEP) > Get_adc_pot_val())

#define Is_mouse_click_left_event()       Is_btn_left()
#define Is_mouse_click_middle_event()     FALSE
#define Is_mouse_click_right_event()      Is_btn_middle()
//! @}


//_____ D E F I N I T I O N S ______________________________________________



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

bit   is_device_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 store the HID mouse report
U16 g_u16_pos_scroll;
//! Used to count the number of SOF and create a timer counter
volatile U8  g_u8_cpt_sof   =0;
volatile U16 g_u16_cpt2_sof =0;


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

   // Init interface board
   Joy_init();
   Leds_init();
   Hwb_button_init();
   init_adc();
   g_u16_pos_scroll=Get_adc_pot_val();
   
   // Send a ack report at startup
   g_b_send_report      = FALSE;
   g_b_send_ack_report  = TRUE;
}


//! This function has no effect, but is called by scheduler. It is replaced by mouse_task_by_IT() that is interrupt handled
//!
void device_mouse_task(void)
{
   if(Is_usb_id_device())
   {
      Usb_enable_sof_interrupt();   // In case of interrupt disabled when USB ID pin change
   }
}

//! Task which links mouse events with the USB HID mouse device
//!
//! @verbatim
//! This task is interrupt handled : the function is called periodically from the ISR of Start of Frame reception
//! That makes possible moving the mouse while the mass storage is used (file copy for example)
//! @endverbatim
//!
void device_mouse_task_by_IT(void)
{
   if(!Is_device_enumerated())
      return;  // Device not ready
   
   if(!g_b_send_report)
   {
      // No report sending on going then check mouse event to eventualy fill a new report
      if(is_device_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
   
   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();
}


//! 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_device_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()) {
      g_u16_pos_scroll+=SCROLL_STEP;
      Hid_mouse_report_scroll_up();
   }
   if (Is_mouse_scroll_down_event()) {
      g_u16_pos_scroll-=SCROLL_STEP;
      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.
//! Periodically this ISR calls the mouse_task_by_IT() function that ensure
//! the mouse operation in any circumstances (mass storage access, etc...)
//! @endverbatim
//!
void sof_action()
{
   U8 ep_selected;
   g_u16_cpt2_sof++;
   g_u8_cpt_sof++;
   if (g_u8_cpt_sof == NB_IDLE_POLLING_SOF)
   {
     ep_selected = Usb_get_selected_endpoint();   // the currently selected endpoint must be saved to avoid
                                                  // problems when interrupt happens during mass storage endpoint reading/writing
     device_mouse_task_by_IT();
     g_u8_cpt_sof = 0;
     Usb_select_endpoint(ep_selected);            // restore current selected endpoint
   }
}

