
/******************************************************************************
* @fn      TempSensor_writeZStackParameters
*
* @brief   Initialize ZStack Parameters
*
* @param   none
*
* @return  none
*/
static void TempSensor_writeZStackParameters(void)
{
  zstack_sysConfigWriteReq_t writeReq = {0};
  uint8_t extendedPANID[] = ZNWK_CONFIG_EXTENDED_PAN_ID;
  
  // HA specifies no Multicast, use group broadcast
  writeReq.has_nwkUseMultiCast = true;
  writeReq.nwkUseMultiCast = false;
  
  // Update the Default Channel List, defined in znwk_config.h
  writeReq.has_chanList = true;
  writeReq.chanList = ZNWK_DEFAULT_CHANLIST;
  
  // Update the Extended PAN ID, defined in znwk_config.h
  writeReq.has_extendedPANID = true;
  memcpy(&(writeReq.extendedPANID), extendedPANID, 8);
  
  // Update the config PAN ID, defined in znwk_config.h
  writeReq.has_panID = true;
  writeReq.panID = ZNWK_CONFIG_PAN_ID;
  //writeReq.panID =4431;     //0x4431;
  //writeReq.panID =1002; //0x0100;
  
  //dalila v2.2.10.4-beacon 1ms beacon request and back off configuration 
  //overwrite from app 
  writeReq.has_rejoinScanDuration = true;
  writeReq.rejoinScanDuration = 10000;   //10s
  writeReq.has_rejoinBackoffDuration = true;
  writeReq.rejoinBackoffDuration = 60000;  //1m
 
  
  (void)Zstackapi_sysConfigWriteReq(ztsEntity, &writeReq);
}


/******************************************************************************
* @fn      Sensor_process
*
* @brief   Application task processing start.
*
* @param   none
*
* @return  void
*/
static void Sensor_process(void)
{
  /* Forever loop */
  if(Util_isClockActive(&dataTransmitClkStruct) == true)
  {
    Util_stopClock(&dataTransmitClkStruct);
  }
  Clock_setTimeout( dataTransmitClkHandle,
                   (TEMPERATURE_SEND_DATA * TIMER_MS_ADJUSTMENT) );
  Util_startClock(&dataTransmitClkStruct);  
  //Init start counter is zero
  DataTransmit.SequenceNumber = 0;
  
  for(;;)
  {
    WatchdogIntClear();  
    
    ICall_ServiceEnum stackid;
    ICall_EntityID dest;
    zstackmsg_genericReq_t *pMsg;
	
	zstack_sysNwkInfoReadRsp_t * pzDevInfo;
  	zstack_DevState dDevState;
	int ICallerrNo;
	ICallerrNo = 99;
  	
	System_printf("ICall_wait start\r\n\0");
    /* Wait for response message */
	ICallerrNo = ICall_wait(ICALL_TIMEOUT_FOREVER);
	System_printf("In ICALL_WAIT\r\n\0");
	System_printf("ICallErrNo = %d \r\n\0", ICallerrNo);
    if(ICallerrNo == ICALL_ERRNO_SUCCESS)
    {
	  System_printf("In ICALL_WAIT\r\n\0");
	  pzDevInfo = zclport_getDeviceInfo(ztsEntity);
	  dDevState = pzDevInfo->devState;
	  outputDevState(dDevState);
      /* Retrieve the response message */
      if(ICall_fetchServiceMsg(&stackid, &dest, (void **)&pMsg)
         == ICALL_ERRNO_SUCCESS)
      {
        if( (stackid == ICALL_SERVICE_CLASS_ZSTACK) &&
           (dest == ztsEntity) )
        {
          if(pMsg)
          {
			
            TempSensor_processZStackMsgs(pMsg);
            
            // Free any separately allocated memory
            Zstackapi_freeIndMsg(pMsg);
          }
        }
        
        if(pMsg)
        {
          ICall_freeMsg(pMsg);
        }
      }
	  System_printf("ICall_fetchServiceMsg end\r\n\0");
      if(events & TEMPSENSOR_DATASEND_EVENT)      
      {
		System_printf("IN TEMPSENSOR_DATASEND_EVENT\r\n\0");
		/* 10秒タイマ開始 */
		if(Util_isClockActive(&dataTransmitClkStruct) == true)
		{
		  Util_stopClock(&dataTransmitClkStruct);
		}
		Clock_setTimeout( dataTransmitClkHandle,
						 (TEMPERATURE_SEND_DATA * TIMER_MS_ADJUSTMENT) );
		Util_startClock(&dataTransmitClkStruct);  
      	
		if(savedState == zstack_DevState_DEV_END_DEVICE){
		  System_printf("IN ZSTACK_STATE = DEV_END_DEVICE\r\n\0");
		  
			Sensor_sendData(); 	
			
			
		}
			
		events &= ~TEMPSENSOR_DATASEND_EVENT;
      }
      
#ifdef ZCL_EZMODE
      if(events & TEMPSENSOR_EZMODE_NEXTSTATE_EVT)
      {
        // going on to next state
        zcl_EZModeAction(EZMODE_ACTION_PROCESS, NULL);
        events &= ~TEMPSENSOR_EZMODE_NEXTSTATE_EVT;
      }
      
      if(events & TEMPSENSOR_EZMODE_TIMEOUT_EVT)
      {
        // EZ-Mode timed out
        zcl_EZModeAction(EZMODE_ACTION_TIMED_OUT, NULL);
        events &= ~TEMPSENSOR_EZMODE_TIMEOUT_EVT;
      }
#endif // ZLC_EZMODE
    }
    
  }

}

