/**************************************************************************************************
  Filename:       SampleApp.c
  Revised:        $Date: 2009-03-18 15:56:27 -0700 (Wed, 18 Mar 2009) $
  Revision:       $Revision: 19453 $

  Description:    Sample Application (no Profile).


  Copyright 2007 Texas Instruments Incorporated. All rights reserved.

  IMPORTANT: Your use of this Software is limited to those specific rights
  granted under the terms of a software license agreement between the user
  who downloaded the software, his/her employer (which must be your employer)
  and Texas Instruments Incorporated (the "License").  You may not use this
  Software unless you agree to abide by the terms of the License. The License
  limits your use, and you acknowledge, that the Software may not be modified,
  copied or distributed unless embedded on a Texas Instruments microcontroller
  or used solely and exclusively in conjunction with a Texas Instruments radio
  frequency transceiver, which is integrated into your product.  Other than for
  the foregoing purpose, you may not use, reproduce, copy, prepare derivative
  works of, modify, distribute, perform, display or sell this Software and/or
  its documentation for any purpose.

  YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
  PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
  NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
  TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
  NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
  LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
  INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
  OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
  OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
  (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

  Should you have any questions regarding your right to use this Software,
  contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/

/*********************************************************************
  This application isn't intended to do anything useful, it is
  intended to be a simple example of an application's structure.

  This application sends it's messages either as broadcast or
  broadcast filtered group messages.  The other (more normal)
  message addressing is unicast.  Most of the other sample
  applications are written to support the unicast message model.

  Key control:
    SW1:  Sends a flash command to all devices in Group 1.
    SW2:  Adds/Removes (toggles) this device in and out
          of Group 1.  This will enable and disable the
          reception of the flash command.
*********************************************************************/

/*********************************************************************
 * INCLUDES
 */
#include "OSAL.h"
#include "ZGlobals.h"
#include "AF.h"
#include "aps_groups.h"
#include "ZDApp.h"

#include "SampleApp.h"
#include "SampleAppHw.h"

#include "OnBoard.h"

/* HAL */
#include "hal_lcd.h"
#include "hal_led.h"
#include "hal_key.h"

#ifdef ALWAY_ONLINE
  #include "ZDObject.h"    //ZD0_RegisterTaskID
#endif

#if (defined (HAL_UART)) && (HAL_UART == TRUE)
  #include "MT_UART.h"
  #include "hal_uart.h"
#endif

#ifdef ZDEBUG
  #include "MyDebug.h"
#endif//ZDEBUG

#include "MT.h"          //CMD_SERIAL_MSG

#include "OSAL_Nv.h"

/*********************************************************************
 * MACROS
 */

/*********************************************************************
 * CONSTANTS
 */

/*********************************************************************
 * TYPEDEFS
 */

/*********************************************************************
 * GLOBAL VARIABLES
 */

// This list should be filled with Application specific Cluster IDs.
const cId_t SampleApp_ClusterList[SAMPLEAPP_MAX_CLUSTERS] =
{
  SAMPLEAPP_PERIODIC_CLUSTERID,
  SAMPLEAPP_CONTROL_CLUSTERID,
  SAMPLEAPP_ACK_CLUSTERID,
  SAMPLEAPP_CAM_CLUSTERID
};

const SimpleDescriptionFormat_t SampleApp_SimpleDesc =
{
  SAMPLEAPP_ENDPOINT,              //  int Endpoint;
  SAMPLEAPP_PROFID,                //  uint16 AppProfId[2];
  SAMPLEAPP_DEVICEID,              //  uint16 AppDeviceId[2];
  SAMPLEAPP_DEVICE_VERSION,        //  int   AppDevVer:4;
  SAMPLEAPP_FLAGS,                 //  int   AppFlags:4;
  SAMPLEAPP_MAX_CLUSTERS,          //  uint8  AppNumInClusters;
  (cId_t *)SampleApp_ClusterList,  //  uint8 *pAppInClusterList;
  SAMPLEAPP_MAX_CLUSTERS,          //  uint8  AppNumOutClusters;
  (cId_t *)SampleApp_ClusterList   //  uint8 *pAppOutClusterList;
};

