예제 #1
0
bool XBeeUtil::getRadioAddress(XBee* xbee, int32_t& msb, int32_t& lsb, Stream* debug_stream){

	bool toRet = true;
	XBeeUtil::debug_stream = debug_stream;

	AtCommandRequest atRequest = AtCommandRequest();
	AtCommandResponse atResponse = AtCommandResponse();

	uint8_t SH_cmd[] = { 'S', 'H' };
	uint8_t SL_cmd[] = { 'S', 'L' };


	atRequest.setCommand(SH_cmd);
	if (XBeeUtil::atCommand(xbee, atRequest, atResponse) && atResponse.getValueLength() == 4
			&& XBeeUtil::readAtResponseInt(xbee, atResponse, msb)) {
	} else {
		toRet = false;
	}

	atRequest.setCommand(SL_cmd);
	if (XBeeUtil::atCommand(xbee, atRequest, atResponse) && atResponse.getValueLength() == 4
			&& XBeeUtil::readAtResponseInt(xbee, atResponse, lsb)) {
	} else {
		toRet = false;
	}


	return toRet;
}
/**	EXPERT FUNCTION: Sends an ATCommand and returns the response as a 32-bit integer.
	If you specify a value of waitForResponse, the program will wait
	for the amount of ms specified by waitForResponse and immediately
	process the AT response. If you don't specify a value or specify 0
	the program will call the general readXbee() and process the response
	there and write it to the corresponding variables.
	This function will then return 0.	**/