/******************************************************************************
* @fn      TempSensor_processZStackMsgs
*
* @brief   Process event from Stack
*
* @param   pMsg - pointer to incoming ZStack message to process
*
* @return  void
*/
static void TempSensor_processZStackMsgs(zstackmsg_genericReq_t *pMsg)
{
  switch(pMsg->hdr.event)
  {
  case zstackmsg_CmdIDs_DEV_STATE_CHANGE_IND:
    {
      // The ZStack Thread is indicating a state change
      zstackmsg_devStateChangeInd_t *pInd
        = (zstackmsg_devStateChangeInd_t *)pMsg;
      
      // Only process the state change if it actually changed.
      if(savedState != pInd->req.state)
      {
        savedState = pInd->req.state;
        
        if((pInd->req.state == zstack_DevState_DEV_ZB_COORD)
           || (pInd->req.state == zstack_DevState_DEV_ROUTER)
             || (pInd->req.state == zstack_DevState_DEV_END_DEVICE))
        {
          // The device is part of a network, get the device's
          // network parameters.
          pNwkInfo = zclport_getDeviceInfo(ztsEntity);
          
          
          if(pInd->req.state != zstack_DevState_DEV_END_DEVICE)
          {
            
            
          }
          else
          {
            // Change the default poll rate from 1 second to
            // the config setting in znwk_config.h
            TempSensor_setPollRate(1000);
          }
          
#if defined (ZCL_EZMODE)
          zcl_EZModeAction(EZMODE_ACTION_NETWORK_STARTED, NULL);
#endif
        }
      }
    }
    break;
    
#if defined (ZCL_EZMODE)
  case zstackmsg_CmdIDs_ZDO_MATCH_DESC_RSP:
    {
      zstackmsg_zdoMatchDescRspInd_t *pInd
        = (zstackmsg_zdoMatchDescRspInd_t *)pMsg;
      zclEZMode_ActionData_t actionData;
      ZDO_MatchDescRsp_t *pRsp;
      
      /*
      * Parse the Match Descriptor Response and give it to
      * the ZCL EZMode module to process
      */
      pRsp = (ZDO_MatchDescRsp_t *)ICall_allocMsg(
                                                  sizeof(ZDO_MatchDescRsp_t) + pInd->rsp.n_matchList);
      if(pRsp)
      {
        pRsp->status = pInd->rsp.status;
        pRsp->nwkAddr = pInd->rsp.nwkAddrOfInterest;
        pRsp->cnt = pInd->rsp.n_matchList;
        memcpy(pRsp->epList, pInd->rsp.pMatchList,
               pInd->rsp.n_matchList);
        
        actionData.pMatchDescRsp = pRsp;
        zcl_EZModeAction(EZMODE_ACTION_MATCH_DESC_RSP, &actionData);
        ICall_freeMsg(pRsp);
      }
    }
    break;
#endif // ZCL_EZMODE
    
  case zstackmsg_CmdIDs_AF_INCOMING_MSG_IND:
    {
      // Process incoming data messages
      zstackmsg_afIncomingMsgInd_t *pInd
        = (zstackmsg_afIncomingMsgInd_t *)pMsg;
      TempSensor_processAfIncomingMsgInd( &(pInd->req) );
    }
    break;
    
    /*
    * These are messages/indications from ZStack that this
    * application doesn't process.  These message can be
    * processed by your application, remove from this list and
    * process them here in this switch statement.
    */
  case zstackmsg_CmdIDs_AF_DATA_CONFIRM_IND:
  case zstackmsg_CmdIDs_ZDO_DEVICE_ANNOUNCE:
  case zstackmsg_CmdIDs_ZDO_NWK_ADDR_RSP:
  case zstackmsg_CmdIDs_ZDO_IEEE_ADDR_RSP:
  case zstackmsg_CmdIDs_ZDO_NODE_DESC_RSP:
  case zstackmsg_CmdIDs_ZDO_POWER_DESC_RSP:
  case zstackmsg_CmdIDs_ZDO_SIMPLE_DESC_RSP:
  case zstackmsg_CmdIDs_ZDO_ACTIVE_EP_RSP:
  case zstackmsg_CmdIDs_ZDO_COMPLEX_DESC_RSP:
  case zstackmsg_CmdIDs_ZDO_USER_DESC_RSP:
  case zstackmsg_CmdIDs_ZDO_USER_DESC_SET_RSP:
  case zstackmsg_CmdIDs_ZDO_SERVER_DISC_RSP:
  case zstackmsg_CmdIDs_ZDO_END_DEVICE_BIND_RSP:
  case zstackmsg_CmdIDs_ZDO_BIND_RSP:
  case zstackmsg_CmdIDs_ZDO_UNBIND_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_NWK_DISC_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_LQI_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_RTG_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_BIND_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_LEAVE_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_DIRECT_JOIN_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_PERMIT_JOIN_RSP:
  case zstackmsg_CmdIDs_ZDO_MGMT_NWK_UPDATE_NOTIFY:
  case zstackmsg_CmdIDs_ZDO_SRC_RTG_IND:
  case zstackmsg_CmdIDs_ZDO_CONCENTRATOR_IND:
  case zstackmsg_CmdIDs_ZDO_NWK_DISC_CNF:
  case zstackmsg_CmdIDs_ZDO_BEACON_NOTIFY_IND:
  case zstackmsg_CmdIDs_ZDO_JOIN_CNF:
  case zstackmsg_CmdIDs_ZDO_LEAVE_CNF:
  case zstackmsg_CmdIDs_ZDO_LEAVE_IND:
  case zstackmsg_CmdIDs_SYS_RESET_IND:
  case zstackmsg_CmdIDs_AF_REFLECT_ERROR_IND:
  case zstackmsg_CmdIDs_ZDO_TC_DEVICE_IND:
  case zstackmsg_CmdIDs_DEV_PERMIT_JOIN_IND:
    break;
    
  default:
    break;
  }
}

