//Event handler for the serial port data private void xbeePort_DataReceived(object sender, SerialDataReceivedEventArgs e) { //Check to see if the first byte received is 0x7e for a valid packet if (xbeePort.ReadByte() == 0x7E) { //Wait a tenth of a second for the rest of the data to be available System.Threading.Thread.Sleep(200); //Get the packet length as individual bytes int msbLength = xbeePort.ReadByte(); int lsbLength = xbeePort.ReadByte(); //Get the total length as combined bytes int totalLength = (msbLength << 8) | lsbLength; //Buffer for the incoming data byte[] incomingData = new byte[totalLength]; //Get the entire packet xbeePort.Read(incomingData, 0, totalLength); //The last byte we get should be the checksum int checksum = xbeePort.ReadByte(); //Check the entire packet for validity if (challengeChecksum(incomingData, checksum)) { //If it's valid, assemble the data into an rx (receive) frameData class WATR_XBeeRxFrameData data = new WATR_XBeeRxFrameData(incomingData); //Raise an event saying we've got valid data and pass the framedata to it WATR_ValidDataGetArgs validDataGet = new WATR_ValidDataGetArgs(data); if (validDataGet != null) ValidDataGet(this, validDataGet); } else { //If it's not valid, send an event saying it's not valid //Keep them as bytes; they may not assemble properly into frame data and may cause an error WATR_InvalidDataGetArgs invalidDataGet = new WATR_InvalidDataGetArgs(incomingData); if (invalidDataGet != null) InvalidDataGet(this, invalidDataGet); } } }
public WATR_ValidDataGetArgs(WATR_XBeeRxFrameData data) { this.Data = data; }