uint32_t LithneClass::sendATCommand( uint8_t * cmd, uint16_t waitForResponse )
{
	uint32_t	atAnswer	=	0;
	
	/*	Create a new AtComand Request and Response	*/
	AtCommandRequest atRequest   	= AtCommandRequest();

	/*	Set the specific command you want to send to the XBee in the atRequest	*/
	atRequest.setCommand( cmd );
	
	/*	Send this request to the xbee	*/
	xbee.send( atRequest );
  
	/*	The processing of the AT response is handled in the readXBee().
		We thus call this function. If we manually tell this function to
		wait for a response, it will skip this and attempt to read the
		information at this point. */
	if( waitForResponse == 0 )
	{
		readXbee();
	}
	else
	{
		if ( xbee.readPacket(waitForResponse) )
		{
			AtCommandResponse atResponse 	= AtCommandResponse();
			/*	If the packet is indeed an AT_COMMAND_RESPONSE,	we write it to the atResponse.	*/
			if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) 
			{
				xbee.getResponse().getAtCommandResponse(atResponse);
				/*	If the atResponse is correct (does not return an error code), we can process it.	*/
				if (atResponse.isOk()) 
				{
					if (atResponse.getValueLength() > 0) 
					{  
						for (int i = 0; i < atResponse.getValueLength(); i++) 
						{
							atAnswer	=	(atAnswer << 8) + atResponse.getValue()[i];
						}
        			}
				}
			}
  		}
		else 
  		{
	    	// at command failed
	    	if (xbee.getResponse().isError()) 
		    {
	//      	Serial.print("Error reading packet.  Error code: ");  
	//  	    Serial.println(xbee.getResponse().getErrorCode());
		    } 
	    	else 
		    {
	//      	Serial.print("No response from radio");  
	    	}
	    }
	}
  return atAnswer;
}
예제 #3
0
파일: Printers.cpp 프로젝트: Introsys/fresh
void printErrorCb(AtCommandResponse& r, uintptr_t data) {
	Print *p = (Print*)data;
	if (!r.isOk()) {
		p->print(F("Error sending "));
		p->write(r.getCommand(), 2);
		p->print(F(" command. Status: "));
		p->println(r.getStatus());
	}
}
예제 #4
0
bool XBeeMACLayer::getResponseMAC(){
          if (atResponse.getValueLength() == 4) {            
            for (int i = 0; i < atResponse.getValueLength(); i++) {
              my_mac.addr[mac_position++] = atResponse.getValue()[i];
            }
            return true;
          }
          return false;
}
예제 #5
0
bool XBeeMACLayer::getResponseCCAFailure(){
          if (atResponse.getValueLength() == 2) {            
            for (int i = 0; i < atResponse.getValueLength(); i++) {
              ((char*)(&cca_retries))[1] = atResponse.getValue()[0];
              ((char*)(&cca_retries))[0] = atResponse.getValue()[1];
            }
            return true;
          }
          return false;
}
예제 #6
0
bool XBeeUtil::readAtResponseInt(XBee* xbee, AtCommandResponse& response, int32_t &value) {
	if (response.getValueLength() == 4) {
		int_packer val;
		for (int i = 0, j = 3; i < 4; i++, j--) {
			val.data[j] = response.getValue()[i];
		}
		value = val.value;
		return true;
	}
	return false;
}
예제 #7
0
bool XBeeUtil::associate(XBee* xbee)
{
	uint8_t AI_cmd[] = { 'A', 'I' };
	AtCommandRequest atRequest = AtCommandRequest();
	AtCommandResponse atResponse = AtCommandResponse();
	atRequest.setCommand(AI_cmd);
	if (XBeeUtil::atCommand(xbee, atRequest, atResponse) && atResponse.getValueLength() == 1) {
		return true;
	} else {
		return false;;
	}
}
예제 #8
0
// Wait for the response to the reset command, ignore everything else
uint8_t EndDevice::resetWait() {
	DEBUG_MSG("[RESET WAIT]");
	if (  xbee.getResponse().isAvailable()
	   && xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE ) {
		AtCommandResponse atcr;
		xbee.getResponse().getAtCommandResponse(atcr);
		if (atcr.getCommand()[0] == 'N' && atcr.getCommand()[1] == 'R') {
			State = EndDeviceStart;
		}
	}
	return TICK_OK;
}
예제 #9
0
파일: Printers.cpp 프로젝트: Introsys/fresh
void printResponseCb(AtCommandResponse& at, uintptr_t data) {
	Print *p = (Print*)data;
	p->println("AtCommandResponse received:");
	p->print(F("  Command: "));
	p->write(at.getCommand(), 2);
	p->println();
	printField(p, F("  Status: 0x"), at.getStatus());
	if (at.getValueLength()) {
		p->print(F("  Value: "));
		printHex(*p, at.getValue(), at.getValueLength(), F(" "), NULL);
		p->println();
	}
}
예제 #10
0
bool XBeeUtil::atCommand(XBee* xbee, AtCommandRequest& request,	AtCommandResponse& response) {
	xbee->send(request);

// wait up to 5 seconds for the status response
	if (xbee->readPacket(5000)) {
		// got a response!

		// should be an AT command response
		if (xbee->getResponse().getApiId() == AT_COMMAND_RESPONSE) {
			xbee->getResponse().getAtCommandResponse(response);

			if (response.isOk()) {
//				XBeeUtil::debug_stream->print("Command [");
//				XBeeUtil::debug_stream->print(response.getCommand()[0]);
//				XBeeUtil::debug_stream->print(response.getCommand()[1]);
//				XBeeUtil::debug_stream->println("] was successful!");

				if (response.getValueLength() > 0) {
//					XBeeUtil::debug_stream->print("Command value length is ");
//					XBeeUtil::debug_stream->println(response.getValueLength(), DEC);

//					XBeeUtil::debug_stream->print("Command value: ");

					for (int i = 0; i < response.getValueLength(); i++) {
//						XBeeUtil::debug_stream->print(response.getValue()[i], HEX);
//						XBeeUtil::debug_stream->print(" ");
					}

//					XBeeUtil::debug_stream->println("");
				}
				return true;
			} else {
//				XBeeUtil::debug_stream->print("Command return error code: ");
//				XBeeUtil::debug_stream->println(response.getStatus(), HEX);
			}
		} else {
//			XBeeUtil::debug_stream->print("Expected AT response but got ");
//			XBeeUtil::debug_stream->print(xbee->getResponse().getApiId(), HEX);
		}
	} else {
		// at command failed
		if (xbee->getResponse().isError()) {
//			XBeeUtil::debug_stream->print("Error reading packet.  Error code: ");
//			XBeeUtil::debug_stream->println(xbee->getResponse().getErrorCode());
		} else {
//			XBeeUtil::debug_stream->print("No response from radio");
		}
	}
	return false;
}
예제 #11
0
bool XBeeMACLayer::sendAtCommand() {
  for(int i=0; i<AT_REQUEST_MAX_ATTEMPTS; ++i){
    // send the command
    xbee.send(atRequest);
  
    //TEMPORARILY, we send the request and wait for the attempt several times until we got it. This is because we can receive other packets that will be placed in the same buffer and they must be ignored until getting our AT response
    for(int i=0; i<AT_RESPONSE_MAX_ATTEMPTS; ++i){
      
      // wait up to 3 seconds for the status response
      if (xbee.readPacket(1000)) {
        // got a response!
    
        // should be an AT command response
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResponse);
    
          if (atResponse.isOk()) {
            if (atRequest.getCommand() == shCmd || atRequest.getCommand() == slCmd){
              return getResponseMAC();
            }else{
              if (atRequest.getCommand() == ecCmd){
                 return getResponseCCAFailure();
              }
            }
          } 
        } 
      } 
    }
  }
  return false;
}
예제 #12
0
    boolean checkNDResponse() { 
      //mySerial.println("checkNDResponse");
      // wait a small bit so the animation looks good
      if (xbee.readPacket(ND_WAIT_TIME / 6)) {
        // got a response!

        // should be an AT command response
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResponse);

          if (atResponse.isOk()) {
            if (atResponse.getCommand()[0] == atCmd[0] && atResponse.getCommand()[1] == atCmd[1] && atResponse.getValueLength() > 3) {

              //mySerial.println(pack(atResponse.getValue()[2],atResponse.getValue()[3],atResponse.getValue()[4],atResponse.getValue()[5]));          
              //mySerial.println(pack(atResponse.getValue()[6],atResponse.getValue()[7],atResponse.getValue()[8],atResponse.getValue()[9]));
              
              addr64 = XBeeAddress64( pack(atResponse.getValue()[2],atResponse.getValue()[3],atResponse.getValue()[4],atResponse.getValue()[5]),pack(atResponse.getValue()[6],atResponse.getValue()[7],atResponse.getValue()[8],atResponse.getValue()[9]) );
              
              
              return true;
            }
          } 
          else {
            //nss.print("Command return error code: ");
            //nss.println(atResponse.getStatus(), HEX);
            nr(1);
          }
        } else {
          //nss.print("Expected AT response but got ");
          //nss.print(xbee.getResponse().getApiId(), HEX);
          nr(2);
        }   
      } else {
        // at command failed
        if (xbee.getResponse().isError()) {
          //nss.print("Error reading packet.  Error code: ");  
          //nss.println(xbee.getResponse().getErrorCode());
          nr(3);
        } 
        else {
          //nss.print("No response from radio");  
          nr(4);
        }
      }
      return false;
    }