/******************************************************************************
*
* @fn          TempSensor_processAfIncomingMsgInd
*
* @brief       Process AF Incoming Message Indication message
*
* @param       pInMsg - pointer to incoming message
*
* @return      none
*
*/
static void TempSensor_processAfIncomingMsgInd(
                                               zstack_afIncomingMsgInd_t *pInMsg)
{
  afIncomingMSGPacket_t afMsg;
  
  /*
  * All incoming messages are passed to the ZCL message processor,
  * first convert to a structure that ZCL can process.
  */
  afMsg.groupId = pInMsg->groupID;
  afMsg.clusterId = pInMsg->clusterId;
  afMsg.srcAddr.endPoint = pInMsg->srcAddr.endpoint;
  afMsg.srcAddr.panId = pInMsg->srcAddr.panID;
  afMsg.srcAddr.addrMode = (afAddrMode_t)pInMsg->srcAddr.addrMode;
  if( (afMsg.srcAddr.addrMode == afAddr16Bit)
     || (afMsg.srcAddr.addrMode == afAddrGroup)
       || (afMsg.srcAddr.addrMode == afAddrBroadcast) )
  {
    afMsg.srcAddr.addr.shortAddr = pInMsg->srcAddr.addr.shortAddr;
  }
  else if(afMsg.srcAddr.addrMode == afAddr64Bit)
  {
    memcpy(afMsg.srcAddr.addr.extAddr, &(pInMsg->srcAddr.addr.extAddr), 8);
  }
  afMsg.macDestAddr = pInMsg->macDestAddr;
  afMsg.endPoint = pInMsg->endpoint;
  afMsg.wasBroadcast = pInMsg->wasBroadcast;
  afMsg.LinkQuality = pInMsg->linkQuality;
  afMsg.correlation = pInMsg->correlation;
  afMsg.rssi = pInMsg->rssi;
  afMsg.SecurityUse = pInMsg->securityUse;
  afMsg.timestamp = pInMsg->timestamp;
  afMsg.nwkSeqNum = pInMsg->nwkSeqNum;
  afMsg.macSrcAddr = pInMsg->macSrcAddr;
  afMsg.radius = pInMsg->radius;
  afMsg.cmd.TransSeqNumber = pInMsg->transSeqNum;
  afMsg.cmd.DataLength = pInMsg->n_payload;
  afMsg.cmd.Data = pInMsg->pPayload;
  
  rssi_send = afMsg.rssi;
  zcl_ProcessMessageMSG(&afMsg);
}