// This is the Endpoint/Interface description.  It is defined here, but
// filled-in in SampleApp_Init().  Another way to go would be to fill
// in the structure here and make it a "const" (in code space).  The
// way it's defined in this sample app it is define in RAM.
endPointDesc_t SampleApp_epDesc;

/*********************************************************************
 * EXTERNAL VARIABLES
 */

/*********************************************************************
 * EXTERNAL FUNCTIONS
 */

/*********************************************************************
 * LOCAL VARIABLES
 */
uint8 SampleApp_TaskID;   // Task ID for internal task/event processing
                          // This variable will be received when
                          // SampleApp_Init() is called.
uint8 SampleApp_TransID;  // This is the unique message ID (counter)

devStates_t SampleApp_NwkState;

aps_Group_t SampleApp_Group;

afAddrType_t SampleApp_SendMsg_DstAddr;

afAddrType_t SampleApp_Flash_DstAddr;
uint8 SampleAppFlashCounter = 0;

uint8 SampleAppPeriodicCounter = 0;

#ifdef CAMRING
uint8 cam_state = 0;
uint8 cam_flag  = 0;

uint16 offset = 0;

//ZComDef.h
// NV Items Reserved for applications (user applications)
// 0x0401 ?0x0FFF
uint16 pg_len[20][2] = {{0x0401,0}};
uint16 pg_hdr = 0x0401;

uint16 iw     = 0x0000;
uint16 iw_max = 0x0000;

/* State values for camera protocal */
#define START_STATE    0x01
#define RLEN_STATE     0x02//读取图片长度
#define RDATA_STATE    0x03//读取图片数据
#define STOP_STATE     0x04
#define DEFAULT        0x08
#endif//CAMRING

/*********************************************************************
 * LOCAL FUNCTIONS
 */
void SampleApp_HandleKeys( uint8 shift, uint8 keys );
void SampleApp_MessageMSGCB( afIncomingMSGPacket_t *pckt );
void SampleApp_SendFlashMessage( uint16 flashTime );
afStatus_t SampleApp_SendMessage( uint8 *data, uint8 datalen, byte CLUSTERID );
void SampleApp_SerialCMD( mtOSALSerialData_t *cmdMsg );//串口

#ifdef CAMRING
void SampleApp_CAM_SendMessage( void );
#endif//CAMRING
/*********************************************************************
 * NETWORK LAYER CALLBACKS
 */

/*********************************************************************
 * PUBLIC FUNCTIONS
 */

/*********************************************************************
 * @fn      SampleApp_Init
 * @brief   Initialization function for the Generic App Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notificaiton ... ).
 * @param   task_id - the ID assigned by OSAL.  This ID should be
 *                    used to send messages and set timers.
 * @return  none
 */
void SampleApp_Init( uint8 task_id )
{
  SampleApp_TaskID = task_id;
  SampleApp_NwkState = DEV_INIT;
  SampleApp_TransID = 0;

  MT_UartRegisterTaskID( task_id );//串口接收
  
  // Device hardware initialization can be added here or in main() (Zmain.c).
  // If the hardware is application specific - add it here.
  // If the hardware is other parts of the device add it in main().

 #if defined ( BUILD_ALL_DEVICES )
  // The "Demo" target is setup to have BUILD_ALL_DEVICES and HOLD_AUTO_START
  // We are looking at a jumper (defined in SampleAppHw.c) to be jumpered
  // together - if they are - we will start up a coordinator. Otherwise,
  // the device will start as a router.
  if ( readCoordinatorJumper() )
    zgDeviceLogicalType = ZG_DEVICETYPE_COORDINATOR;
  else
    zgDeviceLogicalType = ZG_DEVICETYPE_ROUTER;
#endif // BUILD_ALL_DEVICES

#if defined ( HOLD_AUTO_START )
  // HOLD_AUTO_START is a compile option that will surpress ZDApp
  //  from starting the device and wait for the application to
  //  start the device.
  ZDOInitDevice(0);
#endif
  
  // Setup for the periodic message's destination address
  SampleApp_SendMsg_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;
  SampleApp_SendMsg_DstAddr.endPoint = SAMPLEAPP_ENDPOINT;
  SampleApp_SendMsg_DstAddr.addr.shortAddr = 0x0000;
  
  // Fill out the endpoint description.
  SampleApp_epDesc.endPoint = SAMPLEAPP_ENDPOINT;//源端点描述,终端类型在此修改,协调器节点类型也可修改
  SampleApp_epDesc.task_id = &SampleApp_TaskID;
  SampleApp_epDesc.simpleDesc
            = (SimpleDescriptionFormat_t *)&SampleApp_SimpleDesc;
  SampleApp_epDesc.latencyReq = noLatencyReqs;

  // Register the endpoint description with the AF
  afRegister( &SampleApp_epDesc );

  // Register for all key events - This app will handle all key events
  RegisterForKeys( SampleApp_TaskID );

  // By default, all devices start out in Group 1
  SampleApp_Group.ID = 0x0001;
  osal_memcpy( SampleApp_Group.name, "Group 1", 7  );
  aps_AddGroup( SAMPLEAPP_ENDPOINT, &SampleApp_Group );
}

