//Handle any valid data retrieved here void xbeePacketHandler_ValidDataGet(object sender, WATR_ValidDataGetArgs e) { //Log information db.LogReceivePacket(e.Data.RawData); //Figure out what type of packet it is and raise the proper event if (e.Data.GetFrameType() is WATR_XBeeRemoteATCommandResponseFrameData) { WATR_RemoteATCmdResponseGetArgs remoteATcmdResp = new WATR_RemoteATCmdResponseGetArgs(e.Data.GetFrameType()); if (remoteATcmdResp != null) ReceivedRemoteATCommandResponse(this, remoteATcmdResp); } else if (e.Data.GetFrameType() is WATR_XBeeATCommandFrameData) { WATR_ATCmdResponseGetArgs atCmdResp = new WATR_ATCmdResponseGetArgs(e.Data.GetFrameType()); if (atCmdResp != null) ReceivedATCmdResponse(this, atCmdResp); } else if (e.Data.GetFrameType() is WATR_XBeeReceivePacketFrameData) { WATR_RxPacketGetArgs rxFrameData = new WATR_RxPacketGetArgs(e.Data.GetFrameType()); if (rxFrameData != null) ReceivedRxPacket(this, rxFrameData); } else { WATR_TransmitStatusGetArgs transmitStatusGet = new WATR_TransmitStatusGetArgs(e.Data.GetFrameType()); if (transmitStatusGet != null) ReceivedTransmitStatus(this, transmitStatusGet); } }
//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); } } }