/*********************************************************************/
/* @fn      Sensor_sendData
*
* @brief   Called to send current sensor information to the coordinator
*
* @param   none
*
* @return  none３０
*/
/*********************************************************************/
static void Sensor_sendData(void)
{
  /*DataTransmit.node1= 0x0002; //Set node id higher bytes
  DataTransmit.node2= 0x0034; //Set node id lower bytes*/
  uint32_t nodeid1,nodeid2;
  uint32_t nodeid;
  
  nodeid1 = (uint32_t)(HWREG(CCFG_BASE + CCFG_O_IEEE_MAC_0));
  nodeid2 = (uint32_t)(HWREG(CCFG_BASE + CCFG_O_IEEE_MAC_1));
  nodeid = (uint32_t)(((nodeid1&0x00FF)<<16) || (nodeid2&0x00FF));
  DataTransmit.DataType = 0x0003;	// fixed data
  DataTransmit.SerialNumber = (int32_t)nodeid1;
								  
 //debug
 //DataTransmit.node1 = 2;
 //DataTransmit.node2 = 38;

  DataTransmit.firmware_version=20002;  //30101 Set firmware verison v3.01.01
 
  Copy_SensorParams();
	
  

#ifdef ZCL_REPORT
  zclReportCmd_t *pReportCmd;
  
  // Build and send a ZCL temperature reading to the matched device
  pReportCmd = ICall_malloc( sizeof(zclReportCmd_t) + sizeof(zclReport_t) );
  
  if(pReportCmd != NULL)
  {
	System_printf("pReportCmd Addr = %x\r\n\0",pReportCmd);
    afAddrType_t dstAddr;
	uint8 retVal=0xFF;
    
    // Fill in the destination address
    dstAddr.addrMode = (afAddrMode_t)ztsDstAddr.addrMode;
    dstAddr.addr.shortAddr = ztsDstAddr.addr.shortAddr;
    dstAddr.endPoint = ztsDstAddr.endpoint;
    dstAddr.panId = ztsDstAddr.panID;
    
    // Fill in the single attribute information for the temperature reading
    pReportCmd->numAttr = 1;
    pReportCmd->attrList[0].attrID = ATTRID_MS_TEMPERATURE_MEASURED_VALUE;
    pReportCmd->attrList[0].dataType = ZCL_DATATYPE_STRUCT;
    //pReportCmd->attrList[0].dataType = ZCL_DATATYPE_ARRAY;
    pReportCmd->attrList[0].attrData = (void *)&DataTransmit;
    //pReportCmd->attrList[0].attrData = (void *)&ucSensorPayload[0];
    
    // Call ZCL function to send the report
    retVal = zcl_SendReportCmd(TEMPSENSOR_EP, &dstAddr,
                      ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT,
                      pReportCmd,
                      ZCL_FRAME_SERVER_CLIENT_DIR,
                      true,
                      ztsTransID++);
    
    System_printf("SendReportCmd ret=%x\r\n\0", retVal);
    //printing status of zcl_SendReportCmd over UART for debugging
    
    ICall_free(pReportCmd);
  }
  else
  {
	System_printf("pReportCmd Addr = NULL\r\n\0");
  }
  
#endif  // ZCL_REPORT
}