void ConnectOneAdapter::handleAtCommand(XBeeResponse &aResponse)
{
  LOCK(sSendLock);
  
  AtCommandResponse cmd;
  aResponse.getAtCommandResponse(cmd);
  if (cmd.isOk())
  {
    uint8_t *cp = cmd.getCommand();
    if (cp[0] == 'N' && cp[1] == 'P')
    {
      uint16_t v = ntohs(*((uint16_t*) cmd.getValue()));
      mXBee.setMaxSize(v);

      gLogger->debug("Maximum payload = %d", v);

      // Set the PAN ID
      {
        uint8_t command[] = { 'I', 'D' };
        uint8_t value[] = { 0x11, 0x11 };
        
        AtCommandRequest request(command, value, sizeof(value));
        mXBee.send(request);
      }
    }
    else if (cp[0] == 'I' && cp[1] == 'D')
    {
      // Send a discovery request
      uint8_t command[] = { 'N', 'D' };
      uint8_t value[] = { 0 };
      
      AtCommandRequest request(command, value, 0);
      mXBee.send(request);
    }        
    else if (cp[0] == 'N' && cp[1] == 'D')
    {
      uint8_t *response = cmd.getValue();
      XBeeAddress64 addr(ntohl(*((uint32_t*) (response + 2))),
                         ntohl(*((uint32_t*) (response + 6))));
      
      getOrCreateDevice(addr);
    }
  }

  UNLOCK(sSendLock);
}
예제 #14
0
namespace FireNest {

    struct Channel {
      int button_pin;
      int led_pin;
      int state;
      int time;
    };



    Channel channels[] = { 
      {2,8,0,0}, 
      {3,9,0,0},
      {4,A3,0,0},
      {5,A0,0,0},
      {6,A1,0,0},
      {7,A2,0,0}
    };


    //prototypes
    void discover();
    boolean checkNDResponse();
    void flashAll(int ms);
    void clearLeds();
    void nr(uint8_t nr);
    uint32_t pack(uint32_t c1, uint32_t c2, uint32_t c3, uint32_t c4);

    //NewSoftSerial mySerial(12, 13);

    //used when using first button to fire all channels
    uint8_t channel_count = 0;
    uint8_t fired_channels = 0;

    XBee xbee = XBee();

    uint8_t payload[] = { 0 };

    // SH + SL Address of receiving XBee
    uint32_t sh = 0;
    uint32_t sl = 0;

    //XBeeAddress64 addr64; //XBeeAddress64(0x0013a200, 0x403141DA);
    XBeeAddress64 addr64; //XBeeAddress64(0x0013a200, 0x403141DA);
    ZBTxRequest zbTx;
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();

    //for device discovery
    uint8_t atCmd[] = {'N','D'};
    AtCommandRequest atRequest = AtCommandRequest(atCmd);
    AtCommandResponse atResponse = AtCommandResponse();


    void setupold() {
      
      //mySerial.begin(4800);
      //mySerial.println("Hello world");
      
      for (int i= 0; i<CHANNELS; i++) {
        pinMode(channels[i].button_pin,INPUT);
        digitalWrite(channels[i].button_pin,HIGH); //enable internal 20K pullup
        
        pinMode(channels[i].led_pin,OUTPUT);
        //blink leds a bit
        digitalWrite(channels[i].led_pin,HIGH);
        delay(200);
        digitalWrite(channels[i].led_pin,LOW);
      }
      
      //debug led
      //pinMode(13,OUTPUT);
      //digitalWrite(13,HIGH);
      //delay(500);
      //digitalWrite(13,LOW);
      
      xbee.begin(XBEE_BAUD);

      //discover the other XBEE's address
      discover();
      zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
      
      //send a no-op packet so that the xbees can do their magic and find each other
      payload[0] = 254;
      xbee.send(zbTx);
      
      //Flash all leds once so the user knows
      flashAll(500);

      //mySerial.println("Discovered address");
      //mySerial.print("MSB: ");
      //mySerial.println(addr64.getMsb());
      //mySerial.println(addr64.getMsb()==0x0013a200?"Yes!":"NO");
      //mySerial.print("LSB: ");
      //mySerial.println(addr64.getLsb());
      //mySerial.println(addr64.getLsb()==0x403141DA?"Yes!":"NO");
    }