/*********************************************************************
 * @fn      SampleApp_ProcessEvent
 * @brief   Generic Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 * @return  none
 */
uint16 SampleApp_ProcessEvent( uint8 task_id, uint16 events )
{
  afIncomingMSGPacket_t *MSGpkt;
  (void)task_id;  // Intentionally unreferenced parameter

  if ( events & SYS_EVENT_MSG )
  {
    MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( SampleApp_TaskID );
    while ( MSGpkt )
    {
      switch ( MSGpkt->hdr.event )
      {
          
        case CMD_SERIAL_MSG: 
          SampleApp_SerialCMD((mtOSALSerialData_t *)MSGpkt);
          break;
          
        // Received when a key is pressed
        case KEY_CHANGE:
          SampleApp_HandleKeys( ((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys );
          break;

        // Received when a messages is received (OTA) for this endpoint
        case AF_INCOMING_MSG_CMD:
          SampleApp_MessageMSGCB( MSGpkt );
          break;

        // Received whenever the device changes state in the network
        case ZDO_STATE_CHANGE:
          SampleApp_NwkState = (devStates_t)(MSGpkt->hdr.status);
          if ( (SampleApp_NwkState == DEV_ZB_COORD)
              || (SampleApp_NwkState == DEV_ROUTER)
              || (SampleApp_NwkState == DEV_END_DEVICE) )
          {
            // Start sending the periodic message in a regular interval.
            osal_start_timerEx( SampleApp_TaskID,
                              SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
                              SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT );
          }
          else
          {
            // Device is no longer in the network
          }
          break;

        default:
          break;
      }

      // Release the memory
      osal_msg_deallocate( (uint8 *)MSGpkt );

      // Next - if one is available
      MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( SampleApp_TaskID );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }
  
#ifdef CAMRING
  if ( events & SAMPLEAPP_SEND_CAM_PKG_EVT )
  {
    SampleApp_CAM_SendMessage();
    return (events ^ SAMPLEAPP_SEND_CAM_PKG_EVT);
  }
#endif

  // Send a message out - This event is generated by a timer
  //  (setup in SampleApp_Init()).
  if ( events & SAMPLEAPP_SEND_PERIODIC_MSG_EVT )
  {
    // Send the periodic message
    //SampleApp_SendMessage(PeriodMSG, AF_HEARTBEAT_SZ, SAMPLEAPP_PERIODIC_CLUSTERID);
    
    // Setup to send message again in normal period (+ a little jitter)
    osal_start_timerEx( SampleApp_TaskID, SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
        (SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT + (osal_rand() & 0x00FF)) );

    // return unprocessed events
    return (events ^ SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
  }
  // Discard unknown events
  return 0;
}

/*********************************************************************
 * Event Generation Functions
 */
/*********************************************************************
 * @fn      SampleApp_HandleKeys
 *
 * @brief   Handles all key events for this device.
 *
 * @param   shift - true if in shift/alt.
 * @param   keys - bit field for key events. Valid entries:
 *                 HAL_KEY_SW_2
 *                 HAL_KEY_SW_1
 *
 * @return  none
 */
void SampleApp_HandleKeys( uint8 shift, uint8 keys )
{
  (void)shift;  // Intentionally unreferenced parameter
  uint8 startf[5] = {0x56,0x00,0x36,0x01,0x00};//拍照指令
  if ( keys & HAL_KEY_SW_1 )
  {
    /* This key sends the Flash Command is sent to Group 1.
     * This device will not receive the Flash Command from this
     * device (even if it belongs to group 1).
     */
    SampleApp_SendFlashMessage( SAMPLEAPP_FLASH_DURATION );
  }

  if ( keys & HAL_KEY_SW_2 )
  {
    /* The Flashr Command is sent to Group 1.
     * This key toggles this device in and out of group 1.
     * If this device doesn't belong to group 1, this application
     * will not receive the Flash command sent to group 1.
     */
    aps_Group_t *grp;
    grp = aps_FindGroup( SAMPLEAPP_ENDPOINT, SAMPLEAPP_FLASH_GROUP );
    if ( grp )
    {
      // Remove from the group
      aps_RemoveGroup( SAMPLEAPP_ENDPOINT, SAMPLEAPP_FLASH_GROUP );
    }
    else
    {
      // Add to the flash group
      aps_AddGroup( SAMPLEAPP_ENDPOINT, &SampleApp_Group );
    }
  }
}

/*********************************************************************
 * LOCAL FUNCTIONS
 */

/*********************************************************************
 * @fn      SampleApp_MessageMSGCB
 *
 * @brief   Data message processor callback.  This function processes
 *          any incoming data - probably from other devices.  So, based
 *          on cluster ID, perform the intended action.
 *
 * @param   none
 *
 * @return  none
 */
void SampleApp_MessageMSGCB( afIncomingMSGPacket_t *pkt )
{
  switch ( pkt->clusterId )
  {
    case SAMPLEAPP_CONTROL_CLUSTERID:
      break;

    default:
      break;
  }
}

/*********************************************************************
 * @fn      SampleApp_SendFlashMessage
 *
 * @brief   Send the flash message to group 1.
 *
 * @param   flashTime - in milliseconds
 *
 * @return  none
 */
void SampleApp_SendFlashMessage( uint16 flashTime )
{
  uint8 buffer[3];
  buffer[0] = (uint8)(SampleAppFlashCounter++);
  buffer[1] = LO_UINT16( flashTime );
  buffer[2] = HI_UINT16( flashTime );

  if ( AF_DataRequest( &SampleApp_Flash_DstAddr, &SampleApp_epDesc,
                       SAMPLEAPP_CONTROL_CLUSTERID,
                       3,
                       buffer,
                       &SampleApp_TransID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS ) == afStatus_SUCCESS )
  {
  }
  else
  {
    // Error occurred in request to send.
  }
}

/*功能描述: 无线发送
 *data:     发送的数据
 *datalen:  发送数据的长度
 *CLUSTERID:簇ID
 *调用了af函数
 *返回发送状态
*/
afStatus_t SampleApp_SendMessage( uint8 *data, uint8 datalen, byte CLUSTERID )
{
  afStatus_t state;
  state = AF_DataRequest( &SampleApp_SendMsg_DstAddr, &SampleApp_epDesc,
                          CLUSTERID,
                          datalen,
                          data,
                          &SampleApp_TransID,
                          AF_DISCV_ROUTE,
                          AF_DEFAULT_RADIUS );
  return ( state );
}

/*图像数据转发*/
void SampleApp_CAM_SendMessage( void )
{
  uint16 len;
  uint8  *flash_cache = NULL;  
  uint16 ik = 0x0000;
  uint16 pg = 0x0401;
  
  HAL_ENABLE_INTERRUPTS();
  for ( ik = 0; ik < iw_max; ik++ )
  {
    pg  = pg_len[ik][0];
    len = pg_len[ik][1];
    
    flash_cache = osal_mem_alloc( len );
    if ( flash_cache )
    {
      osal_nv_read( pg, offset, len, flash_cache );
      SampleApp_SendMsg_DstAddr.addr.shortAddr = 0x0000;
      //SampleApp_SendMessage( flash_cache, pg_len[ik][1], SAMPLEAPP_CAM_CLUSTERID );
      HalUARTWrite( 1, flash_cache, len );
      osal_mem_free( flash_cache );
    }
  }
  HAL_DISABLE_INTERRUPTS();
}

/*
 * 功能:串口通信
 * 和摄像头串口通信
*/
void SampleApp_SerialCMD(mtOSALSerialData_t *cmdMsg)//串口透传实验，官方本身的协议为发送 FE 02 01 F1  ,则返回01 F1(FE为开头SOF，02为长度)
{
  uint8 *str = NULL;
  uint8 len  = 0;
  
#if 1
  uint8  *flash_cache  = NULL;
//  uint8 start[5] = {0x56,0x00,0x36,0x01,0x00};//拍照指令
  const uint8 startCB[5] = {0x76,0x00,0x36,0x00,0x00};
  uint8 stop[5]  = {0x56,0x00,0x36,0x01,0x03};//停止拍照指令
  uint8 rplen[5] = {0x56,0x00,0x34,0x01,0x00};//读取照片长度指令
  const uint8 rplenCBhdr[7]= {0x76,0x00,0x34,0x00,0x04,0x00,0x00};//读取图片数据长度指令时返回值帧头
  
  uint8 rdata[16] = {0x56,0x00,0x32,0x0C,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0A};
  //起始地址，必须是8的倍数(8/9)，默认设置为0
  //图片数据长度，初始化为0(12/13)
  //interval time间隔时间,默认为0x000A,最小不小于0x0008,尽量小(14/15)
  
  const uint8 pdhdr[5] = {0x76,0x00,0x32,0x00,0x00};//,0xFF,0xD8};    //读取到的图片数据帧头
  const uint8 pdtal[2] = {0xFF,0xD9};    //读取到的图片数据帧尾
  
  str = cmdMsg->msg;
  len = *str;
  switch (cam_state)
  {
    default:
      break;
    case START_STATE:
      if (osal_memcmp(str+1, startCB, 5) == TRUE)//拍照指令成功
      {
        FLASHLED_CTRL = BUZZER_POLARITY(0); /*闪光灯关闭*/
        HalUARTWrite(0, rplen, 5);//读取照片长度
        cam_state = RDATA_STATE;
      }
      break;
      
    case RDATA_STATE:
      if (osal_memcmp(str+1, rplenCBhdr, 7) == TRUE)
      {
        osal_memcpy(rdata+12, str+1+7, 2);//提取读取到的图片长度
        HalUARTWrite(0, rdata, 16);//读取图片
        cam_state = STOP_STATE;
      }
      break;
      
    case STOP_STATE:
      if (osal_memcmp(str+1, pdhdr, 5) == TRUE)
      {
        cam_flag  = 1;
        cam_state = DEFAULT;
        str+=5;len-=5;//去掉帧头76 00 32 00 00
      }
      break;
  }
  if (cam_flag == 1)
  {    
    pg_len[iw][0] = pg_hdr++;
    pg_len[iw][1] = len;
    
    osal_nv_item_init( pg_len[iw][0], len, NULL );
    osal_nv_write( pg_len[iw][0], offset, len, str+1 );
    
//    flash_cache = osal_mem_alloc(len);
//    if ( flash_cache )
//    {
//      osal_nv_read( pg_len[iw][0], offset,len, flash_cache );
//      HalUARTWrite( 1, flash_cache, len );
//      osal_mem_free(flash_cache);
//    }
    
    iw++;
    
    if (osal_memfind(str+1, pdhdr, len, 5) == TRUE)//接收到帧标识说明一帧数据接收完成
    {
      HalUARTWrite(0, stop, 5);  //关闭拍照
      PWR_CTRL = PWR_POLARITY(0);//拍照完成再关闭蜂鸣器供电
      cam_state = 0;
      cam_flag  = 0;
      iw_max = iw;
      iw = 0;
      pg_hdr = 0x0201;
      //len-=5;//去掉帧尾76 00 32 00 00
      osal_start_timerEx( SampleApp_TaskID, SAMPLEAPP_SEND_CAM_PKG_EVT, SAMPLEAPP_CAM_DELAY_VALUE);
      //osal_set_event( SampleApp_TaskID, SAMPLEAPP_SEND_CAM_PKG_EVT );
    }
  }
#endif 
}

/*********************************************************************
*********************************************************************/