#if defined (ZCL_EZMODE)
/*********************************************************************
* @fn      ezmodeCB
*
* @brief   The Application is informed of events. This can be used to
*          show on the UI what is going on during EZ-Mode
*          steering/finding/binding.
*
* @param   state - ignored
* @param   pData - EZMode state information
*
* @return  none
*/
static void ezmodeCB(zlcEZMode_State_t state, zclEZMode_CBData_t *pData)
{
  
  // time to go into identify mode
  if(state == EZMODE_STATE_IDENTIFYING)
  {
    
    ztsIdentifyTime = TEMPSENSOR_CONVERT_TO_SECONDS(EZMODE_TIME);
    TempSensor_processIdentifyTimeChange();
  }
  
  // autoclosing, show what happened (success, cancelled, etc...)
  if(state == EZMODE_STATE_AUTOCLOSE)
  {
    
  }
  
  // finished, either show DstAddr/EP, or nothing (depending on success or
  // not)
  if(state == EZMODE_STATE_FINISH)
  {
    // turn off identify mode
    ztsIdentifyTime = 0;
    TempSensor_processIdentifyTimeChange();
    
    
  }
}
#endif  // ZCL_EZMODE

/*********************************************************************
* @fn      TempSensor_processIdentifyTimeChange
*
* @brief   Called to process any change to the IdentifyTime attribute.
*
* @param   none
*
* @return  none
*/
static void TempSensor_processIdentifyTimeChange(void)
{
  // Stop the Identify timer
  if(Util_isClockActive(&identifyClkStruct) == true)
  {
    Util_stopClock(&identifyClkStruct);
  }
  
  // Are we still identifying?
  if(ztsIdentifyTime > 0)
  {
    // Continue with another timer
    Clock_setTimeout( identifyClkHandle,
                     ((ztsIdentifyTime * TEMPSENSOR_1SEC_MSEC) * TIMER_MS_ADJUSTMENT));
    Util_startClock(&identifyClkStruct);
    
  }
  else
  {
    
  }
}

/*********************************************************************
* @fn      TempSensor_processIdentifyCallback
*
* @brief   Callback from the ZCL General Cluster Library when
*          it received an Identity Command for this application.
*
* @param   pCmd - pointer to ZCL command
*
* @return  none
*/
static void TempSensor_processIdentifyCallback(zclIdentify_t *pCmd)
{
  // Save the incoming time and setup a timer
  ztsIdentifyTime = pCmd->identifyTime;
  TempSensor_processIdentifyTimeChange();
}

/*********************************************************************
* @fn      TempSensor_processIdentifyQueryResponseCallback
*
* @brief   Callback from the ZCL General Cluster Library when
*          it received an Identity Query Response Command for this application.
*
* @param   pRsp - pointer to the response message
*
* @return  none
*/
static void TempSensor_processIdentifyQueryResponseCallback(
                                                            zclIdentifyQueryRsp_t *pRsp)
{
#if defined (ZCL_EZMODE)
  {
    // ZCL EZMode will process this response message
    zclEZMode_ActionData_t data;
    data.pIdentifyQueryRsp = pRsp;
    zcl_EZModeAction(EZMODE_ACTION_IDENTIFY_QUERY_RSP, &data);
  }
#else
  // If you don't have EZMode enabled, add your own code to
  // Process this response message
  (void)pRsp;
#endif
}