    //State 0 == not pressed, waiting for press

    //State 1 == pressed, debouncing time not up
    //Fire on press

    //State 2 == pressed, waiting for release 

    //State 3 == release, debouncing time not up

    void loopold() {
      int val;
      int m;
      
      for (uint8_t i= 0; i<CHANNELS; i++) {
        m = millis();
        
        if (channels[i].state == 0 || channels[i].state == 2) {
          val = digitalRead(channels[i].button_pin);
          
          if (channels[i].state == 0 && val == LOW) {
              //a press!, fire!
              uint8_t cc = i;
              
              //special case, we can fire all channels by firing the first button repeatably
              if (i == 0) {
                cc = channel_count;
                channel_count = (channel_count + 1) % CHANNELS;
              } 
              
              //fire!
              payload[0] = cc;
              xbee.send(zbTx);
              
              //set as fired 
              fired_channels |= (1 << cc);  
              digitalWrite(channels[cc].led_pin,HIGH);  
              
              //check if all is fired
              if (fired_channels == B00111111) {
                //wait a bit
                delay(500);
                
                //reset all
                channel_count = 0;
                fired_channels = 0;
                for (int j = 0; j<CHANNELS; j++) {
                  channels[j].state = 0;
                  digitalWrite(channels[j].led_pin,LOW);
                  delay(300);
                }
                break;
              }
          }
          
          if ((channels[i].state == 0 && val == LOW) || (channels[i].state == 2 && val == HIGH)) {
            channels[i].state = (channels[i].state + 1) % 4; //change state 
            channels[i].time = m;
          }
                
        } else if (m - channels[i].time >  THRESHHOLD) {
          channels[i].state = (channels[i].state + 1) % 4; //change state   
        }
      } 
    }


    //discover target node
    void discover() {
      //mySerial.println("discover");
      //if we don't get a address we can't fire
      while (true) {
        //send node discovery
        xbee.send(atRequest);
        
        //default value is that responding XBEE can wait up to six seconds before answering
        //so spamming it with node discoverys might be a bad thing, but waiting so long is booring so
        //we we'll try it and see if it works...
        
        //knight rider on the diodes let's the users know we're looking
        for (int i=0; i<CHANNELS; i++) {
          clearLeds();
          digitalWrite(channels[i % CHANNELS].led_pin,HIGH);

          if (checkNDResponse()) {
            return;
          }      
        }

        for (int i=CHANNELS-1; i>=0; i--) {
          clearLeds();
          digitalWrite(channels[i % CHANNELS].led_pin,HIGH);

          if (checkNDResponse()) {
            return;
          }      
        }
      }
    }

