/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { SerialPort.DiscardInBuffer(); SerialPort.DiscardOutBuffer(); try { SerialPort.Write(buffer, offset, count); logText = BuildWriteLogText(buffer, offset, count, logFormat); WriteError = false; } catch (TimeoutException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } } catch (Exception ex) { WriteError = true; throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { // данный способ чтения данных необходим для избежания исключения // System.ObjectDisposedException при прерывании потока линии связи int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); SerialPort.ReadTimeout = 0; while (readCnt < count && startDT <= nowDT && nowDT <= stopDT) { try { readCnt += SerialPort.Read(buffer, offset + readCnt, count - readCnt); } catch (TimeoutException) { } // накопление входных данных в буфере порта if (readCnt < count) { Thread.Sleep(DataAccumThreadDelay); } nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Сформировать текст записи данных для вывода в журнал /// </summary> public static string BuildWriteLogText(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat) { return(CommPhrases.SendNotation + " (" + count + "): " + (logFormat == CommUtils.ProtocolLogFormats.Hex ? CommUtils.BytesToHex(buffer, offset, count) : CommUtils.BytesToString(buffer, offset, count))); }
/// <summary> /// Сформировать текст считывания данных для вывода в журнал /// </summary> public static string BuildReadLogText(byte[] buffer, int offset, int readCnt, CommUtils.ProtocolLogFormats logFormat) { return(CommPhrases.ReceiveNotation + " (" + readCnt + "): " + (logFormat == CommUtils.ProtocolLogFormats.Hex ? CommUtils.BytesToHex(buffer, offset, readCnt) : CommUtils.BytesToString(buffer, offset, readCnt))); }
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime utcNowDT = DateTime.UtcNow; DateTime startDT = utcNowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); IPEndPoint endPoint = CreateIPEndPoint(); stopReceived = false; UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout; while (readCnt < maxCount && !stopReceived && startDT <= utcNowDT && utcNowDT <= stopDT) { // считывание данных byte[] datagram = ReceiveDatagram(ref endPoint, out int readPos, out bool isNew); if (datagram != null && datagram.Length > 0) { // поиск кода остановки в считанных данных int stopCodeInd = -1; for (int i = readPos, len = datagram.Length; i < len && !stopReceived; i++) { if (stopCond.CheckCondition(datagram, i)) { stopCodeInd = i; stopReceived = true; } } // копирование полученных данных в заданный буфер int requiredCnt = stopReceived ? stopCodeInd - readCnt + 1 : maxCount - readCnt; int copyCnt = Math.Min(datagram.Length - readPos, requiredCnt); Array.Copy(datagram, readPos, buffer, readCnt + offset, copyCnt); readCnt += copyCnt; readPos += copyCnt; } // накопление данных во внутреннем буфере соединения if (readCnt < maxCount && !stopReceived && isNew) { Thread.Sleep(DataAccumThreadDelay); } StoreDatagram(datagram, readPos); utcNowDT = DateTime.UtcNow; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); IPEndPoint endPoint = CreateIPEndPoint(); UdpClient.Client.ReceiveTimeout = DatagramReceiveTimeout; while (readCnt < count && startDT <= nowDT && nowDT <= stopDT) { // считывание данных int readPos; bool isNew; byte[] datagram = ReceiveDatagram(ref endPoint, out readPos, out isNew); // копирование полученных данных в заданный буфер if (datagram != null && datagram.Length > 0) { int requiredCnt = count - readCnt; int copyCnt = Math.Min(datagram.Length - readPos, requiredCnt); Array.Copy(datagram, readPos, buffer, readCnt, copyCnt); readCnt += copyCnt; readPos += copyCnt; } // накопление данных во внутреннем буфере соединения if (readCnt < count && isNew) { Thread.Sleep(DataAccumThreadDelay); } StoreDatagram(datagram, readPos); nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); return(readCnt); } catch (SocketException ex) { logText = CommPhrases.ReadDataError + ": " + ex.Message; return(0); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные с условием остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); NetStream.ReadTimeout = OneByteReadTimeout; stopReceived = false; int curOffset = offset; byte stopCode = stopCond.StopCode; while (readCnt < maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT) { // считывание одного байта данных bool readOk; try { readOk = NetStream.Read(buffer, curOffset, 1) > 0; } catch (IOException) { readOk = false; } if (readOk) { stopReceived = buffer[curOffset] == stopCode; curOffset++; readCnt++; } else { // накопление данных во внутреннем буфере соединения Thread.Sleep(DataAccumThreadDelay); } nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); if (readCnt > 0) { UpdateActivityDT(); } return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { NetStream.Write(buffer, offset, count); logText = BuildWriteLogText(buffer, offset, count, logFormat); } catch (IOException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные /// </summary> public override int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime utcNowDT = DateTime.UtcNow; DateTime startDT = utcNowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); NetStream.ReadTimeout = timeout; // таймаут не выдерживается, если считаны все доступные данные while (readCnt < count && startDT <= utcNowDT && utcNowDT <= stopDT) { // считывание данных try { if (NetStream.DataAvailable) // checking DataAvailable is critical in Mono { readCnt += NetStream.Read(buffer, readCnt + offset, count - readCnt); } } catch (IOException) { } // накопление данных во внутреннем буфере соединения if (readCnt < count) { Thread.Sleep(DataAccumThreadDelay); } utcNowDT = DateTime.UtcNow; } logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); if (readCnt > 0) { UpdateActivityDT(); } return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public override int Read(byte[] buffer, int offset, int maxCount, int timeout, Connection.BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int readCnt = 0; DateTime nowDT = DateTime.Now; DateTime startDT = nowDT; DateTime stopDT = startDT.AddMilliseconds(timeout); stopReceived = false; byte stopCode = stopCond.StopCode; int curInd = offset; SerialPort.ReadTimeout = 0; while (readCnt <= maxCount && !stopReceived && startDT <= nowDT && nowDT <= stopDT) { bool readOk; try { readOk = SerialPort.Read(buffer, curInd, 1) > 0; } catch (TimeoutException) { readOk = false; } if (readOk) { stopReceived = buffer[curInd] == stopCode; curInd++; readCnt++; } else { // накопление входных данных в буфере порта Thread.Sleep(DataAccumThreadDelay); } nowDT = DateTime.Now; } logText = BuildReadLogText(buffer, offset, readCnt, logFormat); return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadDataWithStopCondError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные в последовательный порт /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер передаваемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="count">Количество передаваемых байт</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> public static void WriteToSerialPort(SerialPort serialPort, byte[] buffer, int index, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = WriteDataImpossible; } else { serialConn.SetSerialPort(serialPort); serialConn.Write(buffer, index, count, logFormat, out logText); } } catch (Exception ex) { logText = ex.Message; } }
/// <summary> /// Считать данные, доступные на текущий момент /// </summary> public int ReadAvailable(byte[] buffer, int offset, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { int count = TcpClient.Available; int readCnt = NetStream.Read(buffer, offset, count); logText = BuildReadLogText(buffer, offset, count, readCnt, logFormat); if (readCnt > 0) { UpdateActivityDT(); } return(readCnt); } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.ReadAvailableError + ": " + ex.Message, ex); } }
/// <summary> /// Записать данные /// </summary> public override void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (string.IsNullOrEmpty(RemoteAddress)) { throw new InvalidOperationException("RemoteAddress is undefined."); } if (RemotePort <= 0) { throw new InvalidOperationException("RemotePort is undefined."); } byte[] datagram; if (offset > 0) { datagram = new byte[count]; Array.Copy(buffer, offset, datagram, 0, count); } else { datagram = buffer; } try { int sentCnt = UdpClient.Send(datagram, count, RemoteAddress, RemotePort); logText = BuildWriteLogText(datagram, 0, count, logFormat); } catch (SocketException ex) { logText = CommPhrases.WriteDataError + ": " + ex.Message; } } catch (Exception ex) { throw new InvalidOperationException(CommPhrases.WriteDataError + ": " + ex.Message, ex); } }
/// <summary> /// Считать данные из последовательного порта /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер принимаемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="maxCount">Максимальное количество принимаемых байт</param> /// <param name="stopCode">Байт, означающий окончание считывания данных</param> /// <param name="timeout">Таймаут чтения данных, мс</param> /// <param name="wait">Ожидать завершения таймаута после окончания чтения</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> /// <returns>Количество считанных байт</returns> public static int ReadFromSerialPort(SerialPort serialPort, byte[] buffer, int index, int maxCount, byte stopCode, int timeout, bool wait /*игнорируется*/, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = ReadDataImpossible; return(0); } else { serialConn.SetSerialPort(serialPort); bool stopReceived; return(serialConn.Read(buffer, index, maxCount, timeout, new Connection.BinStopCondition(stopCode), out stopReceived, logFormat, out logText)); } } catch (Exception ex) { logText = ex.Message; return(0); } }
/// <summary> /// Считать данные из последовательного порта /// </summary> /// <param name="serialPort">Последовательный порт</param> /// <param name="buffer">Буфер принимаемых данных</param> /// <param name="index">Начальный индекс в буфере</param> /// <param name="count">Количество принимаемых байт</param> /// <param name="timeout">Таймаут чтения данных, мс</param> /// <param name="wait">Ожидать завершения таймаута после окончания чтения</param> /// <param name="logFormat">Формат вывода данных в журнал</param> /// <param name="logText">Строка для вывода в журнал</param> /// <returns>Количество считанных байт</returns> public static int ReadFromSerialPort(SerialPort serialPort, byte[] buffer, int index, int count, int timeout, bool wait /*игнорируется*/, CommUtils.ProtocolLogFormats logFormat, out string logText) { try { if (serialPort == null) { logText = ReadDataImpossible; return(0); } else { serialConn.SetSerialPort(serialPort); return(serialConn.Read(buffer, index, count, timeout, logFormat, out logText)); } } catch (Exception ex) { logText = ex.Message; return(0); } }
/// <summary> /// Считать данные /// </summary> /// <returns>Количество считанных байт</returns> public abstract int Read(byte[] buffer, int offset, int count, int timeout, CommUtils.ProtocolLogFormats logFormat, out string logText);
/// <summary> /// Записать данные /// </summary> public abstract void Write(byte[] buffer, int offset, int count, CommUtils.ProtocolLogFormats logFormat, out string logText);
/// <summary> /// Считать данные с условиями остановки чтения /// </summary> public abstract int Read(byte[] buffer, int offset, int maxCount, int timeout, BinStopCondition stopCond, out bool stopReceived, CommUtils.ProtocolLogFormats logFormat, out string logText);