/* Wait for channel to close */
static void UserAppSM_WaitChannelClose(void)
{
  /* Monitor the channel status to check if channel is closed */
  if(AntRadioStatus() == ANT_CLOSED)
  {
#ifdef MPG1
    LedOff(GREEN);
    LedOn(YELLOW);
#endif /* MPG1 */

#ifdef MPG2
    LedOn(GREEN0);
    LedOn(RED0);
#endif /* MPG2 */
    UserApp_StateMachine = UserAppSM_Idle;
  }
  
  /* Check for timeout */
  if( IsTimeUp(&UserApp_u32Timeout, TIMEOUT_VALUE) )
  {
#ifdef MPG1
    LedOff(GREEN);
    LedOff(YELLOW);
    LedBlink(RED, LED_4HZ);
#endif /* MPG1 */

#ifdef MPG2
    LedBlink(RED0, LED_4HZ);
    LedOff(GREEN0);
#endif /* MPG2 */
    
    UserApp_StateMachine = UserAppSM_Error;
  }
    
} /* end UserAppSM_WaitChannelClose() */
示例#2
0
void Con_Module_Quit_Proc(void)
{
    if((button[1].heldFlag == FALSE)&&(button[0].heldFlag == FALSE))
	{
	    module_state = MODULE_STATE_INIT;
		module_quit_flag = FALSE;
		
		LedBlink(LED_D1, BLINK_2HZ);
	    LedBlink(LED_D2, BLINK_2HZ);
	    Per_Dly_Ms(2000);
	}
}
示例#3
0
void ExternCounterInc(uint8_t num)
{
	uint32_t *pCounter;
	uint8_t *pSubcounter;
	if(num==NUM_CHANEL1)
	{
		pCounter = &param.counter1;
		pSubcounter = &param.subCounter1;
	}
	else
	{
		pCounter = &param.counter2;
		pSubcounter = &param.subCounter2;
	}

	if((!(param.status & E_STATUS_MAIN_MODE))&&(!(param.status & E_STATUS_ERROR)))
	{
		LedBlink(LED1_PxBIT, 3);
	}
	else
	{
		(*pSubcounter)++;

		if((*pSubcounter) >= param.counterType)
		{
			(*pSubcounter) = 0;
			(*pCounter) ++;
		}
	}
}
/* Wait for a message to be queued */
static void UserAppSM_Idle(void)
{
  /* Look for BUTTON 0 to open channel */
  if(WasButtonPressed(BUTTON0))
  {
    /* Got the button, so complete one-time actions before next state */
    ButtonAcknowledge(BUTTON0);
     LcdClearScreen();

     PixelBlockType sideScale = {0,19,128,5};
     LcdLoadBitmap(&au8Scale[0][0], &sideScale);
     PixelAddressType line0 = {0,0};
     LcdLoadString("183", LCD_FONT_SMALL, &line0);
     PixelAddressType line1 = {8,0};
     LcdLoadString("167", LCD_FONT_SMALL, &line1);
     PixelAddressType line2 = {16,0};
     LcdLoadString("151", LCD_FONT_SMALL, &line2);
     PixelAddressType line3 = {24,0};
     LcdLoadString("135", LCD_FONT_SMALL, &line3);
     PixelAddressType line4 = {32,0};
     LcdLoadString("119", LCD_FONT_SMALL, &line4);
     PixelAddressType line5 = {40,0};
     LcdLoadString("103", LCD_FONT_SMALL, &line5);
     PixelAddressType line6 = {48,0};
     LcdLoadString("87", LCD_FONT_SMALL, &line6);
     PixelAddressType line7 = {56,0};
     LcdLoadString("71", LCD_FONT_SMALL, &line7);
     
    /* Queue open channel and change LED0 from yellow to blinking green to indicate channel is opening */
    AntOpenChannel();

#ifdef MPG1
    LedOff(YELLOW);
    LedBlink(GREEN, LED_2HZ);
#endif /* MPG1 */    
    
#ifdef MPG2
    LedOff(RED0);
    LedBlink(GREEN0, LED_2HZ);
#endif /* MPG2 */
    
    /* Set timer and advance states */
    UserApp_u32Timeout = G_u32SystemTime1ms;
    UserApp_StateMachine = UserAppSM_WaitChannelOpen;
  }
    
} /* end UserAppSM_Idle() */
示例#5
0
文件: main.cpp 项目: Kreyl/nute
void App_t::OnUartCmd(CmdUart_t *PUart) {
    LedBlink(54);
    UartCmd_t *PCmd = &PUart->Cmd;
    __attribute__((unused)) int32_t dw32 = 0;  // May be unused in some configurations
    Uart.Printf("\r%S\r", PCmd->Name);
    // Handle command
    if(PCmd->NameIs("#Ping")) PUart->Ack(OK);

    else if(PCmd->NameIs("#SetLines")) {
        int32_t L[4];
        // Receive desired state
        if(PCmd->GetNextToken() != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->TryConvertTokenToNumber(&L[0]) != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->GetNextToken() != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->TryConvertTokenToNumber(&L[1]) != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->GetNextToken() != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->TryConvertTokenToNumber(&L[2]) != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->GetNextToken() != OK) { PUart->Ack(CMD_ERROR); return; }
        if(PCmd->TryConvertTokenToNumber(&L[3]) != OK) { PUart->Ack(CMD_ERROR); return; }
        // Setup state
        if(L[0] == 0) PinClear(PATH_GPIO, PATH21_PIN);
        else PinSet(PATH_GPIO, PATH21_PIN);
        if(L[1] == 0) PinClear(PATH_GPIO, PATH31_PIN);
        else PinSet(PATH_GPIO, PATH31_PIN);
        if(L[2] == 0) PinClear(PATH_GPIO, PATH22_PIN);
        else PinSet(PATH_GPIO, PATH22_PIN);
        if(L[3] == 0) PinClear(PATH_GPIO, PATH32_PIN);
        else PinSet(PATH_GPIO, PATH32_PIN);
        PUart->Ack(OK);
    }

    else if(PCmd->NameIs("#GetLines")) {
        char c[4];
        // Collect data
        c[0] = PinIsSet(PATH_GPIO, PATH21_PIN)? '1' : '0';
        c[1] = PinIsSet(PATH_GPIO, PATH31_PIN)? '1' : '0';
        c[2] = PinIsSet(PATH_GPIO, PATH22_PIN)? '1' : '0';
        c[3] = PinIsSet(PATH_GPIO, PATH32_PIN)? '1' : '0';
        // Send reply
        PUart->Printf("#Lines %c %c %c %c\r\n", c[0], c[1], c[2], c[3]);
    }

    else if(*PCmd->Name == '#') PUart->Ack(CMD_UNKNOWN);  // reply only #-started stuff
}
示例#6
0
void SaveResult(void)
{
    uint64_t finUnixTime;
    uint32_t finRecentMs;
    
    SendFinStatus(FIN_READY);
    LedBlink(FREQ_INIT_BLINK);
    Display("Save data");
    MyDelay(TIMEOUT_USER_READ_INFO);
    
    /*write time in fifo*/
    GetFinTime(&finUnixTime, &finRecentMs);
    WriteFinishTime(finUnixTime,finRecentMs);
    
    FifoPushLastFinished();
    
    /*print time result last skier finished*/
    DisplayLastSkierTime(LastSecTimeOnWay(),LastMillsTimeOnWay());/*LastTimeOnWaySecs(), LastTimeOnWayMillis()*/
    MyDelay(2*TIMEOUT_USER_READ_INFO);
}
示例#7
0
uint32_t TimeSynchronize(void)
{
    uint32_t result;
    
    LedBlink(FREQ_INIT_BLINK);
    
    /* network connect */
    if(NetworkStatus() == NETWORK_DISCONNECT)
    {
        Display("Network conn...");
        //MyDelay(TIMEOUT_DELAY);
    }
    else
    {  
        /* time sync */
        Display("Sync time...");
        if(NTPsync() == TIME_SYNC_OK)
        {
            Display("Sync ok");
            ClearRebootFlag();
            BLE_sendSystemStatus(STATUS_OK);
            ResetTimerForTimeSync();
            
            MyDelay(4 * TIMEOUT_USER_READ_INFO);
            
            result = TIME_SYNC_OK;
        }
        else
        {
            Display("Sync time error");
            SetRebootFlag();
            BLE_sendSystemStatus(STATUS_ERROR);
            MyDelay(4 * TIMEOUT_USER_READ_INFO);
            
            result = TIME_SYNC_ERR;
        }
    }
    
    return result;
}
/* Channel is open, so monitor data */
static void UserAppSM_ChannelOpen(void)
{
  static u8 u8LastState = 0xff;
  static u8 au8TickMessage[] = "EVENT x\n\r";  /* "x" at index [6] will be replaced by the current code */
  static u8 au8DataContent[] = "xxxxxxxxxxxxxxxx";
  static u8 au8LastAntData[ANT_APPLICATION_MESSAGE_BYTES] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  static u8 au8TestMessage[] = {0, 0, 0, 0, 0xA5, 0, 0, 0};
  bool bGotNewData;

  /* Check for BUTTON0 to close channel */
  if(WasButtonPressed(BUTTON0))
  {
    /* Got the button, so complete one-time actions before next state */
    ButtonAcknowledge(BUTTON0);
    
    /* Queue close channel and change LED to blinking green to indicate channel is closing */
    AntCloseChannel();
    u8LastState = 0xff;

#ifdef MPG1
    LedOff(YELLOW);
    LedOff(BLUE);
    LedBlink(GREEN, LED_2HZ);
#endif /* MPG1 */    
    
#ifdef MPG2
    LedOff(RED0);
    LedOff(BLUE0);
    LedBlink(GREEN0, LED_2HZ);
#endif /* MPG2 */
    
    /* Set timer and advance states */
    UserApp_u32Timeout = G_u32SystemTime1ms;
    UserApp_StateMachine = UserAppSM_WaitChannelClose;
  } /* end if(WasButtonPressed(BUTTON0)) */
  
  /* Always check for ANT messages */
  if( AntReadData() )
  {
     /* New data message: check what it is */
    if(G_eAntApiCurrentMessageClass == ANT_DATA)
    {
      UserApp_u32DataMsgCount++;
      
      /* Check if the new data is the same as the old data and update as we go */
      bGotNewData = TRUE;//used to be false
      for(u8 i = 0; i < ANT_APPLICATION_MESSAGE_BYTES; i++)
      {
        if(G_au8AntApiCurrentData[i] != au8LastAntData[i])
        {
          bGotNewData = TRUE;
          au8LastAntData[i] = G_au8AntApiCurrentData[i];

          au8DataContent[2 * i] = HexToASCIICharUpper(G_au8AntApiCurrentData[i] / 16);
          au8DataContent[2 * i + 1] = HexToASCIICharUpper(G_au8AntApiCurrentData[i] % 16); 
        }
      }
      
      
      if(bGotNewData)
      {
        /* We got new data: show on LCD */
#ifdef MPG1
        LCDClearChars(LINE2_START_ADDR, 20); 
        LCDMessage(LINE2_START_ADDR, au8DataContent); 
#endif /* MPG1 */    
    
#ifdef MPG2
        PixelAddressType sStringLocation1 = {0, 122}; 
        PixelAddressType sStringLocation2 = {8, 122};
        PixelAddressType sStringLocation3 = {16, 122};
        const unsigned char * HRTop = ReturnTopDigit(G_au8AntApiCurrentData[7]);
        const unsigned char * HRMiddle = ReturnMiddleDigit(G_au8AntApiCurrentData[7]);
        const unsigned char * HRBottom = ReturnLastDigit(G_au8AntApiCurrentData[7]);
        LcdLoadString(HRTop, LCD_FONT_SMALL, &sStringLocation1); 
        LcdLoadString(HRMiddle, LCD_FONT_SMALL, &sStringLocation2); 
        LcdLoadString(HRBottom, LCD_FONT_SMALL, &sStringLocation3); 
        //LcdLoadString(" ",LCD_FONT_SMALL, &sStringLocation);
        printToScreen(G_au8AntApiCurrentData[7]);
#endif /* MPG2 */

        /* Update our local message counter and send the message back */
        au8TestMessage[7]++;
        if(au8TestMessage[7] == 0)
        {
          au8TestMessage[6]++;
          if(au8TestMessage[6] == 0)
          {
            au8TestMessage[5]++;
          }
        }
        AntQueueBroadcastMessage(au8TestMessage);

        /* Check for a special packet and respond */
#ifdef MPG1
        if(G_au8AntApiCurrentData[0] == 0xA5)
        {
          LedOff(LCD_RED);
          LedOff(LCD_GREEN);
          LedOff(LCD_BLUE);
          
          if(G_au8AntApiCurrentData[1] == 1)
          {
            LedOn(LCD_RED);
          }
          
          if(G_au8AntApiCurrentData[2] == 1)
          {
            LedOn(LCD_GREEN);
          }

          if(G_au8AntApiCurrentData[3] == 1)
          {
            LedOn(LCD_BLUE);
          }
        }
#endif /* MPG1 */    
    
#ifdef MPG2
        /*if(G_au8AntApiCurrentData[0] == 0xFF)
        {
          LedOff(RED3);
          LedOff(GREEN3);
          LedOff(BLUE3);
          
          if(G_au8AntApiCurrentData[1] == 0xFF)
          {
            LedOn(RED3);
          }
          
          if(G_au8AntApiCurrentData[2] == 0xFF)
          {
            LedOn(GREEN3);
          }

          if(G_au8AntApiCurrentData[3] == 0xFF)
          {
            LedOn(BLUE3);
          }
        }*/
        
        
#endif /* MPG2 */
      } /* end if(bGotNewData) */
    } /* end if(G_eAntApiCurrentMessageClass == ANT_DATA) */
    
    else if(G_eAntApiCurrentMessageClass == ANT_TICK)
    {
      UserApp_u32TickMsgCount++;

      /* Look at the TICK contents to check the event code and respond only if it's different */
      if(u8LastState != G_au8AntApiCurrentData[ANT_TICK_MSG_EVENT_CODE_INDEX])
      {
        /* The state changed so update u8LastState and queue a debug message */
        u8LastState = G_au8AntApiCurrentData[ANT_TICK_MSG_EVENT_CODE_INDEX];
        au8TickMessage[6] = HexToASCIICharUpper(u8LastState);
        DebugPrintf(au8TickMessage);

        /* Parse u8LastState to update LED status */
        switch (u8LastState)
        {
#ifdef MPG1
          /* If we are synced with a device, blue is solid */
          case RESPONSE_NO_ERROR:
          {
            LedOff(GREEN);
            LedOn(BLUE);
            break;
          }

          /* If we are paired but missing messages, blue blinks */
          case EVENT_RX_FAIL:
          {
            LedOff(GREEN);
            LedBlink(BLUE, LED_2HZ);
            break;
          }

          /* If we drop to search, LED is green */
          case EVENT_RX_FAIL_GO_TO_SEARCH:
          {
            LedOff(BLUE);
            LedOn(GREEN);
            break;
          }
#endif /* MPG 1 */
#ifdef MPG2
          /* If we are synced with a device, blue is solid */
          case RESPONSE_NO_ERROR:
          {
            LedOff(GREEN0);
            LedOn(BLUE0);
            break;
          }

          /* If we are paired but missing messages, blue blinks */
          case EVENT_RX_FAIL:
          {
            LedOff(GREEN0);
            LedBlink(BLUE0, LED_2HZ);
            break;
          }

          /* If we drop to search, LED is green */
          case EVENT_RX_FAIL_GO_TO_SEARCH:
          {
            LedOff(BLUE0);
            LedOn(GREEN0);
            break;
          }
#endif /* MPG 2 */
          /* If the search times out, the channel should automatically close */
          case EVENT_RX_SEARCH_TIMEOUT:
          {
            DebugPrintf("Search timeout\r\n");
            break;
          }

          default:
          {
            DebugPrintf("Unexpected Event\r\n");
            break;
          }
        } /* end switch (G_au8AntApiCurrentData) */
      } /* end if (u8LastState != G_au8AntApiCurrentData[ANT_TICK_MSG_EVENT_CODE_INDEX]) */
    } /* end else if(G_eAntApiCurrentMessageClass == ANT_TICK) */
    
  } /* end AntReadData() */
  
  /* A slave channel can close on its own, so explicitly check channel status */
  if(AntRadioStatus() != ANT_OPEN)
  {
#ifdef MPG1
    LedBlink(GREEN, LED_2HZ);
    LedOff(BLUE);
#endif /* MPG1 */

#ifdef MPG2
    LedBlink(GREEN0, LED_2HZ);
    LedOff(BLUE0);
#endif /* MPG2 */
    u8LastState = 0xff;
    
    UserApp_u32Timeout = G_u32SystemTime1ms;
    UserApp_StateMachine = UserAppSM_WaitChannelClose;
  } /* if(AntRadioStatus() != ANT_OPEN) */
      
} /* end UserAppSM_ChannelOpen() */
/*--------------------------------------------------------------------------------------------------------------------
Function: UserAppInitialize

Description:
Initializes the State Machine and its variables.

Requires:
  -

Promises:
  - 
*/
void UserAppInitialize(void)
{
  u8 au8WelcomeMessage[] = "REAL TIME HR GRAPH";
  u8 au8Instructions[] = "B0 toggles radio";
  
  /* Clear screen and place start messages */
#ifdef MPG1
  LCDCommand(LCD_CLEAR_CMD);
  LCDMessage(LINE1_START_ADDR, au8WelcomeMessage); 
  LCDMessage(LINE2_START_ADDR, au8Instructions); 

  /* Start with LED0 in RED state = channel is not configured */
  LedOn(RED);
#endif /* MPG1 */
  
#ifdef MPG2
  PixelAddressType sStringLocation = {LCD_SMALL_FONT_LINE0, LCD_LEFT_MOST_COLUMN}; 
  LcdClearScreen();
  LcdLoadString(au8WelcomeMessage, LCD_FONT_SMALL, &sStringLocation); 
  sStringLocation.u16PixelRowAddress = LCD_SMALL_FONT_LINE1;
  LcdLoadString(au8Instructions, LCD_FONT_SMALL, &sStringLocation); 
  
  /* Start with LED0 in RED state = channel is not configured */
  LedOn(RED0);
#endif /* MPG2 */
  
 /* Configure ANT for this application */
  G_stAntSetupData.AntChannel          = ANT_CHANNEL_USERAPP;
  G_stAntSetupData.AntSerialLo         = ANT_SERIAL_LO_USERAPP;
  G_stAntSetupData.AntSerialHi         = ANT_SERIAL_HI_USERAPP;
  G_stAntSetupData.AntDeviceType       = ANT_DEVICE_TYPE_USERAPP;
  G_stAntSetupData.AntTransmissionType = ANT_TRANSMISSION_TYPE_USERAPP;
  G_stAntSetupData.AntChannelPeriodLo  = ANT_CHANNEL_PERIOD_LO_USERAPP;
  G_stAntSetupData.AntChannelPeriodHi  = ANT_CHANNEL_PERIOD_HI_USERAPP;
  G_stAntSetupData.AntFrequency        = ANT_FREQUENCY_USERAPP;
  G_stAntSetupData.AntTxPower          = ANT_TX_POWER_USERAPP;
 
  /* If good initialization, set state to Idle */
  if( AntChannelConfig(ANT_SLAVE) )
  {
    /* Channel is configured, so change LED to yellow */
#ifdef MPG1
    LedOff(RED);
    LedOn(YELLOW);
#endif /* MPG1 */
    
#ifdef MPG2
    LedOn(GREEN0);
#endif /* MPG2 */
    
    UserApp_StateMachine = UserAppSM_Idle;
  }
  else
  {
    /* The task isn't properly initialized, so shut it down and don't run */
#ifdef MPG1
    LedBlink(RED, LED_4HZ);
#endif /* MPG1 */
    
#ifdef MPG2
    LedBlink(RED0, LED_4HZ);
#endif /* MPG2 */

    UserApp_StateMachine = UserAppSM_Error;
  }

} /* end UserAppInitialize() */
示例#10
0
static void LedActorOnRequestBlink(PVOID pParam)
{
	char* message = (char*)pParam;
	char **znpSplitMessage;
	if (pLedActor == NULL) return;
	json_t* payloadJson = NULL;
	json_t* paramsJson = NULL;
	json_t* redJson = NULL;
	json_t* greenJson = NULL;
	json_t* blueJson = NULL;
	json_t* responseJson = NULL;
	json_t* statusJson = NULL;
	json_t* periodJson = NULL;
	int period;
	BYTE red, green, blue;
	PACTORHEADER header;
	char* responseTopic;
	char* responseMessage;
	char* colorMessage;
	znpSplitMessage = ActorSplitMessage(message);
	if (znpSplitMessage == NULL)
		return;
	// parse header to get origin of message
	header = ActorParseHeader(znpSplitMessage[0]);
	if (header == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		return;
	}
	//parse payload
	payloadJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	if (payloadJson == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	paramsJson = json_object_get(payloadJson, "params");
	if (paramsJson == NULL)
	{
		json_decref(payloadJson);
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	redJson = json_object_get(paramsJson, "red");
	if (redJson == NULL)
		red = 255;
	else
		red = json_integer_value(redJson);

	greenJson = json_object_get(paramsJson, "green");
	if (greenJson == NULL)
		green = 255;
	else
		green = json_integer_value(greenJson);

	blueJson = json_object_get(paramsJson, "blue");
	if (blueJson == NULL)
		blue = 255;
	else
		blue = json_integer_value(blueJson);

	periodJson = json_object_get(paramsJson, "period");
	if (periodJson == NULL)
		period = 2000;
	else
		period = json_integer_value(periodJson);

	int result = LedBlink(red, green, blue, period);

	//make response package
	responseJson = json_object();
	statusJson = json_object();
	json_t* requestJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	json_object_set(responseJson, "request", requestJson);
	json_decref(requestJson);
	json_t* resultJson;
	colorMessage = calloc(20, sizeof(BYTE));
	sprintf(colorMessage, "0x%02X%02X%02X", red, green, blue);
	if (result == 0)
	{
		LedActorPublishStateChange(colorMessage, LED_BLINK, period);
		resultJson = json_string("status.success");
	}
	else
	{
		LedActorPublishStateChange(colorMessage, LED_OFF, 0);
		resultJson = json_string("status.failure");
	}
	json_decref(periodJson);
	if (redJson)
		json_decref(redJson);
	if (greenJson)
		json_decref(greenJson);
	if (blueJson)
		json_decref(blueJson);
	free(colorMessage);
	json_decref(paramsJson);
	json_decref(payloadJson);
	json_object_set(statusJson, "status", resultJson);
	json_decref(resultJson);
	json_object_set(responseJson, "response", statusJson);
	json_decref(statusJson);
	responseMessage = json_dumps(responseJson, JSON_INDENT(4) | JSON_REAL_PRECISION(4));
	//responseTopic = ActorMakeTopicName(header->origin, "/:response");
	responseTopic = StrDup(header->origin);
	ActorFreeHeaderStruct(header);
	json_decref(responseJson);
	ActorFreeSplitMessage(znpSplitMessage);
	ActorSend(pLedActor, responseTopic, responseMessage, NULL, FALSE, "response");
	free(responseMessage);
	free(responseTopic);
}
示例#11
0
文件: main.c 项目: PolyakovV/Unit213
int32_t main()
{

/***************************************************************************
*       ClkInit()
****************************************************************************/
	ClkInit();

/***************************************************************************
*       GPIOInit();
****************************************************************************/
//	DrvGPIO_InitFunction(E_FUNC_GPIO);
	outpw(&SYS->P0_MFP, 0);
	outpw(&SYS->P1_MFP, 0);
	outpw(&SYS->P2_MFP, 0);
	outpw(&SYS->P3_MFP, 0);
	outpw(&SYS->P4_MFP, 0);

	_GPIO_SET_PIN_MODE(MODEM_ON_PORT, MODEM_ON_PIN, GPIO_PMD_OUTPUT);
	ModuleOn(TRUE);

	_GPIO_SET_PIN_MODE(MODEM_POWER_PORT, MODEM_POWER_PIN, GPIO_PMD_OUTPUT);
	ModulePowerOn(FALSE);

	_GPIO_SET_PIN_MODE(LOCK_POWER_PORT, LOCK_POWER_PIN, GPIO_PMD_OUTPUT);
	LockPower(FALSE);

	_GPIO_SET_PIN_MODE(KEY_HELP_PORT, KEY_HELP_PIN, GPIO_PMD_QUASI);
	_GPIO_SET_PIN_MODE(KEY_BAT_PORT, KEY_BAT_PIN, GPIO_PMD_QUASI);

	_GPIO_SET_PIN_MODE(SLEEP_PORT, SLEEP_PIN, GPIO_PMD_OUTPUT);
	ModemSleep(FALSE);

	_GPIO_SET_PIN_MODE(LED_PORT, LED_PIN, GPIO_PMD_OUTPUT);
	
	LedDark();
	
	_GPIO_SET_PIN_MODE(INT_PORT, INT_PIN, GPIO_PMD_INPUT);

/***************************************************************************
*       TimerInit();
****************************************************************************/
	SysTick_Config(SYS_TICK);
//	SYS_LockReg();

/***************************************************************************
*       UartInit();
****************************************************************************/
	UartInit();
//	debug(VERSION);
//	DrvSYS_GetPLLClockFreq();

/***************************************************************************
*       WatchdogInit();
****************************************************************************/	
	WatchdogInit();

//	udpTest();
	NvInit();



 	WhatToDo();
	AdcInit();
	
	
	
	WaitLockPower();

  LockPower(!custermParam.param.lockState);


	InitMsgDebug();	
	
	if( Communication(10) == FALSE )
		SoftReset();

	if( isCheckingBattery )
	{
		delay_50ms(40);
		MeasurePower(4);
	}
	else
	{
		MeasurePower(2);
	}
					
	Flag_ModuleOn = TRUE;
	//Flag_ModuleOn = TRUE;
	ModemVolumeInit();

	///--------------------24.11.2015----------------------------------------------
	////////////////////////////////////////////////////////////////////////////////////////
while(PressHelp()&&(tmp_my<200)&&(PressBatter())){
	tmp_my++;
		
	delay_50ms(1);
if (tmp_my>=150) {
	  LedLight(144);
	    if (custermParam.param.lockState) {
														LockPower(TRUE);
														custermParam.param.lockState = FALSE;
												    WriteToNv( &custermParam ); //- save to eeprom
  													PlayVoice("\"unitUnlock.wav\",2\r");
														delay_ms(2000);
			                      LockPower(FALSE);
			
			} else {
	                          //  debug("ins");
															while(PressBatter()){};
														 tmp_my=0;
												while (tmp_my<25){               
																											tmp_my++;
																											delay_ms(150);
																											if (PressBatter()){counterPress++;
																																				while(!PressBatter()){};
																																					}
																										  if (counterPress>2){ 
																																					PlayVoice("\"unitLock.wav\",2\r");
																																					delay_ms(2000);
																																					custermParam.param.lockState = TRUE;
																																					WriteToNv( &custermParam ); //- save to eeprom
																																		      tmp_my=0;
																																					delay_ms(2000);
																																					LockPower(DISABLE);

																																				}
																											}
													LedBlink();
										} 
					///////				
			tmp_my=0;
			}

}

while(custermParam.param.lockState){}
 
///////////////////////////////////////////////////////////////////////////////////////////////													
#ifdef DELAY_TEST
	DelayTest();
#endif
	PowerOn();
	
	

	
	if(state==STATE_POWERING_DOWN || Flag_Power_Down)
	{
		Flag_Power_Down = FALSE;
		EnterPowerDown();
		while( TimerWait )
			FeedWatchdog();
		PowerDown();
		//不会返回
	}
	
	InitVariables();
	  
	if(state == STATE_NULL)
	{
		state = STATE_1ST_CALL;
		TimerWait = 100;	// 5 s
	}
	
	TimerTestMode = 6000;
	//debug("ent main loop");
	while(1)
	{  
			
		///--------------------
				if (!TimerTestMode && state==STATE_TEST)
										{ 
										PlayMusic(MUSIC_PD);
										EnterPowerDown();
										}
		
		///--------------------
		
		if( Flag_Incomming )
		{
	#if 1
			TimerWait = 200;
			Flag_Incomming = FALSE;
			TimerStandby = custermParam.param.delay;
			//if(state != STATE_ACTIVE)
			{
				ModemSleep(FALSE);
				state = STATE_INCOMMING;
			}
	#else
			Flag_Incomming = FALSE;
			if(state != STATE_INCOMMING)
			{
				state = STATE_INCOMMING;
				ModemSleep(FALSE);
				EnterAnswer();
			}
	#endif
		}
		
		if(TimerWait == 0)
		{
			switch(state)
			{
									
			case STATE_POWERING_DOWN:
				PowerDown();
				break;

			case STATE_1ST_CALL:
				RegisterWait();
				break;

			case STATE_REGISTER_OK:	
				GetCpsiInfo();
				if( Flag_ObtainCpsi==TRUE)
				{
					state = STATE_GSM_STEADY;
					if( Flag_SimExist )
					{
						//delay_50ms(200);
						SockOpen();
						TimerWait = 400;
					}
					else
					{
						TimerWait = 60;
					}
				}
				else
				{
					TimerWait = 70;
				}
				break;

			case STATE_GSM_STEADY:	
				if( gPhoneNumOk==PHONE_NUM_READY || Flag_SimExist==FALSE)
					EnterCall();
				else
					TimerWait = 40;
				break;
				
			case STATE_CALL_PROMPT:
				Call();
				break;

			case STATE_ALERT:
				EnterCallFail();
				break;
			
			case STATE_NEXT_CALL:
				Redial();
				break;				

			case STATE_BATT_DISPLAY:
				EnterPowerDown();
				break;

			case STATE_INCOMMING:
				TimerStandby = custermParam.param.delay;
				EnterStandby();
				break;
			}
		}

		if( TimerSock==0 && Flag_SimExist
			&& ( (state>=STATE_GSM_STEADY && state<STATE_STANDBY) || progress>=TEST_GPS ) )
		{
			switch(sockState)
			{
			//case SOCKSTATE_NULL:
			case SOCKSTATE_CONFIG:				
			case SOCKSTATE_OPENNING:
				SockOpen();	// 打开失败,从新打开
				break;

			case SOCKSTATE_OPENED:
				SendAtWaitRsq(50, 1, FALSE, "AT+CIPOPEN=0,\"UDP\",,,%s\r\n", custermParam.param.local_port);
				TimerSock = 80;
				break;
	#if 0
			case SOCKSTATE_CONNECTING:
				SockConnect();	// 连接失败,从新连接
				break;
	#endif
			case SOCKSTATE_CONNECT_OK:		
				if( witchApn == 1)
					ClientInit();
				break;

			default:
				break;
			}
		}

		KeyHandle();

		SecondHandle();
		//SignalCheck();
		BatterCheck();
		PowerDownHandle();
		MsgHandle();
											
		if( Flag_SimExist )
		{
			UdpHandle();
			SmsHandle();
			PowerDownHandle();
		}
		
		FeedWatchdog();
	}
}