    boolean checkNDResponse() { 
      //mySerial.println("checkNDResponse");
      // wait a small bit so the animation looks good
      if (xbee.readPacket(ND_WAIT_TIME / 6)) {
        // got a response!

        // should be an AT command response
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResponse);

          if (atResponse.isOk()) {
            if (atResponse.getCommand()[0] == atCmd[0] && atResponse.getCommand()[1] == atCmd[1] && atResponse.getValueLength() > 3) {

              //mySerial.println(pack(atResponse.getValue()[2],atResponse.getValue()[3],atResponse.getValue()[4],atResponse.getValue()[5]));          
              //mySerial.println(pack(atResponse.getValue()[6],atResponse.getValue()[7],atResponse.getValue()[8],atResponse.getValue()[9]));
              
              addr64 = XBeeAddress64( pack(atResponse.getValue()[2],atResponse.getValue()[3],atResponse.getValue()[4],atResponse.getValue()[5]),pack(atResponse.getValue()[6],atResponse.getValue()[7],atResponse.getValue()[8],atResponse.getValue()[9]) );
              
              
              return true;
            }
          } 
          else {
            //nss.print("Command return error code: ");
            //nss.println(atResponse.getStatus(), HEX);
            nr(1);
          }
        } else {
          //nss.print("Expected AT response but got ");
          //nss.print(xbee.getResponse().getApiId(), HEX);
          nr(2);
        }   
      } else {
        // at command failed
        if (xbee.getResponse().isError()) {
          //nss.print("Error reading packet.  Error code: ");  
          //nss.println(xbee.getResponse().getErrorCode());
          nr(3);
        } 
        else {
          //nss.print("No response from radio");  
          nr(4);
        }
      }
      return false;
    }

    //flash leds once, variable time
    void flashAll(int ms) {
      for (int i=0;i<CHANNELS; i++) {
        digitalWrite(channels[i].led_pin,HIGH);
      }
      
      delay(ms);
      clearLeds();  
    }

    //clear all leds
    void clearLeds() {
      for (int i=0;i<CHANNELS; i++) {
        digitalWrite(channels[i].led_pin,LOW);
      }
    }

    //light up a nr, binary code
    void nr(uint8_t nr) {
      //TODO: smarter code...
      if (nr & B00000001) {
        digitalWrite(8,HIGH);
      }
      if (nr & B00000010) {
        digitalWrite(9,HIGH);
      }
      if (nr & B00000100) {
        digitalWrite(A3,HIGH);
      }
      if (nr & B00001000) {
        digitalWrite(A0,HIGH);
      }
      if (nr & B00010000) {
        digitalWrite(A1,HIGH);
      }
      if (nr & B00100000) {
        digitalWrite(A2,HIGH);
      }
    }
     
    uint32_t pack(uint32_t c1, uint32_t c2, uint32_t c3, uint32_t c4) {
        return (c1 << 24) | (c2 << 16) | (c3 << 8) | (c4);
    }
}
예제 #15
0
void XBeeActive::sendAtCommand_ar()
{
	int i10;

	Serial.println("\nSending command sendAtCommand_ar to the XBee");
	xbee.send(arRequestMod);      // send the command

								  // wait up to 5 seconds for the status response
	if (xbee.readPacket(5000))
	{

		// should be an AT command response
		if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE)
		{
			xbee.getResponse().getAtCommandResponse(atResponse);

			if (atResponse.isOk())
			{

				//myGLCD.setColor(255 , 0, 0);

				//	Serial.print("Command [");
				//	Serial.print(atResponse.getCommand()[0]);
				//	Serial.print(atResponse.getCommand()[1]);
				//	Serial.println("] was successful!");

				if (atResponse.getValueLength() > 0)
				{
					Len_XBee = atResponse.getValueLength();
					//  Serial.print("Command value length is ");
					//  Serial.println(atResponse.getValueLength(), DEC);
					//  Serial.print("Command value: ");
					int i11 = Len_XBee - 1;
					info_XBee_data1[0] = 0;
					info_XBee_data1[1] = 0;
					info_XBee_data1[2] = 0;
					info_XBee_data1[3] = 0;

					for (i10 = 0; i10 < atResponse.getValueLength(); i10++)
					{
						info_XBee_data[i10] = atResponse.getValue()[i10];
						Serial.print(info_XBee_data[i10], HEX);
						info_XBee_data1[i11] = info_XBee_data[i10];
						i11--;
					}

					// Serial.println("");
				}
			}
			else
			{
				Serial.print("Command return error code: ");
				Serial.println(atResponse.getStatus(), HEX);

				//myGLCD.setColor(255, 0, 0);
				//myGLCD.fillRoundRect(278, 92, 318, 132);
				//myGLCD.setColor(255, 255, 255);
				//myGLCD.drawRoundRect(278, 92, 318, 132);
				//myGLCD.setBackColor(0, 0, 0);
				//delay(200);
				////XBee_alarm();
				//delay(1000);
				//myGLCD.setColor(0, 0, 0);
				//myGLCD.fillRoundRect(278, 92, 318, 132);
				//myGLCD.setColor(0, 0, 0);
				//myGLCD.drawRoundRect(278, 92, 318, 132);
				//	mcp_Out1.digitalWrite(Beep, LOW);                    // 
				delay(300);
			}
		}
		else
		{
			Serial.print("Expected AT response but got ");
			Serial.println(xbee.getResponse().getApiId(), HEX);
		}
	}
	else
	{
		// at command failed
		if (xbee.getResponse().isError())
		{
			Serial.print("Error reading packet.  Error code: ");
			Serial.println(xbee.getResponse().getErrorCode());
		}
		else
		{
			Serial.println("No response from radio2");
		}
	}
}
예제 #16
0
void XBeeActive::sendAtCommand()
{
	int i10;
	xbee.send(atRequest);
	if (xbee.readPacket(5000)) // подождите до 5 секунд для ответа состояния
	{
		if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) // Должна быть команда отклика AT
		{
			xbee.getResponse().getAtCommandResponse(atResponse);

			if (atResponse.isOk())
			{
				//DEBAG.print("Command [");
				//DEBAG.print(atResponse.getCommand()[0]);
				//DEBAG.print(atResponse.getCommand()[1]);
				//DEBAG.println("] was successful!");

				if (atResponse.getValueLength() > 0)
				{
					Len_XBee = atResponse.getValueLength();
					//DEBAG.print("\nCommand value length is - ");
					//DEBAG.println(atResponse.getValueLength(), DEC);
					//DEBAG.print("Command value: ");
					int i11 = Len_XBee - 1;
					info_XBee_data1[0] = 0;
					info_XBee_data1[1] = 0;
					info_XBee_data1[2] = 0;
					info_XBee_data1[3] = 0;

					for (i10 = 0; i10 < atResponse.getValueLength(); i10++)
					{
						info_XBee_data[i10] = atResponse.getValue()[i10];
						//DEBAG.print(info_XBee_data[i10], HEX);
						//DEBAG.print(" ");
						info_XBee_data1[i11] = info_XBee_data[i10];
						i11--;
					}
					//DEBAG.println("");
				}
			}
			else
			{
				//DEBAG.print("Command return error code: ");
				//DEBAG.println(atResponse.getStatus(), HEX);
			}
		}
		else
		{
			//DEBAG.print("Expected AT response but got ");
			//DEBAG.println(xbee.getResponse().getApiId(), HEX);
		}
	}
	else
	{
		if (xbee.getResponse().isError())             // at command failed
		{
			//DEBAG.print("Error reading packet.  Error code: ");
			//DEBAG.println(xbee.getResponse().getErrorCode());
		}
		else
		{
			//DEBAG.println("No response from radio1");
		}
	}
	delay(200);
}
/** This function takes care of all processing when a message is received.
	It is called after Lithne.available();
	This section is based on examples in the XBee library by Andrew Rapp**/
