public void SendPacket(PacketEventArgs packet) { int packetLen = 0; int checkLen = 0; byte[] data; if (xmodemInfo.CheckMode == XModemCheckMode.CheckSum) { checkLen = 1; } else { checkLen = 2; } if (xmodemInfo.Type == XModemType.XModem_1K) { packetLen = 1024; } else { packetLen = 128; } data = new byte[3 + packetLen + checkLen]; data[0] = SOH; if (xmodemInfo.Type == XModemType.XModem_1K) { data[0] = STX; } data[1] = Convert.ToByte(packet.PacketNo & 0xFF); data[2] = Convert.ToByte((~data[1]) & 0xFF); Array.Copy(packet.Packet, 0, data, 3, packetLen); if (xmodemInfo.CheckMode == XModemCheckMode.CheckSum) { data[3 + packetLen] = Convert.ToByte(DataCheck.GetCheckSum(packet.Packet) & 0xFF); } else { UInt16 crc = Convert.ToUInt16(DataCheck.GetCRC(CRCType.CRC16_XMODEM, packet.Packet) & 0xFFFF); data[3 + packetLen] = Convert.ToByte(crc >> 8); data[3 + packetLen + 1] = Convert.ToByte(crc & 0xFF); } SendFrameToUart(data); }
/// <summary> /// 解析数据 /// </summary> /// <param name="data"></param> private void ParseReceivedMessage(byte[] data) { YmodemMessage ReceivedMessage = null; if (data == null) { ReceivedMessage = null; } else { if (data[0] == STX || data[0] == SOH) { ReceivedMessage = new YmodemMessage(YmodemMessageType.PACKET_ERROR); int packetLen = 0; if (data[0] == STX) { packetLen = 1024; } else if (data[0] == SOH) { packetLen = 128; } int checkDataLen = 2; if (packetLen + 3 + checkDataLen == data.Length) { int packetNo = 0; if (data[1] == Convert.ToByte((~data[2]) & 0xFF)) { packetNo = data[1]; } int frameCheckCode = 0; int calCheckCode = -1; byte[] packet = new byte[packetLen]; Array.Copy(data, 3, packet, 0, packetLen); frameCheckCode = (data[3 + packetLen] << 8) + data[3 + packetLen + 1]; calCheckCode = Convert.ToUInt16(DataCheck.GetCRC(CRCType.CRC16_XMODEM, packet) & 0xFFFF); if (frameCheckCode == calCheckCode) { ReceivedMessage = new YmodemMessage(YmodemMessageType.PACKET, new PacketEventArgs(packetNo, packet)); } } } else { foreach (byte b in data) { ReceivedMessage = null; if (b == EOT) { ReceivedMessage = new YmodemMessage(YmodemMessageType.EOT); } else if (b == CAN) { ReceivedMessage = new YmodemMessage(YmodemMessageType.CAN); } else if (b == NAK) { ReceivedMessage = new YmodemMessage(YmodemMessageType.NAK); } else if (b == ACK) { ReceivedMessage = new YmodemMessage(YmodemMessageType.ACK); } else if (b == KEY_C) { ReceivedMessage = new YmodemMessage(YmodemMessageType.KEY_C); } else { } if (ReceivedMessage != null) { msgQueue.Enqueue(ReceivedMessage); } } } } waitReceiveEvent.Set(); }