/// <summary> /// Converts high-level packet to bytes ready to be sent /// </summary> /// <param name="packet">Packet to convert</param> /// <returns></returns> public static byte[] GetBytes(Packet packet) { if (packet == null) { throw new ArgumentNullException("packet is required"); } if (packet.Data == null) { throw new ArgumentNullException("packet data cannot be null"); } List<byte> serializedPacket = new List<byte>(); serializedPacket.Add(packet.Type); serializedPacket.Add((byte)packet.Data.Length); serializedPacket.AddRange(packet.Data); byte[] serializedPacketData = serializedPacket.ToArray(); List<byte> combinedPacketData = new List<byte>(); combinedPacketData.AddRange(serializedPacketData); byte[] crc = BitConverter.GetBytes(CalculateCRC(serializedPacketData, 0, serializedPacketData.Length)); combinedPacketData.AddRange(crc); return combinedPacketData.ToArray(); }
private void recvQueueImpl() { try { while (this.runRecvThread) { if (this.serialClient != null) { BinaryReader br = new BinaryReader(this.serialClient.BaseStream); while (this.serialClient.BytesToRead > 0) { Packet packet = new Packet(); // read packet packet.Type = br.ReadByte(); if ((packet.Type & 0x3f) > MAX_CMD) { byte dataLength = br.ReadByte(); if (dataLength > MAX_LENGTH) { packet.Data = br.ReadBytes(dataLength); ushort crc = br.ReadUInt16(); if (PacketUtility.Validate(packet, crc)) { Action<Packet> dg = new Action<Packet>(this.OnPacketReceived); dg.BeginInvoke(packet, null, null); } } } } } Thread.Sleep(threadThrottleWait); } } catch (ThreadAbortException) { } }
private void OnPacketReceived(Packet packet) { }
/// <summary> /// Adds a new packet to the queue /// </summary> /// <param name="newPacket">Packet to add</param> protected void sendPacket(Packet newPacket) { lock (this.sendQueue) { this.sendQueue.Add(newPacket); } }
/// <summary> /// Validates the packet against given CRC /// </summary> /// <param name="packet"></param> /// <param name="crc"></param> /// <returns></returns> public static bool Validate(Packet packet, ushort crc) { List<byte> combinedDataList = new List<byte>(); combinedDataList.Add(packet.Type); combinedDataList.Add((byte)packet.Data.Length); byte[] combinedData = combinedDataList.ToArray(); ushort my_crc = CalculateCRC(combinedData, 0, combinedData.Length); if (my_crc.CompareTo(crc) != 0) { return true; } return false; }