
/**************************************************************************//**
  \file blank.c
  
  \brief Zigbee Aplikace, odeslani dat ku koordinatorovi

  \author

  \internal
    History:    

******************************************************************************/

// hlavickove soubory Bitcloudu
#include <appTimer.h>
#include <zdo.h>
#include <adc.h>
// hlavickove soubory Aplikace
#include "blank.h"
#include "boardabstraction.h"

//******* DEKLARACE KONSTANT*********

// pocet paketu k odeslani
#define PACKET_COUNT 1000
// prodleva mezi pakety
#define PACKET_DELAY 2000
// velkost uzitecnych dat, max 127B
#define PACKET_SIZE  2
// cilova adresa, 0x0000 je adresa koordinatora site
#define DEST_ADDR	 0x0000




// pocitadlo odeslanych paketu
uint16_t sendPacketCount=0;
uint16_t adcData = 0; //pridal M.S.

// deklarace callbacku pro casovace

void PacketTimerFired(void);
void AdcTimerFired(void);

// definice promenne pro stavovy automat aplikace
static AppState_t appState = APP_STATE_INITIAL;
// definice struktury dat
static AppDataMessageBuffer_t appData; 

// definice struktury pro pripojeni se do site
static ZDO_StartNetworkReq_t  zdoStartNetworkReq; 
// definice callbacku pripojeni se do site
static void ZDO_StartNetworkConf(ZDO_StartNetworkConf_t *confInfo);

// funkce start network
static void StartNetwork(void); 
// callback pro prijata data
static void DataReceived(APS_DataInd_t *ind); 
// callback pro odeslana data
static void DataConf(APS_DataConf_t *conf); 	
//definice funkce pro indikovani namerenych dat
static void adcReadInd(void); //pridal M.S.


//---------DEFINICE_FUNKCI---------------------

// packet timer
static HAL_AppTimer_t packetTimer = {
 .interval = PACKET_DELAY,
 .mode = TIMER_ONE_SHOT_MODE,
 .callback = PacketTimerFired,
};

//struktura ADC
static HAL_AdcParams_t adcParamDescriptor ={
	.resolution=RESOLUTION_10_BIT,
	.sampleRate=ADC_9600SPS,
	.voltageReference=AVCC,
	.bufferPointer=&adcData,
	.selectionsAmount=1,
	.callback=adcReadInd,
};

static void adcReadInd(void){
	static char value[20]; 
 	snprintf(value, sizeof(value), "ADC:%d", adcData);
	SendStrToConsole(value);
};


// definice SimpleDescriptoru
static SimpleDescriptor_t dataEndpointDescriptor =
{
  .endpoint = APP_DATA_SRC_ENDPOINT,
  .AppProfileId = APP_PROFILE_ID,
  .AppDeviceId = 1,
  .AppDeviceVersion = 1,
};

// definice struktury pro Endpoint
static APS_RegisterEndpointReq_t apsDataEndpointReq = { 
  .simpleDescriptor = &dataEndpointDescriptor,
  .APS_DataInd = DataReceived,
};

// definice struktury pro DataReq
static APS_DataReq_t apsDataReq = {
  .dstAddress = DEST_ADDR,
  .asduLength  = sizeof(appData.data),
  .dstAddrMode             = APS_SHORT_ADDRESS,                     // Short addressing mode
  .dstEndpoint             = APP_DATA_DST_ENDPOINT,                     // Destination endpoint
  .profileId               = APP_PROFILE_ID,                        // Profile ID
  .clusterId               = APP_CLUSTER_ID,                        // Destination cluster ID
  .srcEndpoint             = APP_DATA_SRC_ENDPOINT,                     // Source endpoint
  .radius                  = 0,                                     // Default radius
  .asdu                    = appData.data,               // ASDU pointer as an application message
  .APS_DataConf            = DataConf, 
};



/*******************************************************************************
  Description: application task handler.

  Parameters: none.
  
  Returns: nothing.
*******************************************************************************/
void APL_TaskHandler(void)
{
 switch(appState) 
 {	
	 case APP_STATE_INITIAL:
		InitHW();
	 	sendPacketCount = 0;
		 
		 if(HAL_OpenAdc(&adcParamDescriptor) == -1)
			SendStrToConsole("ADC open Failed!\r\n");
		else
			SendStrToConsole("ADC open OK.\r\n");
		
		StartNetwork();			  
	 break;

	 case APP_STATE_NETWORK_JOINED:
	 break;

	 case APP_STATE_SENDING:
	 break;

	 case APP_STATE_NETWORK_OUT:
	 	NetworkFailedIndication();
	 break;
 }
}

