public static Serial GetChannel(SerialPortNames portName) { try { foreach (Channel c in m_channels) { if (c.GetType() == typeof(Serial)) { Serial serial = c as Serial; if (serial.PortName == portName) { return(serial); } } } return(null); } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
public static Ethernet GetChannel(string remoteIp, Int32 remotePort) { try { foreach (Channel c in m_channels) { if (c.GetType() == typeof(Ethernet)) { Ethernet ethernet = c as Ethernet; if ((ethernet.RemoteIP == remoteIp) && (ethernet.RemotePort == remotePort)) { return(ethernet); } } } return(null); } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
public static EthernetListener GetChannel(int port) { try { foreach (Channel c in m_channels) { if (c.GetType() == typeof(EthernetListener)) { EthernetListener listener = c as EthernetListener; if (listener.LocalPort == port) { return(listener); } } } return(null); } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
public static void GetChannel(int port, out ListenerServer listenerServer) { try { foreach (Channel c in m_channels) { if (c.GetType() == typeof(ListenerServer)) { ListenerServer listener = c as ListenerServer; if (listener.LocalPort == port) { listenerServer = listener; return; } } } listenerServer = null; } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
public static void ActivationService(Object activationService) { try { if (activationService is String) { string activationString = activationService as String; System.Security.Cryptography.MD5CryptoServiceProvider MD5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] encodedBytes = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(activationString)); activationString = Utils.HexEncoding.GetHexTwoCharsPerByte(encodedBytes); if (activationString == "7C765F7F05BC73663FFA9ED33B9998D5") { m_ActivationService = true; } else { m_ActivationService = false; } } } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
/// <summary> /// Closes the Socket connection and releases all associated resources. /// </summary> public override void Disconnect() { if (base.QueueCount != 0) { return; } if (m_PLCSocket != null) { if (m_PLCSocket.Connected) { m_PLCSocket.Close(); try { ComDriverLogger.LogConnectionState(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), ConnectionStatus.ConnectionClosed.ToString()); } catch { } } } }
public static void GetPLC(ListenerServer litenerServer) { try { bool isConnected = false; Channel plcChannel = getChannel(litenerServer, ref isConnected); ListenerServer listener = plcChannel as ListenerServer; if (listener == null) { throw new ComDriveExceptions("Listener Server could not be intialized due to unexpected error", ComDriveExceptions.ComDriveException.UnexpectedError); } listener.Listen(); } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
internal void Listen() { if (Status == ConnectionStatus.Disconnected) { m_ConnectionFlag = ConnectionFlag.None; try { socket.Listen(m_LocalPort); Status = ConnectionStatus.Listening; string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.Listening.ToString()); } catch { } } catch { throw new ComDriveExceptions( "Failed binding local port " + m_LocalPort.ToString() + ". Please check that the port is not in use", ComDriveExceptions.ComDriveException.PortInUse); } } else { //GetPLC was called. Therefore since we already listening then there are 2 options: //1. Socket is not connected and it is listening. When connection will arive then the PLC will be returned //2. Socket is connected. Therefore On Connect event will not happen and we need to return the PLC right now. Socket worker = socket.GetWorker(); if (Status == ConnectionStatus.Connected) { try { PLC plc = PLCFactory.GetPLC(this, 0); if (OnListenerConnectionAccepted != null) { OnListenerConnectionAccepted(plc); } } catch { try { worker.Close(); } catch { } } } else { System.Diagnostics.Debug.Print("Listen request denied... Connection Status: " + Status.ToString()); } } }
internal override void Connect() { if (!m_serialPort.IsOpen) { CheckPortName(m_SerialPortNames); m_serialPort.PortName = m_SerialPortNames.ToString(); try { m_serialPort.DtrEnable = true; m_serialPort.RtsEnable = true; m_serialPort.Open(); } catch (Exception ex) { throw new ComDriveExceptions(ex.Message, ComDriveExceptions.ComDriveException.PortInUse); } string text = ConnectionStatus.ConnectionOpened + " with BR" + m_serialPort.BaudRate.ToString() + "(" + m_serialPort.DataBits.ToString() + ", " + m_serialPort.Parity.ToString() + ", " + m_serialPort.StopBits.ToString() + ")"; ComDriverLogger.LogConnectionState(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), text); } }
public override void Disconnect() { if (base.QueueCount != 0) { return; } if (m_serialPort.IsOpen) { m_serialPort.Close(); AlreadyInitialized = false; try { ComDriverLogger.LogConnectionState(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), ConnectionStatus.ConnectionClosed.ToString()); } catch { } m_serialPort.Dispose(); } }
internal void Dispose() { // This function literally kills the socket, no matter if the message queue is not empty. try { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); Disposed = true; worker.Close(); if (OnConnectionClosed != null) { OnConnectionClosed(this); } string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } AbortAll(); } } catch (Exception ex) { string exceptionText = "InnerListenerClientEcxeption (Dispose)" + " - " + ex.Message; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); } }
private void initSocket(Socket socket, int port) { try { worker = socket; localPort = port; IPEndPoint ep = worker.RemoteEndPoint as IPEndPoint; RemoteIP = ep.Address.ToString(); string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionOpened.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } ListenerClientsInfo.IncrementCount(localPort); waitForData(); } catch (Exception ex) { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); } try { worker.Close(); } catch { } if (!Disposed) { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } } Disposed = true; string exceptionText = "InnerListenerClientEcxeption (initSocket)" + " - " + ex.Message; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); AbortAll(); } }
public ComDriveExceptions(string pExceptionMsg, ComDriveException pErrCode) : base(pExceptionMsg) { _errCode = pErrCode; string exceptionText = pErrCode.ToString() + " - " + pExceptionMsg; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); }
/// <summary> /// Closes the Socket connection and releases all associated resources. /// </summary> public override void Disconnect() { if (base.QueueCount != 0) { return; } Socket worker = socket.GetWorker(); try { AbortAll(); m_ConnectionFlag = ConnectionFlag.DisconnectedStopListening; socket.Close(); Status = ConnectionStatus.Disconnected; } catch { } string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString()); } catch { } if (worker != null) { System.Threading.Thread.Sleep(100); while (worker.Connected) { try { worker.Close(); } catch { } System.Threading.Thread.Sleep(100); } } }
public static void DisableLogger() { try { ComDriverLogger.Disable(); } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
void socket_OnSocektError(object sender, SocketError socketError) { // Socket error can be caused when Enfora closes the socket. if (m_ConnectionFlag == ConnectionFlag.DisconnectedStopListening) { AbortAll(); socket.Close(); } else { AbortAll(); System.Diagnostics.Debug.Print("Disconnected, back to listen"); if (OnListenerConnectionClosed != null) { OnListenerConnectionClosed(this); } m_ConnectionFlag = ConnectionFlag.DisconnectedResumeListening; Status = ConnectionStatus.Listening; socket.Close(); try { socket.Listen(m_LocalPort); } catch { throw new ComDriveExceptions( "Failed binding local port " + m_LocalPort.ToString() + ". Please check that the port is not in use", ComDriveExceptions.ComDriveException.PortInUse); } try { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString()); ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.Listening.ToString()); } catch { } } }
internal static PLC getPLC(ref Channel channel, int unitId, ref bool isConnected, bool suppressEthernetHeader) { try { isConnected = false; if (unitId < 0 || unitId > 127) { throw new ComDriveExceptions("UnitID out of range! The value must be between 0 and 127.", ComDriveExceptions.ComDriveException.InvalidUnitID); } Channel plcChannel = getChannel(channel, ref isConnected); channel = plcChannel; try { return(new PLC(unitId, plcChannel, suppressEthernetHeader)); } catch (ComDriveExceptions ex) { if ((!isConnected) && (channel.GetType() != typeof(EthernetListener))) { plcChannel.Disconnect(); } throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } } catch (ComDriveExceptions ex) { throw; } catch (Exception ex) { string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); throw; } }
private void appendReceivedDataToString(ref string incomingData) { byte[] tempBuffer; string bufferAsString; int bytesToRead; bytesToRead = m_serialPort.BytesToRead; if (bytesToRead > 0) { tempBuffer = new byte[bytesToRead]; m_serialPort.Read(tempBuffer, 0, bytesToRead); bufferAsString = ASCIIEncoding.ASCII.GetString(tempBuffer); incomingData += bufferAsString; ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), tempBuffer); } }
private void appendReceivedDataToArray(ref byte[] incomingData) { byte[] tempBuffer; byte[] copyOfBuffer; int bytesToRead; bytesToRead = m_serialPort.BytesToRead; if (bytesToRead > 0) { tempBuffer = new byte[bytesToRead]; m_serialPort.Read(tempBuffer, 0, bytesToRead); copyOfBuffer = incomingData; incomingData = new byte[copyOfBuffer.Length + tempBuffer.Length]; Array.Copy(copyOfBuffer, 0, incomingData, 0, copyOfBuffer.Length); Array.Copy(tempBuffer, 0, incomingData, copyOfBuffer.Length, tempBuffer.Length); ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), tempBuffer); } }
internal void OnDataReceived(byte[] receivedBytes) { int cbRead = receivedBytes.Length; byte[] tmpBuffer = new byte[receivedBuffer.Length + cbRead]; Array.Copy(receivedBuffer, 0, tmpBuffer, 0, receivedBuffer.Length); Array.Copy(receivedBytes, 0, tmpBuffer, receivedBuffer.Length, cbRead); receivedBuffer = tmpBuffer; ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), tmpBuffer); if (inputMode == InputMode.ASCII) { ClientReceiveString(); } else if (inputMode == InputMode.Binary) { ClientReceiveBytes(); } }
void socket_OnConnect(object sender, EventArgs e) { Status = ConnectionStatus.Connected; Socket worker = socket.GetWorker(); string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionOpened.ToString()); } catch (Exception ex) { // The PLC did not reply... Close the connection and return to Listen mode. { worker.Close(); Console.Write(ex.Message); } } try { System.Threading.Thread.Sleep(1000); PLC plc = PLCFactory.GetPLC(this, 0); if (OnListenerConnectionAccepted != null) { OnListenerConnectionAccepted(plc); } } catch (Exception ex) { // The PLC did not reply... Close the connection and return to Listen mode. { worker.Close(); Console.Write(ex.Message); } } }
private void onDataReceived(IAsyncResult ar) { SocketState socketState = null; try { socketState = (SocketState)ar.AsyncState; int cbRead = 0; cbRead = worker.EndReceive(ar); if (cbRead > 0) { byte[] temp = new byte[cbRead]; Array.Copy(socketState.ReceivedData, 0, temp, 0, cbRead); OnDataReceived(temp); waitForData(); } else { try { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); } worker.Close(); } catch { } if (!Disposed) { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } Disposed = true; AbortAll(); if (OnConnectionClosed != null) { OnConnectionClosed(this); } } } } catch (ObjectDisposedException) { try { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); } worker.Close(); } catch { } if (!Disposed) { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } Disposed = true; AbortAll(); if (OnConnectionClosed != null) { OnConnectionClosed(this); } } } catch (SocketException se) { try { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); } worker.Close(); } catch { } if (!Disposed) { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP + ", Client GUID: " + guid.ToString()); } catch { } Disposed = true; AbortAll(); if (OnConnectionClosed != null) { OnConnectionClosed(this); } } } catch { try { if (!Disposed) { ListenerClientsInfo.DecrementCount(localPort); } worker.Close(); } catch { } if (!Disposed) { string channelLog = Utils.HelperComDriverLogger.GetLoggerChannel(this); try { ComDriverLogger.LogConnectionState(DateTime.Now, channelLog, Unitronics.ComDriver.ConnectionStatus.ConnectionClosed.ToString() + ", Remote IP (Client): " + RemoteIP); } catch { } Disposed = true; AbortAll(); if (OnConnectionClosed != null) { OnConnectionClosed(this); } } } }
internal override void Connect() { if (m_PLCSocket != null) { if (m_PLCSocket.Connected) { return; } try { m_PLCSocket.Close(); } catch { } } if (Protocol == EthProtocol.TCP) { m_PLCSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } else { m_PLCSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } SocketState socketState = new SocketState(); socketState.Socket = m_PLCSocket; socketState.State = SocketState.ConnectionState.Connecting; bool isHostNameMode = false; IPAddress ipAddress = null; try { ipAddress = IPAddress.Parse(m_remoteIPorHostName); } catch { isHostNameMode = true; } IPEndPoint PLCIPEndPoint = null; if (!isHostNameMode) { PLCIPEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(m_remotePort)); } try { if (!isHostNameMode) { IAsyncResult result = m_PLCSocket.BeginConnect(PLCIPEndPoint, socketConnect, socketState); bool success = result.AsyncWaitHandle.WaitOne(connectTimeOut, true); lock (socketState) { if (success) { try { m_PLCSocket.EndConnect(result); } catch { socketState.State = SocketState.ConnectionState.Failed; throw; } } else { socketState.State = SocketState.ConnectionState.Failed; throw new SocketException(10060); } } // Enfora modems Suck. It require a sleep after the connection before data is being sent to it // Otherwise the communication fails. Thread.Sleep(500); } else { IAsyncResult result = m_PLCSocket.BeginConnect(m_remoteIPorHostName, m_remotePort, socketConnect, socketState); bool success = result.AsyncWaitHandle.WaitOne(connectTimeOut, true); lock (socketState) { if (success) { try { m_PLCSocket.EndConnect(result); } catch { socketState.State = SocketState.ConnectionState.Failed; throw; } } else { socketState.State = SocketState.ConnectionState.Failed; throw new SocketException(10060); } } // Enfora modems Suck. It require a sleep after the connection before data is being sent to it // Otherwise the communication fails. Thread.Sleep(500); } string text = ConnectionStatus.ConnectionOpened + " on port " + m_remotePort.ToString(); ComDriverLogger.LogConnectionState(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), text); } catch (SocketException se) { if (se.Message.Contains(m_remoteIPorHostName)) { throw new ComDriveExceptions(se.Message, ComDriveExceptions.ComDriveException.GeneralCommunicationError); } else { throw new ComDriveExceptions(se.Message + " " + m_remoteIPorHostName + ":" + m_remotePort, ComDriveExceptions.ComDriveException.GeneralCommunicationError); } } }
private void socketReceivedBytes(byte[] incomingBytes, int count) { bool bStxFound = false; byte[] tempBuffer; string bufferAsString; int index = 0; int totalLength = 0; byte[] tcpHeader; const int HEADER_LENGTH = 24; tcpHeader = ethernetHeader; try { int cbRead = 0; cbRead = count; if (cbRead > 0) { byte[] temp = new byte[cbRead]; Array.Copy(incomingBytes, 0, temp, 0, cbRead); ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), temp); byte[] tmpBuffer = new byte[incomingData.Length + cbRead]; Array.Copy(incomingData, 0, tmpBuffer, 0, incomingData.Length); Array.Copy(temp, 0, tmpBuffer, incomingData.Length, cbRead); incomingData = tmpBuffer; } else { // Socket was closed? m_PLCSocket.Close(); } } catch { // Socket Error? m_PLCSocket.Close(); } if (incomingData.Length >= Utils.Lengths.LENGTH_TCP_HEADER) { if (incomingData.Take(4).SequenceEqual(tcpHeader) == true) { tempBuffer = new byte[incomingData.Length - 6]; Array.Copy(incomingData, 6, tempBuffer, 0, incomingData.Length - 6); incomingData = tempBuffer; } else { //throw new ComDriveExceptions("Ethernet Transaction ID mismatch", ComDriveExceptions.ComDriveException.TransactionIdMismatch); } } if (incomingData.Length > 0) { bufferAsString = ASCIIEncoding.ASCII.GetString(incomingData); index = bufferAsString.IndexOf(STX_STRING); if (index >= 0) { tempBuffer = new byte[incomingData.Length - index]; Array.Copy(incomingData, index, tempBuffer, 0, incomingData.Length - index); incomingData = tempBuffer; bStxFound = true; } else { if (incomingData.Length > 100) { throw new ComDriveExceptions("STX is missing", ComDriveExceptions.ComDriveException.CommunicationTimeout); } } } if (!bStxFound) { return; } if (incomingData.Length < HEADER_LENGTH) { return; } totalLength = BitConverter.ToUInt16(incomingData, 20) + HEADER_LENGTH + 3; // 3 for data checksum + ETX if (incomingData.Length < totalLength) { return; } tempBuffer = new byte[totalLength]; Array.Copy(incomingData, 0, tempBuffer, 0, totalLength); incomingData = tempBuffer; tempBuffer = null; if (incomingData[totalLength - 1] != 92) // 92 is '\' which is the ETX { throw new ComDriveExceptions("ETX is missing", ComDriveExceptions.ComDriveException.ETXMissing); } messageReceived = true; }
private void socketReceivedString(byte[] incomingBytes, int count) { bool bStxFound = false; bool bEtxFound = false; string incomingString = ""; byte[] tempBuffer; byte[] tcpHeader; int index = 0; int checksum = 0; try { int cbRead = 0; cbRead = count; if (cbRead > 0) { byte[] temp = new byte[cbRead]; Array.Copy(incomingBytes, 0, temp, 0, cbRead); ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), temp); byte[] tmpBuffer = new byte[incomingData.Length + cbRead]; Array.Copy(incomingData, 0, tmpBuffer, 0, incomingData.Length); Array.Copy(temp, 0, tmpBuffer, incomingData.Length, cbRead); incomingData = tmpBuffer; } else { // Socket was closed? m_PLCSocket.Close(); } } catch { // Socket Error? m_PLCSocket.Close(); } tcpHeader = ethernetHeader; incomingString = ASCIIEncoding.ASCII.GetString(incomingData); if (!_suppressEthernetHeader && incomingString.Length >= Utils.Lengths.LENGTH_TCP_HEADER) { if (incomingData.Take(4).SequenceEqual(tcpHeader) == true) { tempBuffer = new byte[incomingString.Length - 6]; Array.Copy(incomingData, 6, tempBuffer, 0, incomingData.Length - 6); incomingData = tempBuffer; incomingString = ASCIIEncoding.ASCII.GetString(incomingData); } else { //throw new ComDriveExceptions("Ethernet Transaction ID mismatch", ComDriveExceptions.ComDriveException.TransactionIdMismatch); } } if (incomingString.Length > 0) { index = incomingString.IndexOf("/"); // find the STX if (index >= 0) { incomingString = incomingString.Substring(index, incomingString.Length - index); bStxFound = true; } else { if (incomingString.Length > 100) { throw new ComDriveExceptions("STX is missing", ComDriveExceptions.ComDriveException.CommunicationTimeout); } } index = incomingString.IndexOf("\r"); // find the ETX if (index >= 0) { incomingString = incomingString.Substring(0, index + 1); bEtxFound = true; } } if (!bStxFound || !bEtxFound) { return; } for (int i = 2; i < incomingString.Length - 3; i++) { checksum += incomingData[i]; } string CRC = Utils.DecimalToHex(checksum % 256); if (CRC != incomingString.Substring(incomingString.Length - 3, 2)) { throw new ComDriveExceptions("Wrong Data Checksum", ComDriveExceptions.ComDriveException.ChecksumError); } messageReceived = true; }
internal void ReadWrite(ref ReadWriteRequest[] values, bool suppressEthernetHeader) { lock (objectLocker) { m_BreakFlagCount++; } System.Diagnostics.Debug.Print("Entering Read Write. Count: " + m_BreakFlagCount.ToString()); Guid parentID = Guid.NewGuid(); List <ReadWriteRequest> requestsList = new List <ReadWriteRequest>(); try { ComDriverLogger.LogReadWriteRequest(DateTime.Now, m_channel.GetLoggerChannelText(), values, MessageDirection.Sent, parentID.ToString()); CheckReadWriteRequests(values); for (int i = 0; i < values.Length; i++) { ReadWriteRequest rw = values[i]; if ((rw is ReadOperands) || (rw is WriteOperands)) { requestsList.Add(rw); if (i == values.Length - 1) { if (requestsList.Count > 0) { ReadWriteRequest[] requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } } } else if ((rw is ReadDataTables) || (rw is WriteDataTables)) { ReadWriteRequest[] requestsArray; if (requestsList.Count > 0) { requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } requestsArray = new ReadWriteRequest[] { rw }; if (DataTablesExecuter != null) { DataTablesExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Data Tables", ComDriveExceptions.ComDriveException.UnsupportedCommand); } } else if (rw is BinaryRequest) { ReadWriteRequest[] requestsArray; if (requestsList.Count > 0) { requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } requestsArray = new ReadWriteRequest[] { rw }; BinaryRequest br = rw as BinaryRequest; switch (br.CommandCode) { case 0x1: //Read Ram/Flash case 0x41: //Write Ram/Flash case 62: //Set Password case 0x2: //verify password case 0x9: //Download Start case 0x45: //Download End case 0xA: //Erase Flash case 0x7: //Wait for flash idle case 0xB: //Blind mode case 0x13: //UnBlind mode case 0xF: //Put PLC in state (Preebot, boot, OS Stop, OS Run) case 0xC: //Get PLC Name if (BasicBinaryExecuter != null) { BasicBinaryExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Basic Binary commands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } break; default: if (BinaryExecuter != null) { BinaryExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Binary Commands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } break; } } } } catch (Exception ex) { ComDriveExceptions comDriveException = ex as ComDriveExceptions; if (comDriveException != null) { if ((comDriveException.ErrorCode == ComDriveExceptions.ComDriveException.AbortedByUser) || m_BreakFlag) { throw; } else if (m_BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } else { throw; } } else if (m_BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } else { throw; } } finally { lock (objectLocker) { m_BreakFlagCount--; } System.Diagnostics.Debug.Print("Exiting Read Write. Count: " + m_BreakFlagCount.ToString()); ComDriverLogger.LogReadWriteRequest(DateTime.Now, m_channel.GetLoggerChannelText(), values, MessageDirection.Received, parentID.ToString()); } }
private void SendQueueIterator(Object objectState) { while (queueHasItems()) { MessageRecord messsage = null; lock (messageQueue) { if (messageQueue.Any()) { abortRetries = false; messsage = messageQueue.Dequeue(); } } if (messsage != null && !messsage.IsSent && messsage.MessageResponse == null) { int retry = m_retry; bool plcReplyReceived = false; if (messsage.ReceiveStringDelegate != null) { while (!plcReplyReceived && retry > 0) { try { SendString(messsage.MessageRequest as string, messsage.MessageEnumerator, messsage.IsIdMessage, messsage.SuppressEthernetHeader); //Log the requests if (ComDriverLogger.Enabled) { string retryLog = Utils.HelperComDriverLogger.GetLoggerCurrentRetry(m_retry - retry + 1, m_retry); ComDriverLogger.LogFullMessage(DateTime.Now, GetLoggerChannelText(), messsage.MessageGuid.ToString(), MessageDirection.Sent, retryLog, messsage.MessageRequest as string, messsage.ParentID, messsage.Description); } try { messsage.MessageResponse = ReceiveString(); plcReplyReceived = true; //Log the requests if (ComDriverLogger.Enabled) { string retryLog = Utils.HelperComDriverLogger.GetLoggerCurrentRetry(m_retry - retry + 1, m_retry); ComDriverLogger.LogFullMessage(DateTime.Now, GetLoggerChannelText(), messsage.MessageGuid.ToString(), MessageDirection.Received, retryLog, messsage.MessageResponse, messsage.ParentID, messsage.Description); } } catch (TimeoutException ex) { if (abortRetries) { retry = 1; } if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } catch (ComDriveExceptions ex) { if (abortRetries) { retry = 1; } if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } } catch (Exception ex) { if (abortRetries) { retry = 1; } string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } if (PLCFactory.MessageDelay != 0) { System.Threading.Thread.Sleep(PLCFactory.MessageDelay); } } if (retry <= 0) { messsage.ReceiveStringDelegate(null, CommunicationException.Timeout, messsage.MessageGuid); } else { messsage.ReceiveStringDelegate(messsage.MessageResponse as string, CommunicationException.None, messsage.MessageGuid); } } else { while (!plcReplyReceived && retry > 0) { try { SendBytes(messsage.MessageRequest as byte[], messsage.MessageEnumerator); string retryLog = Utils.HelperComDriverLogger.GetLoggerCurrentRetry(m_retry - retry + 1, m_retry); //Log the requests if (ComDriverLogger.Enabled) { ComDriverLogger.LogFullMessage(DateTime.Now, GetLoggerChannelText(), messsage.MessageGuid.ToString(), MessageDirection.Sent, retryLog, messsage.MessageRequest as byte[], messsage.ParentID, messsage.Description); } try { messsage.MessageResponse = ReceiveBytes(); plcReplyReceived = true; //Log the requests if (ComDriverLogger.Enabled) { ComDriverLogger.LogFullMessage(DateTime.Now, GetLoggerChannelText(), messsage.MessageGuid.ToString(), MessageDirection.Received, retryLog, messsage.MessageResponse, messsage.ParentID, messsage.Description); } } catch (TimeoutException ex) { if (abortRetries) { retry = 1; } if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } catch (ComDriveExceptions ex) { if (abortRetries) { retry = 1; } if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } } catch (Exception ex) { if (abortRetries) { retry = 1; } string exceptionText = ex.GetType().ToString() + ": " + ex.Message + "\n\n" + ex.StackTrace; ComDriverLogger.LogExceptions(DateTime.Now, exceptionText); if (OnRetry != null) { OnRetry((m_retry - retry) + 1, ex); } retry--; if (this is Serial) { try { bool channelInitialized = AlreadyInitialized; Disconnect(); Connect(); AlreadyInitialized = channelInitialized; } catch { } } } if (PLCFactory.MessageDelay != 0) { System.Threading.Thread.Sleep(PLCFactory.MessageDelay); } } if (retry <= 0) { messsage.ReceiveBytesDelegate(null, CommunicationException.Timeout, messsage.MessageGuid); } else { messsage.ReceiveBytesDelegate(messsage.MessageResponse as byte[], CommunicationException.None, messsage.MessageGuid); } } messsage.IsSent = true; } } lock (messageQueue) { m_threadIsRunning = false; if (messageQueue.Any()) { messageQueue_Changed(); } } }
private void serialPortReceiveBytes(byte[] incomingBytes, int count) { bool bStxFound = false; byte[] tempBuffer; string bufferAsString; int index = 0; UInt16 pcCheckSum; int totalLength = 0; const int HEADER_LENGTH = 24; if (count > 0) { byte[] temp = new byte[count]; Array.Copy(incomingBytes, 0, temp, 0, count); ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), temp); byte[] tmpBuffer = new byte[resultBytes.Length + count]; Array.Copy(resultBytes, 0, tmpBuffer, 0, resultBytes.Length); Array.Copy(temp, 0, tmpBuffer, resultBytes.Length, count); resultBytes = tmpBuffer; } if (resultBytes.Length > 0) { bufferAsString = ASCIIEncoding.ASCII.GetString(resultBytes); index = bufferAsString.IndexOf(STX_STRING); if (index >= 0) { tempBuffer = new byte[resultBytes.Length - index]; Array.Copy(resultBytes, index, tempBuffer, 0, resultBytes.Length - index); resultBytes = tempBuffer; bStxFound = true; } else { if (resultBytes.Length > 100) { throw new ComDriveExceptions("STX is missing", ComDriveExceptions.ComDriveException.CommunicationTimeout); } } } else { return; } if (!bStxFound) { return; } if (resultBytes.Length < HEADER_LENGTH) { return; } pcCheckSum = Utils.calcCheckSum(ref resultBytes, 0, 21); if (pcCheckSum != BitConverter.ToUInt16(resultBytes, 22)) { throw new ComDriveExceptions("Wrong Header Checksum", ComDriveExceptions.ComDriveException.ChecksumError); } totalLength = BitConverter.ToUInt16(resultBytes, 20) + HEADER_LENGTH + 3; // 3 for data checksum + ETX if (resultBytes.Length < totalLength) { return; } tempBuffer = new byte[totalLength]; Array.Copy(resultBytes, 0, tempBuffer, 0, totalLength); resultBytes = tempBuffer; tempBuffer = null; pcCheckSum = Utils.calcCheckSum(ref resultBytes, 24, totalLength - 4); if (pcCheckSum != BitConverter.ToUInt16(resultBytes, totalLength - 3)) { throw new ComDriveExceptions("Wrong Data Checksum", ComDriveExceptions.ComDriveException.ChecksumError); } if (resultBytes[totalLength - 1] != 92) // 92 is '\' which is the ETX { throw new ComDriveExceptions("ETX is missing", ComDriveExceptions.ComDriveException.ETXMissing); } messageReceived = true; }
private void serialPortReceiveString(byte[] incomingBytes, int count) { bool bStxFound = false; bool bEtxFound = false; int index = 0; int checksum = 0; string resultString; if (count > 0) { byte[] temp = new byte[count]; Array.Copy(incomingBytes, 0, temp, 0, count); ComDriverLogger.LogReceivedMessageChunk(DateTime.Now, Utils.HelperComDriverLogger.GetLoggerChannel(this), temp); byte[] tmpBuffer = new byte[resultBytes.Length + count]; Array.Copy(resultBytes, 0, tmpBuffer, 0, resultBytes.Length); Array.Copy(temp, 0, tmpBuffer, resultBytes.Length, count); resultBytes = tmpBuffer; } resultString = ASCIIEncoding.ASCII.GetString(resultBytes); if (resultString.Length > 0) { index = resultString.IndexOf("/"); // find the STX if (index >= 0) { resultString = resultString.Substring(index, resultString.Length - index); byte[] tempBuffer = new byte[resultBytes.Length - index]; Array.Copy(resultBytes, index, tempBuffer, 0, resultBytes.Length - index); resultBytes = tempBuffer; bStxFound = true; } else { if (resultString.Length > 100) { throw new ComDriveExceptions("STX is missing", ComDriveExceptions.ComDriveException.CommunicationTimeout); } } index = resultString.IndexOf("\r"); // find the ETX if (index >= 0) { resultString = resultString.Substring(0, index + 1); bEtxFound = true; } } else { return; } if (!bStxFound || !bEtxFound) { return; } for (int i = 2; i < resultString.Length - 3; i++) { checksum += resultBytes[i]; } string CRC = Utils.DecimalToHex(checksum % 256); if (CRC != resultString.Substring(resultString.Length - 3, 2)) { throw new ComDriveExceptions("Wrong Data Checksum", ComDriveExceptions.ComDriveException.ChecksumError); } messageReceived = true; }
public static void LoadLoggerSettingsFromConfig() { ComDriverLogger.Disable(); }