#if defined (ZCL_EZMODE)
/*********************************************************************
* @fn      TempSensor_processEzmodeTimerCallback
*
* @brief   Callback function to process the setup an EZMode timer.
*
* @param   start - true to start a timeer, false to stop a timer
* @param   event_id - timer ID
* @param   timeout_value - in milliseconds
*
* @return  none
*/
static void TempSensor_processEzmodeTimerCallback(bool start,
                                                  uint16_t event_id,
                                                  uint32_t timeout_value)
{
  if(event_id == TEMPSENSOR_EZMODE_TIMEOUT_EVT)
  {
    // Setup the EZMode Timeout timer
    if(Util_isClockActive(&ezmodeTimeoutClkStruct) == true)
    {
      Util_stopClock(&ezmodeTimeoutClkStruct);
    }
    
    if(start)
    {
      Clock_setTimeout( ezmodeTimeoutClkHandle,
                       (timeout_value * TIMER_MS_ADJUSTMENT) );
      Util_startClock(&ezmodeTimeoutClkStruct);
    }
  }
  else if(event_id == TEMPSENSOR_EZMODE_NEXTSTATE_EVT)
  {
    // Setup the EZMode Next State timer
    if(Util_isClockActive(&ezmodeStateClkStruct) == true)
    {
      Util_stopClock(&ezmodeStateClkStruct);
    }
    
    if(start)
    {
      Clock_setTimeout( ezmodeStateClkHandle,
                       (timeout_value * TIMER_MS_ADJUSTMENT) );
      Util_startClock(&ezmodeStateClkStruct);
    }
  }
}

/******************************************************************************
* @fn      TempSensor_processEzmodeTimeoutCallback
*
* @brief   Timeout handler function
*
* @param   a0 - ignored
*
* @return  none
*/
static void TempSensor_processEzmodeTimeoutCallback(UArg a0)
{
  (void)a0; // Parameter is not used
  
  events |= TEMPSENSOR_EZMODE_TIMEOUT_EVT;
  
  // Wake up the application thread when it waits for clock event
  Semaphore_post(sem);
}

/******************************************************************************
* @fn      TempSensor_processEzmodeStateChangeCallback
*
* @brief   Timeout handler function
*
* @param   a0 - ignored
*
* @return  none
*/
static void TempSensor_processEzmodeStateChangeCallback(UArg a0)
{
  (void)a0; // Parameter is not used
  
  events |= TEMPSENSOR_EZMODE_NEXTSTATE_EVT;
  
  // Wake up the application thread when it waits for clock event
  Semaphore_post(sem);
}
#endif // ZCL_EZMODE

/******************************************************************************
* @fn      TempSensor_processIdentifyTimeoutCallback
*
* @brief   Timeout handler function
*
* @param   a0 - ignored
*
* @return  none
*/
static void TempSensor_processIdentifyTimeoutCallback(UArg a0)
{
  (void)a0; // Parameter is not used
  
  events |= TEMPSENSOR_IDENTIFY_TIMEOUT_EVT;
  
  // Wake up the application thread when it waits for clock event
  Semaphore_post(sem);
}


/******************************************************************************
* @fn      ZigbeeData timerCallback
*Date      18/4/2017
* @brief   Timeout handler function
*
* @param   a0 - ignored
*
* @return  none
*/
static void Send_SensorData(UArg a0)
{
  (void)a0; // Parameter is not used
  
  events |= TEMPSENSOR_DATASEND_EVENT;
  
  // Wake up the application thread when it waits for clock event
  Semaphore_post(sem);
}

/******************************************************************************
* @fn      TempSensor_setPollRate
*
* @brief   Set the ZStack Thread Poll Rate
*
* @param   newPollRate - new poll rate in milliseconds
*
* @return  none
*/
static void TempSensor_setPollRate(uint32_t newPollRate)
{
  zstack_sysConfigWriteReq_t writeReq = {0};
  
  // Set the new poll rate
  writeReq.has_pollRate = true;
  writeReq.pollRate = newPollRate;
  
  (void)Zstackapi_sysConfigWriteReq(ztsEntity, &writeReq);
}