void LithneClass::readXbee()
{
/*DONT EDIT IF YOU DON'T KNOW WHAT YOU'RE DOING!!!	*/

/* Reads all available serial bytes until a packet is parsed, an error occurs, or the buffer is empty. */
xbee.readPacket();  

if( newXBeePacket ) { newXBeePacket = false; } // Set this flag to false; only raise it if we receive a message

if (xbee.getResponse().isAvailable()) //Returns a reference to the current response Note: once readPacket is called again this response will be overwritten!
{
	newXBeePacket = true;

	int responseType	=	xbee.getResponse().getApiId();

  	if (responseType == ZB_RX_RESPONSE)
    { //Call with instance of ZBRxResponse class only if getApiId() == ZB_RX_RESPONSE to populate response.

     	/* Indicate we have received a new message */
     	newMessage = true; // set flag
     	
     	/* Clear the old received message */
		incomingMessage.clearArguments();
     	
     	xbee.getResponse().getZBRxResponse(rx);
     	
     	/* Retrieve the sender from the packet and store it in the message */
     	XBeeAddress64	addr64	=	rx.getRemoteAddress64();
     	uint16_t		addr16	=	rx.getRemoteAddress16();

		/*  if the 16 bit add shows this is the coordinator, we store the default
			coordinator address 0x0 0x0 instead of the hardware address       */
		if (addr16 == 0) 
		{
			addr64 = XBeeAddress64(0x0, 0x0);
		}
     	

		// Serial.println("-----------");
		
  //   	for( uint16_t i = 0; i <rx.getDataLength(); i++ )
  //     	{
    		
		// 	Serial.print( rx.getData(i) );
		// 	Serial.print( " " );
  //   	}
  //   	Serial.println("");
  //   	Serial.println("-----------");

	incomingMessage.setSender( addr16, addr64 );
     	 
     	/*	The scope of the message is stored in the first two bytes
     		of the payload.	Here we retrieve this and write it to the
     		incoming message	*/
	incomingMessage.setScope( (rx.getData(Message::SCOPE_MSB) << 8) + rx.getData(Message::SCOPE_LSB) );
     	
		/* 	The function identifier (1 byte) is stored in the third
			byte of the payload. Here we retrieve this and write it to
			the incoming message	*/
	incomingMessage.setFunction((rx.getData(Message::FUNCTION_MSB) << 8) + rx.getData(Message::FUNCTION_LSB) );

      	/*	The remainder of the payload contains our arguments. Here
      		we retrieve the number of arguments, by subtracting the 
      		first three bytes (which contain the scope and the function
      		ID) and dividing the number of bytes by two, since we send
      		16-bit values and not 8-bit values (2x 8-bits = 1x 16bits)	*/
      	uint16_t numOfBytes	=	(rx.getDataLength()-Message::MSG_HEADER_SIZE);
		
		/* Store the arguments in the incomingMessage */
    	for( uint16_t i = 0; i < numOfBytes; i++ )
      	{
    		uint16_t pos    =	i + Message::MSG_HEADER_SIZE;
		incomingMessage.addByte( rx.getData(pos) );
    	}
    	
    	/*	Here we always overwrite the 16-bit address. The received address 
    		is directly taken from the header information and thus correct.	*/
    	
		Node * senderNode = getNodeBy64( addr64 );
		if (senderNode != NULL) 
		{	
			senderNode->setAddress16( addr16 );
		}
		// delete senderNode;
    	
    	/* If the sender(!) of the message got an acknowledgement, this code is executed */
    	if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED)
		{
			
		}
		/*	If not, something strange has happened, because we got the message, but
			the sender did not receive an acknowledgement */
      	else
      	{
        	//we got it (obviously) but sender didn't get an ACK
      	}
    }
    
    /*	If the packet is indeed an AT_COMMAND_RESPONSE,	we write it to the atResponse.	*/
	else if (responseType == AT_COMMAND_RESPONSE) 
	{
		AtCommandResponse atResponse 	=	AtCommandResponse();
		uint32_t atAnswer				=	0;
		
		xbee.getResponse().getAtCommandResponse( atResponse );

		/*	If the atResponse is correct (does not return an error code), we can process it.	*/
		if (atResponse.isOk()) 
		{
			newATMessage = true;
			if (atResponse.getValueLength() > 0) 
			{
				for (int i = 0; i < atResponse.getValueLength(); i++) 
				{
					atAnswer	=	(atAnswer << 8) + atResponse.getValue()[i];
				}
       		}
       		
       		/*	If we got a Serial High	('S','H')	*/
       		if( atResponse.getCommand()[0] == atSH[0] &&
       			atResponse.getCommand()[1] == atSH[1] )
       		{
       			myAddress64.setMsb( atAnswer );
       		}
       		/*	If we got a Serial LOW ('S','L')	*/
       		if( atResponse.getCommand()[0] == atSL[0] &&
       			atResponse.getCommand()[1] == atSL[1] )
       		{
       			myAddress64.setLsb( atAnswer );
       		}
       		/*	If we got my 16-bit address ('M','Y')	*/
       		if( atResponse.getCommand()[0] == atMY[0] &&
       			atResponse.getCommand()[1] == atMY[1] )
       		{
       			myAddress16	=	atAnswer & 0xFFFF;
       		}
       		/*	If we got my 16-bit address ('M','Y')	*/
       		if( atResponse.getCommand()[0] == atID[0] &&
       			atResponse.getCommand()[1] == atID[1] )
       		{
       			myPANid		=	atAnswer & 0xFFFF;
       		}
       		/*	If we got my 16-bit address ('M','Y')	*/
       		if( atResponse.getCommand()[0] == atAI[0] &&
       			atResponse.getCommand()[1] == atAI[1] )
       		{
       			myAssStat	=	atAnswer & 0xFFFF;
       		}
		}
		else {	} 
	}
    
    /* NODE JOINING/LEAVING THE NETWORK */
	else if( responseType == MODEM_STATUS_RESPONSE )
	{
    	xbee.getResponse().getModemStatusResponse(msr);

       	if (msr.getStatus() == ASSOCIATED) 
       	{
        	/* A new node has joined the network.
        		Here we add the node if it is not yet known and store the 
        		64-bit and 16-bit address
        	*/
//        	xbee.getResponse().;
       	} 
	  	else if (msr.getStatus() == DISASSOCIATED) 
	  	{
         	/* Node leaves the network
         	*/
       	} 
	}
	/* DB MEASUREMENT RESPONSE */
	else if( responseType == REMOTE_AT_COMMAND_RESPONSE ) 	//REMOTE_AT_COMMAND_RESPONSE
	{	
		// Serial.println("Received Remote AT Command Response");
		xbee.getResponse().getRemoteAtCommandResponse(rATcmd);
		if (rATcmd.isOk()) 
		{
	      	if ( rATcmd.getCommand()[0]	==	atDB[0] &&
	      		 rATcmd.getCommand()[1]	==	atDB[1] )
	      	{
				newRemoteATMessage = true;
		      	XBeeAddress64 rAddress64	=	rATcmd.getRemoteAddress64();
		      	uint16_t rAddress16			=	rATcmd.getRemoteAddress16();

				// Serial.print("AT DB from ");
				// Serial.print(rAddress64.getMsb(), HEX);
				// Serial.println(rAddress64.getLsb(), HEX);
				
				// This is now done at the end of this section
				//getNodeBy64( rAddress64 )->addDBMeasurement( rATcmd.getValue()[0] );
				
				/*	The line above replaces this section
				for (int i = 0; i < numNodes; i++)
				{
					if( nodes[i]->getID() == remoteId )
					{
		    			nodes[i]->addDBMeasurement( rATcmd.getValue()[0] );
			    	}
		      	}
		      	*/
		      	/* we use this function also to relate 16 bit addresses to 64 bit addresses */
		      	if( !nodeKnown16( rAddress16 ) && nodeKnown64( rAddress64 ) )
		      	{
		      		getNodeBy64( rAddress64 )->setAddress16( rAddress16 );
		      		// Serial.println("We know the 64-bit address, but not the 16-bit - now setting");
		      	}
				/* If we receive a message from the coordinator; it has 16-bit add 0. We related this to the node with 64 bit address 0x0 0x0; the coordinator. */
				else if ( rAddress16 == 0 && !nodeKnown16( rAddress16 ) )
				{ 			
					Node * defaultCoordinator = getNodeBy64( XBeeAddress64(0x0,0x0) );
					if (defaultCoordinator != NULL) 
					{
						defaultCoordinator->setAddress16( rAddress16 );
					}
					/*Serial.print("Set 16 bit add of coordinator to ");
					Serial.print( getNodeBy64( XBeeAddress64(0x0,0x0) )->getAddress16(  ) ); 
					Serial.print(" which is Node ID ");
					Serial.print( getNodeBy64( XBeeAddress64(0x0,0x0) )->getID(  ) );  */
				}
				
				/*Serial.print("Received Remote DB from nodeId ");
				Serial.print( getNodeBy16( rAddress16 )->getID() );
				Serial.print(" (64b: ");
				Serial.print( rAddress64.getLsb(), HEX );
				Serial.print(", 16b: ");
				Serial.print( rAddress16, DEC ); 
				
				Serial.print( ") DB val: ");
				Serial.println( rATcmd.getValue()[0] ); */
				
				Node * remoteNode = getNodeBy16( rAddress16 );
				if ( remoteNode != NULL) 
				{
					remoteNode->addDBMeasurement( rATcmd.getValue()[0] );
				}
		    }
		    /*	Here we can add other remote AT command responses
		    else if( rATcmd.getCommand()[0]	==	atSH[0] &&
	      		 	 rATcmd.getCommand()[1]	==	atSH[1] )
			{
			
			}
			*/
		}
    }
    /*	Confirmation on transmitted package. This is received
    	everytime a message is transmitted and has details
    	whether the package is received or not.
	*/
    else if (responseType == ZB_TX_STATUS_RESPONSE)
    {
    	// Serial.println("Received ZBTxStatusResponse");

	    xbee.getResponse().getZBTxStatusResponse(txStatus);
     	
     	if (txStatus.getDeliveryStatus() == SUCCESS) 
	 	{
			/* Als we hier zijn aangekomen, hebben we een berichtje gestuurd,
	 		dat is goed aangekomen. Deze response geeft echter alleen een
	 		16-bit address terug en geen 64-bit, dus die kunnen we niet aan
	 		een node koppelen.
	 		Nu willen we kijken of de 16-bit bekend is in onze node lijst.
	 		Als dat zo is, dan hoeven we niets te doen, we kennen deze node.
	 		Als dat NIET zo is, dan willen we van deze node ook het 64-bit
	 		address opvragen, zodat we 16-bit en 64-bit op kunnen slaan.
	 		*/
			
	 		uint16_t rAddress16	=	txStatus.getRemoteAddress();	//Stores the 16-bit address

	 		setMessageDelivered( true );
	 		
	 		if( !nodeKnown16( rAddress16 ) )
	 		{
	 			/*Here we send something that requests data from the remote node
				We can link the two addresses in the returned data (remote at command response)*/
	 			sendDBRequest16( rAddress16 );
	 		}
		}      	
      	else 
	  	{
        	/* the remote XBee did not receive our packet. 
        		If this is because the 16 bit address is outdated; we wish to reset that */
       		uint16_t rAddress16	=	txStatus.getRemoteAddress();	//Get the 16-bit address
			if( nodeKnown16( rAddress16 ) ) // If we know that address, but the message was not received
			{
				Node * remoteNode = getNodeBy16( rAddress16 );
				if ( remoteNode != NULL) 
				{
					remoteNode->setAddress16( UNKNOWN_16B ); // We reset the 16 bit address so it will use the 64 bit again
				}
			}
     	}
    }
    //Something occured that is unknown, or we do not care about
    else
    {
    }
  }
}
예제 #18
0
void XBeeActive::search_XBee()
{
	d0Value[0] = 0xFE;
	commandValueLength = 0x1;
	atRequest.setCommand(NTCmd);
	sendAtCommand();
	delay(250);
	arRequestMod.clearCommandValue();
	delay(100);
	atRequest.setCommand(NDCmd);
	int search_list = 0;
	int i10;
	Serial.println("\nSending command search XBee");
	xbee.send(atRequest);
	while (true)
	{
		if (xbee.readPacket(5000)) // подождите до 5 секунд для ответа состояния
		{
			if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) // Должна быть команда отклика AT
			{
				xbee.getResponse().getAtCommandResponse(atResponse);

				if (atResponse.isOk())
				{
					Serial.print("Command [");
					Serial.print(atResponse.getCommand()[0]);
					Serial.print(atResponse.getCommand()[1]);
					Serial.println("] was successful!");

					if (atResponse.getValueLength() > 0)
					{
						Len_XBee = atResponse.getValueLength();
						Serial.print("Command value length is - ");
						Serial.println(atResponse.getValueLength(), DEC);
						Serial.print("Command value: ");

						for (i10 = 0; i10 < atResponse.getValueLength(); i10++)
						{
							info_XBee_data[i10] = atResponse.getValue()[i10];
							Serial.print(info_XBee_data[i10], HEX);
							Serial.print(" ");
						}
						Serial.println("");
						search_list++;
					}
				}
				else
				{
					Serial.print("Command return error code: ");
					Serial.println(atResponse.getStatus(), HEX);
				}
			}
			else
			{
				Serial.print("Expected AT response but got ");
				Serial.println(xbee.getResponse().getApiId(), HEX);
			}
		}
		else
		{
			if (xbee.getResponse().isError())             // at command failed
			{
				Serial.print("Error reading packet.  Error code: ");
				Serial.println(xbee.getResponse().getErrorCode());
			}
			else
			{
				Serial.println("\nNo response from radio1");
				return;
			}
		}

	}
}