public static byte[] makePacket(byte[] rawData, byte source, byte destination, bool addError = false) { int packetsAmount = rawData.Length / bytesPerPacket; if ((rawData.Length % bytesPerPacket) > 0) { packetsAmount++; } packets.Clear(); for (int packetNumber = 0; packetNumber < packetsAmount; packetNumber++) { CRC8.clearValue(); insertEndOfPacket(); insertByte(source); CRC8.updateChecksumm(source); insertByte(destination); CRC8.updateChecksumm(destination); int currentPosition = packetNumber * bytesPerPacket; for (int byteNumber = 0; byteNumber < bytesPerPacket; byteNumber++) { byte currentByte; if (currentPosition + byteNumber >= rawData.Length) { break; } else { currentByte = rawData[currentPosition + byteNumber]; } insertByte(currentByte); CRC8.updateChecksumm(currentByte); } if (addError) { if (packets[packets.Count - 1]) { packets[packets.Count - 1] = false; } else { packets[packets.Count - 1] = true; } } insertByte(CRC8.Value); insertEndOfPacket(); } return(bitListToByteArray()); }
public static byte[] extractFromPacket(byte[] packet) { int bitsDeleted = 0; bool bitDeleted = false; packets.Clear(); for (int byteNumber = 1; byteNumber < packet.Length - 1; byteNumber++) { for (int bitNumber = 7; bitNumber >= 0; bitNumber--) { packets.Add(((packet[byteNumber] >> bitNumber) & 1) == 1); if (!bitDeleted && checkForSequence(Operation.Extract)) { bitDeleted = true; bitsDeleted++; continue; } bitDeleted = false; } } int bitsToDelete = 8 - (bitsDeleted % 8); if (bitsToDelete != 8) { for (int i = 0; i < bitsToDelete; i++) { packets.RemoveAt(packets.Count - 1); } } byte expectedChecksumm = extractByte((packets.Count / 8) - 1); for (int i = 0; i < 8; i++) { packets.RemoveAt(packets.Count - 1); } byte[] extractedMessage = bitListToByteArray(); CRC8.clearValue(); CRC8.updateChecksumm(extractedMessage); byte checksumm = CRC8.Value; if (checksumm != expectedChecksumm) { return(null); } return(extractedMessage); }
private static void insertCheckSum(byte[] data, int currentPos) { CRC8.clearValue(); for (int i = 0; i < bytesPerPacket; i++) { if (currentPos + i >= data.Length) { break; } CRC8.updateChecksumm(data[currentPos + i]); } insertByte(CRC8.Value); }