/******************************************************************************
* @fn      TempSensor_startEzMode
*
* @brief   Start the EZMode process
*
* @param   none
*
* @return  none
*/
static void TempSensor_startEzMode(void)
{
#if defined (ZCL_EZMODE)
  zclEZMode_InvokeData_t ezModeData;
  // only bind on temperature measurement
  static uint16_t clusterIDs[] = { ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT };
  
  // Invoke EZ-Mode
  ezModeData.endpoint = TEMPSENSOR_EP; // endpoint on which to invoke EZ-Mode
  if( (savedState == zstack_DevState_DEV_ZB_COORD)
     || (savedState == zstack_DevState_DEV_ROUTER)
       || (savedState == zstack_DevState_DEV_END_DEVICE) )
  {
    ezModeData.onNetwork = true;  // node is already on the network
  }
  else
  {
    ezModeData.onNetwork = false; // node is not yet on the network
  }
  ezModeData.initiator = true;      // Temperature Sensor is an initiator
  ezModeData.numActiveInClusters = 1;
  ezModeData.pActiveInClusterIDs = clusterIDs;
  ezModeData.numActiveOutClusters = 0; // active output cluster
  ezModeData.pActiveOutClusterIDs = NULL;
  zcl_InvokeEZMode(&ezModeData);
  
#elif defined (ZSTACK_MANUAL_START)
  Zstart_discovery();
#endif // ZCL_EZMODE
}

static void Copy_SensorParams()
{
  
  ACCMTR_PARMS *ABC = &(g_stSensorParms.m_stAccmtrParms);
  
  DataTransmit.X_axisVal= (int16_t)(ABC->flAcclX_Grms * ACC_MULTIPLIER);
  DataTransmit.Y_axisVal= (int16_t)(ABC->flAcclY_Grms * ACC_MULTIPLIER);
  DataTransmit.Z_axisVal= (int16_t)(ABC->flAcclZ_Grms * ACC_MULTIPLIER);
  DataTransmit.Comp_Accl= (int16_t)(ABC->flAcclComp_Grms * ACC_MULTIPLIER);;
  DataTransmit.Freq_Accl= (int16_t)(ABC->usAcclX_Freq);
//  DataTransmit.Ampl_Accl= (int16_t)(ABC->usAcclX_Ampl);
  DataTransmit.Ampl_Accl= (int16_t)(ABC->Amplitude_long);
  DataTransmit.reserve1 =(int16_t)(ABC->Amplitude_short);
  DataTransmit.Angle = (int16_t)(ABC->Vib_Angle_deg);
  //DataTransmit.temperature_IR1= (int16_t)(temperature_celc * 10);
  DataTransmit.temperature_IR1= (int16_t)(Median_Filter(temperature_celc) * 10);        //change by Yuya Murata for Add median filter 20221011
  DataTransmit.PhaseDiff = (int16_t)(ABC->PhaseDiff_deg);
  DataTransmit.reserve2 = 0;
  
  if( 0x7FFF == DataTransmit.SequenceNumber){
   DataTransmit.SequenceNumber = 0;
  }else{
	DataTransmit.SequenceNumber++;
  }
 
  DataTransmit.battery_voltage= (int16_t)(ADC_Volts * 100);
  DataTransmit.radio_power =0; //rssi_send;
  DataTransmit.G_Peak_X = (int16_t)(ABC->flAcclX_Max * ACC_MULTIPLIER);
  DataTransmit.G_Peak_Y = (int16_t)(ABC->flAcclY_Max * ACC_MULTIPLIER);
  DataTransmit.G_Peak_Z = (int16_t)(ABC->flAcclZ_Max * ACC_MULTIPLIER);
  DataTransmit.reserve3 = 0;				
}

void outputDevState(zstack_DevState devState)
{
  	switch (devState)
	{
	case zstack_DevState_NWK_DISC:
		System_printf("savedState=DevState_NWK_DISC\r\n\0");
		break;
	case zstack_DevState_DEV_END_DEVICE:
		System_printf("savedState=DevState_DEV_END_DEVICE\r\n\0");
		break;
	case zstack_DevState_NWK_BACKOFF:
		System_printf("savedState=DevState_NWK_BACKOFF\r\n\0");
		break;
	default :
		System_printf("savedState=%d\r\n\0",savedState);
		break; 
	}
}