// callback pro prijimani dat
static void DataReceived(APS_DataInd_t* ind) {
 ind=ind;
}

// callback pro packetTimer
void PacketTimerFired(void)
{
// casovac vyprsel
	if(HAL_ReadAdc(HAL_ADC_CHANNEL1) == -1)
		SendStrToConsole("ADC read Failed!\r\n");
	else
		SendStrToConsole("ADC read OK.\r\n");
	
	appData.data[0]=MSG_TYPE;
	appData.data[1]=SENSOR_ID;
	appData.data[2]=(adcData>>8);
	appData.data[3]=(adcData & 0xFF);	
	APS_DataReq(&apsDataReq);
	SendStrToConsole("Packet sent\r\n");
}

// callback pro odeslani dat
static void DataConf(APS_DataConf_t *conf)
{
  HAL_StartAppTimer(&packetTimer);
}

/********************************************************************
  Description: start network
  Parameters: none.
  Returns:    none
********************************************************************/
static void StartNetwork(void)
{
  SendStrToConsole("Network connecting..."); 
  NetworkJoiningIndication();
  // TODO 1: prirad callback pro promennou zdoStartNetworkReq 
  zdoStartNetworkReq.ZDO_StartNetworkConf = ZDO_StartNetworkConf; 
  // TODO 2: spusti pokus o pripojeni do site pomoci funkce ZDO_StartNetworkReq(...)
  ZDO_StartNetworkReq(&zdoStartNetworkReq); // start network
}

/********************************************************************
  Description: ZDO_StartNetwork primitive confirmation was received.
  Parameters: confirmInfo - confirmation information
  Returns:    none
********************************************************************/
static void ZDO_StartNetworkConf(ZDO_StartNetworkConf_t *confInfo)
{
  // Pripojeni do site bylo uspesne
  if (ZDO_SUCCESS_STATUS == confInfo->status)     
  {
	// zmen stav automatu  
    appState = APP_STATE_NETWORK_JOINED;
	
	// indikuj pripojenou sit pomoci LED
    NetworkJoinedIndication();
    
	// TODO 3: Zaregistruj endpoint pro data, pomoci funkce APS_RegisterEndpointReq(...)
	APS_RegisterEndpointReq(&apsDataEndpointReq);
	SendStrToConsole("OK\r\n"); 
	
	// pokud je zarizeni typu router
		
		
				
		SendStrToConsole("Packet sending...");
		
		// zmen stav automatu
		appState = APP_STATE_SENDING;
		
		// indikuj odesilani paketu
		NetworkSendingDataIndication();
		
		// TODO 4: Spusti timer pro odesilani paketu
		HAL_StartAppTimer(&packetTimer);
	
  }
  else // Pripojeni do site se nezdarilo
  {  
  	SendStrToConsole("Failed\r\n"); 
	appState = APP_STATE_NETWORK_OUT;
  }
  // navrat do stavoveho automatu
  SYS_PostTask(APL_TASK_ID);
}


/*******************************************************************************
  Description: just a stub.

  Parameters: are not used.
  
  Returns: nothing.
*******************************************************************************/
void ZDO_MgmtNwkUpdateNotf(ZDO_MgmtNwkUpdateNotf_t *nwkParams) 
{
  if ((ZDO_NETWORK_LEFT_STATUS == nwkParams->status) || (ZDO_NETWORK_LOST_STATUS == nwkParams->status))
  {
    SendStrToConsole("Connection Lost\r\n"); 
	appState = APP_STATE_NETWORK_OUT;
  }
}

/*******************************************************************************
  Description: just a stub.

  Parameters: none.
  
  Returns: nothing.
*******************************************************************************/
void ZDO_WakeUpInd(void) 
{
}

#ifdef _BINDING_
/***********************************************************************************
  Stub for ZDO Binding Indication

  Parameters:
    bindInd - indication

  Return:
    none

 ***********************************************************************************/
void ZDO_BindIndication(ZDO_BindInd_t *bindInd) 
{
  (void)bindInd;
}

/***********************************************************************************
  Stub for ZDO Unbinding Indication

  Parameters:
    unbindInd - indication

  Return:
    none

 ***********************************************************************************/
void ZDO_UnbindIndication(ZDO_UnbindInd_t *unbindInd)
{
  (void)unbindInd;
}
#endif //_BINDING_

/**********************************************************************//**
  \brief Main - C program main start function

  \param none
  \return none
**************************************************************************/
int main(void)
{
  SYS_SysInit();

  for(;;)
  {
    SYS_RunTask();
  }
}

//eof blink.c
