private void SerialDataIntBUSResponse() { int byteRecieved = SerialPortIntBUS.BytesToRead; byte[] responseBytes = new byte[byteRecieved]; if (responseBytes.Length == 0) { return; } SerialPortIntBUS.Read(responseBytes, 0, byteRecieved); SerialPortIntBUS.DiscardInBuffer(); string message = BitConverter.ToString(responseBytes).Replace('-', ' '); message = AddTime(message); AddConsoleText(message + "\r", textBox_ConsoleIntBUS, Brushes.LimeGreen); List <byte> listBytes = new List <byte>(); listBytes.AddRange(responseBytes); listBytes = listBytes.Skip(2).ToList();//TODO переделать listBytes = listBytes.Take(listBytes.Count() - 2).ToList(); listBytes.AddRange(ModbusUtility.CalculateCrc(listBytes.ToArray())); responseBytes = listBytes.ToArray(); message = BitConverter.ToString(responseBytes).Replace('-', ' '); message = AddTime(message); if (SerialPortModbus != null) { if (SerialPortModbus.IsOpen) { SerialPortModbus.Write(responseBytes, 0, responseBytes.Length); } } }
private void SerialDataModbusReceived(object sender, SerialDataReceivedEventArgs e) { int byteRecieved = (sender as SerialPort).BytesToRead; byte[] receivedBytes = new byte[byteRecieved]; (sender as SerialPort).Read(receivedBytes, 0, byteRecieved); int mbAddress = receivedBytes.First(); IntbusDevice device; if (IntbusDevice.ModbusDeviceAddresses.ContainsKey(mbAddress) == true) { device = IntbusDevice.ModbusDeviceAddresses[mbAddress]; } else { return; } string message = null; List <byte> listBytes = new List <byte>(); listBytes.AddRange(receivedBytes); listBytes = device.ConvertToIntbusFrame(listBytes); if (SerialPortIntBUS != null) { if (SerialPortIntBUS.IsOpen) { message = null; for (int i = 0; i < listBytes.Count; i++) { message += String.Format("{0:X2} ", listBytes[i]); } ///////////////////////////////// receivedBytes = listBytes.ToArray(); SerialPortIntBUS.DiscardOutBuffer(); SerialPortIntBUS.DiscardInBuffer(); SerialPortIntBUS.Write(receivedBytes, 0, receivedBytes.Length); Task.Factory.StartNew(() => { Thread.Sleep(responseTimeOut); SerialDataIntBUSResponse(); }); message = AddTime(message); AddConsoleText(message + "\r", textBox_ConsoleIntBUS, Brushes.NavajoWhite); } } }