public bool WriteDatasEx(int address, byte[] bytes, int timeOut) { try { if (timeOut < 3000) { timeOut = 3000; } _dataRecv = null; if (null != _port && _port.IsOpen) { var command = PLCCommandFactory.GetWriteCommand(address, bytes); _port.Write(command); Console.WriteLine($"向PLC发送数据"); CommandFactory.PrintBytes(command); } else { throw new Exception("请先打开串口"); } var index = 1; while (index < timeOut) { Thread.Sleep(100); index += 100; if (null != _dataRecv && _dataRecv.Length > 0) { var newBuffer = new byte[_dataRecv.Length]; Array.Copy(_dataRecv, 0, newBuffer, 0, _dataRecv.Length); //接受到应答数据 Console.WriteLine($"接受到PLC应答数据 0x06--true 0x15---false :{GetHexString(newBuffer)}"); if (newBuffer[0] == 0x06) { return(true); } return(false); } } throw new Exception("执行命令超时"); } finally { _dataRecv = null; } }
/// <summary> /// Sets the cursor to line 1 column 1. /// </summary> private static void SetCursorToLine(this GodSerialPort serial, Line lineNumber) { var command = new byte[6] { 0x1B, 0x5B, (byte)lineNumber, 0x3B, 0x31, 0x48 }; serial.Write(command, 0, 6); }
public DataResult WriteForResult(byte[] dataList, int timeOut) { if (!Monitor.TryEnter(_flag)) { throw new Exception("串口正在执行命令,请稍后"); } lock (_flag) { _dataRecv = null; if (null != _port && _port.IsOpen) { _port.Write(dataList); Console.WriteLine($"发送数据:{GetHexString(dataList)}"); } else { throw new Exception("请先打开串口"); } var index = 1; while (index < timeOut) { Thread.Sleep(1); index++; if (null != _dataRecv && _dataRecv.Length > 1) { var newBuffer = new byte[_dataRecv.Length]; Array.Copy(_dataRecv, 0, newBuffer, 0, _dataRecv.Length); //接受到应答数据 Console.WriteLine($"接受到应答数据:{GetHexString(newBuffer)}"); //对接受到的数据进行解析 if (!CommandFactory.ValidateData(newBuffer)) { throw new Exception("接受到的数据校验失败"); } return(new DataResult(newBuffer)); } } throw new Exception("执行命令超时"); } }
/// <summary> /// Clears the entire display and sets the cursor to line 1 column 1. /// </summary> private static void ClearScreen(this GodSerialPort serial) { var command = new byte[4] { 0x1B, 0x5B, 0x32, 0x4A }; try { serial.Write(command, 0, 4); //SetCursorToLine(serial, Line.One); } catch { } }
private void SendData(byte[] datas) { this.Dispatcher.Invoke(() => { content.Text = StringHelper.BytesToHexString(datas); }); if (_serialPort.IsOpen) { _serialPort.Write(datas); } else { Console.WriteLine("串口未打开"); } }