public void Close() { if (usedPort != null) { usedPort.Close(); } //usedPort = null; }
/// <summary> /// Realiza el intercambio de comandos basandose en bytes /// </summary> /// /// <param name="cmdBin">The command to send to printer</param> /// <returns>The output object (same as <b>cmd.OutputObject</b>)</returns> public byte[] ExchangePacketBinLowLevel(byte[] cmdBin) { byte[] rcvBin = null; usedPort = ConstructPort(); usedPort.Open(); if (usedPort == null || !usedPort.IsOpen) { return(null); } cancelling = false; // Patch the sequence if (packetSequence <= 0x80 || packetSequence >= 0xff) { packetSequence = (byte)new Random().Next(0x81, 0xff); } cmdBin[0] = packetSequence++; if (packetSequence <= 0x80 || packetSequence >= 0xff) { packetSequence = 0x81; } // Ensure than nothing is in the wire while (usedPort.BytesToRead || usedPort.BytesToWrite) { lock (locker) { var sb = new StringBuilder(); while (usedPort.BytesToRead) { int ch = usedPort.ReadByte(); if (cancelling || ch == EOF) { break; } sb.Append((char)ch); } if (sb.Length > 0 && RxOutOfFrame != null) { RxOutOfFrame(sb.ToString()); } usedPort.DiscardInBuffer(); usedPort.DiscardOutBuffer(); inputQ.Clear(); } #if !_CONSOLE Application.DoEvents(); #endif Thread.Sleep(50); } // Send the command... TxPacket(cmdBin); // Wait an answser and match the packet id do { if (cancelling) { break; } rcvBin = RxPacket(); if (rcvBin == null && NAKReceived) { TxPacket(cmdBin); continue; } if (cancelling || rcvBin == null) { break; } } while (rcvBin == null || (rcvBin[0] != cmdBin[0])); // Flush (could exists an ACK in the wire) while (usedPort.BytesToRead || usedPort.BytesToWrite) { lock (locker) { var sb = new StringBuilder(); while (usedPort.BytesToRead) { int ch = usedPort.ReadByte(); sb.Append((char)ch); } if (sb.Length > 0 && RxOutOfFrame != null) { RxOutOfFrame(sb.ToString()); } } #if !_CONSOLE Application.DoEvents(); #endif } usedPort.Close(); if (cancelling && OnCancelled != null) { OnCancelled(); return(null); } return(rcvBin); }