//==============================================================================
// This is The function that is called by the Main program to initialize
//   the input controller, which in this case is the PS2 controller
//   process any commands.
//==============================================================================
void DIYXBeeController::Init(void)
{

  // Lets try to initialize the XBEE to use
  InitXBee();


#ifdef __AVR__
#if not defined(UBRR1H)
  XBeeSerial.listen();
#endif    
#endif     
  // Clear any stuff left in the buffer
  delay(20);
  ClearXBeeInputBuffer();

#if 0 //def DBGSerial    
  word wMy = GetXBeeMY();
  DBGSerial.print("XBee My: ");
  DBGSerial.println(wMy, HEX);
#endif    
  g_BodyYOffset = 0;
  g_BodyYSift = 0;
  bXBeeControlMode = WALKMODE;

  g_fDisplayLiPo = true;    // assume we display the lipo state
}
Esempio n. 2
0
/****************************************************************************
 Function
    RunLobbyistSM

 Parameters
   ES_Event : the event to process

 Returns
   ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise

 Description
   Deals with the high level state transitions of the Lobbyist state machine.
****************************************************************************/
ES_Event RunLobbyistSM( ES_Event ThisEvent )
{
  ES_Event ReturnEvent;
  ReturnEvent.EventType = ES_NO_EVENT; // assume no errors

  switch ( CurrentState )
  {
    case InitPState :       // If current state is initial Psedudo State
        if ( ThisEvent.EventType == ES_INIT ) // only respond to ES_Init
        {
            //Prep the timer hardware.
						printf("Init Steering \r\n");
						InitSteering();					// Initialize the steering systems
						printf("Init Packets \r\n");					
						InitPackets(); 					// Initialize packet array
						printf("Init XBee \r\n");
            InitXBee(); 						// Initialize the comms
						printf("Init Lift Fan \r\n");
						InitLiftFan();					// Initialize the lift fan
            //Initialize the DMC.
            CurrentState = WaitingForPair;
        }
    break;

    case WaitingForPair :
      switch ( ThisEvent.EventType )
      {
        //If the event is a pair request, change state to pairing and wait for the key.
        case MESSAGE_RECEIVED:
					// Read incoming message
					message = GetMessageData();
					// Check that message is a pair request and that it's meant for us
					if(*message == PAIR_REQUEST_HEADER && CheckLobbyistNumber() && GetApiIdentifier() == INCOMING_PACKET_API_IDENTIFIER){  // Ensure that this is not a Tx success receive
						printf("\r\n Current Message Size: %d ", GetMessageDataSize());
						// If we passed the checks, we're now paired. Start timers.
						printf("\n\r\nPair request received in unpaired state.");
						ES_Timer_InitTimer(UNPAIR_TIMER, UNPAIR_TIME); //Start the 45s timer
						ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Start the 1s timer
						
						
						TurnOnLiftFan();     					//Start the lift fan
						//Update DMC
						
						// Recognize our new pac daddy
						pairedAddress = GetSenderAddress() ;
						// Send an ACK back to the sender
						TransmitStatusPacket(PAIRED); 
						// Set the pair time
						PairTimeLeft = 45;
						CurrentState = PairedAwaitEncryptionKey;
				}
        break;
        default :
            ; 
      }
    break;

    case PairedAwaitEncryptionKey:
      switch(ThisEvent.EventType){
        case MESSAGE_RECEIVED:
					// Check sender and message
					message = GetMessageData();
					uint16_t sender = GetSenderAddress() ;
					if(sender == pairedAddress && *message == KEY_SEND_HEADER){
						printf("\n\r\nKey received in pairing state.");
						//Save the key 
						SetKey((message+1)); // Make sure to +1 to start after header byte
						
						ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Restart the 1s timer
						TransmitStatusPacket(PAIRED); //transmit status with the pairing bit set.
						CurrentState = PairedAwaitControl;
						printf("\r\n In paired await control");
				}
        break;
        case ES_TIMEOUT: // if there is a timeout on the 1s timer
					printf("\n\r\n1s timeout in pairing - moving to awaiting pair.");
					TurnOffLiftFan(); 										//Turn off the lift fan
					//Update DMC to avaiable for pairing
					ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
					ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
					TransmitStatusPacket(UNPAIRED); 			//Transmit status with the pairing bit cleared.
					CurrentState = WaitingForPair;
        break;
      }
    break;

    case PairedAwaitControl:
      switch(ThisEvent.EventType){
        case MESSAGE_RECEIVED:
					// See who sent the message
					uint16_t sender = GetSenderAddress() ;
					if(sender == pairedAddress){  // Only attempt decrypt if from sender
						message = DecryptMessage(GetMessageData(),GetMessageDataSize());
						RotateCipher();
	//					printf("\r\n Rotating Key");
						if(*message == CNTRL_REQUEST_HEADER){
							//printf("\n\r\nCommand received in the paired state.");
							ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Restart the control command timer.
							ExecuteControl(); //Execute the control command.
							TransmitStatusPacket(PAIRED);// ACK YAY. Transmit the status with pairing bit set.
						} else {
							printf("\n\r Not a valid control packet received, Header: %d", *message);
						}
				}
        break;

        case ES_TIMEOUT: //Either the 1s or 45s timer
				case MANUAL_UNPAIR: // Or if the pair is manual
				case DECRYPT_FAIL:  // Or if the decryption failed
          if(ThisEvent.EventParam == UNPAIR_TIMER){
						// Keep track of how long is left on UNPAIR_TIMER
              PairTimeLeft--;
              printf("\n\r\nTime until unpair: %ds", PairTimeLeft);
						// If timer has run for 45 s
              if(PairTimeLeft == 0){    
                CurrentState = WaitingForPair;
								TurnOffLiftFan(); 										//Turn off the lift fan
								UpdateSteering(OFF,OFF);							//Turn off the propulsion fans
								//Update DMC to avaiable for pairing
								ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
								ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
                printf("\n\r\nUnpairing.");
						// If timer is not at 0, reinitialize the timer again for 1s to keep counting
              }else{
								 ES_Timer_InitTimer(UNPAIR_TIMER, UNPAIR_TIME); //Start the 45s timer
							}								
						} else {  
							// If we have an event NOT on the 45s timer, unpair
								printf("\n\r\nTimeout in the paired state. Moving to waiting for pair \r\n");
								TurnOffLiftFan(); 										//Turn off the lift fan
								UpdateSteering(OFF,OFF);							//Turn off the propulsion fans
								//Update DMC to avaiable for pairing
								ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
								ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
								if(ThisEvent.EventType == DECRYPT_FAIL){	// If this event came from a decryption failure 		//// WEHERE DOES THIS COME FROM?
									TransmitStatusPacket(DECRYPT_FAILURE);	// Transmit status with the decryption fail bit set
								} else {
									TransmitStatusPacket(UNPAIRED); 				//Transmit status with the pairing bit cleared.
								}
								CurrentState = WaitingForPair;
              }

        break;
      }

    break;

  default :
    break;
  }

  return ReturnEvent;
}