/// <summary> /// Send Data to the Connected Serial Port /// </summary> /// <param name="message"></param> private void ConnectionInterface_SendMsgData(MsgData msg) { // If the Message is empty we do not send anything if (msg.value == null) { return; } // Send the Data try { msg.connectionNumber = connectionSelectionSendData; if (connection.Send(msg) == 1) { // Everything is fine } } catch { // Configure the message box to be displayed string messageBoxText = "Der Senden Job konnte nicht bearbeitet werden. Das Telegramm ist ungültig!"; string caption = "Ungültige parameter für das Senden"; MessageBoxButton button = MessageBoxButton.OK; MessageBoxImage icon = MessageBoxImage.Warning; // Display message box MessageBox.Show(messageBoxText, caption, button, icon); } }
/// <summary> /// View Binary Values of the In and Outgoing Data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menuItem_ViewRepresentationChange_Click(object sender, RoutedEventArgs e) { MenuItem menuItemSender = sender as MenuItem; // Save the current SendBox Data with the Current View Settings try { currentSendData = msgLog.getRawMsgWithCurrentViewSettings(tbSendData.Text); } catch { currentSendData = msgLog.getRawMsgWithCurrentViewSettings(""); } // Set the Current View Configuration try { settings.viewSettings.dataPresentation = (Int32)menuItemSender.Resources["ViewRepresentation"]; } catch { settings.viewSettings.dataPresentation = 0; } msgLog.viewSettings = settings.viewSettings; // Update the StatusBar UpdateViewStateDependence(msgLog.viewSettings); }
/// <summary> /// Send Data over Serial Interface /// </summary> /// <param name="data"></param> public void send(MsgData message) { if (pcSerialPort.IsOpen) { try { // Send the Data over Serial and to the UI pcSerialPort.Write(message.value, 0, message.value.Length);// Send the Data after replacing the Human Readable ASCII Chars message.setCurrentTimeStamp(); // Set the Time Stamp message.connectionNumber = interfaceNumber; // Set the Interface Reference // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = message; msgSendRecived(msgLogEventArgs); } catch (Exception ex) { MsgData logMessage = new MsgData(); // Set an error Message to the UI logMessage.value = Encoding.ASCII.GetBytes("Konnte nicht gesendet werden: " + message.value + "\n" + ex); logMessage.type = MsgData.messageType.infoNegative; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = message; msgSendRecived(msgLogEventArgs); } } }
/// <summary> /// Returns the previous MSG in the Send History /// </summary> /// <returns></returns> public string getPriviousSendedMsg() { // Check if the History allready exist if (sendHistory.Count == 0) { return(""); } MsgData sendMsgHistoryItem = new MsgData(); // Increment the Index of the History List if (sendMsgHistoryCurrentIndex >= sendHistory.Count - 1) { sendMsgHistoryCurrentIndex = 0; } else { sendMsgHistoryCurrentIndex++; } sendMsgHistoryItem = sendHistory.ElementAt(sendMsgHistoryCurrentIndex); return(getMsgWithCurrentViewSettings(sendMsgHistoryItem)); }
/// <summary> /// Update of the Input is Available pass it through to the Interface /// </summary> /// <param name="newInputMsg"></param> public void InputUpdate(MsgData newInputMsg) { if (simulationInterface != null) { simulationInterface.InputUpdate(newInputMsg); } }
/// <summary> /// Redirect the Log Messages Fromm the Connections /// </summary> /// <param name="logMessage"></param> public void SendRecivedEventHandler(object sender, MsgSendRecivedEventArgs e) { ConnectionInterface connection = sender as ConnectionInterface; if (e.msgData.type == MsgData.messageType.recived) { // Create a new Send Object! MsgData sendData = new MsgData(e.msgData.value, MsgData.messageType.redirect); if (connection.interfaceNumber == 1) { connection2.Send(sendData); } else { connection1.Send(sendData); } // Update the MsgLog bevore we send the Data to the Corresponding Data msgSendRecived(e); } else if (e.msgData.type == MsgData.messageType.send) { // Update the Msg Log with the injected Message by the User msgSendRecived(e); } else if (e.msgData.type == MsgData.messageType.infoPositive || e.msgData.type == MsgData.messageType.infoNegative) { msgSendRecived(e); } }
/// <summary> /// Get the Value from the Message and convert it to an ASCII Charakter String /// This is used to show User hints /// </summary> /// <param name="msg"></param> /// <returns></returns> public static string msgDataToAsciiChar(MsgData msg) { // Convert the Array of byte to a string ASCIIEncoding encoder = new ASCIIEncoding(); return(encoder.GetString(msg.value, 0, (int)msg.value.LongLength)); }
/// <summary> /// Send Data to the Connected Serial Port /// </summary> /// <param name="message"></param> private void ConnectionInterface_Send(string message) { // If the Message is empty we do not send anything if (message == "") { return; } // Send the Data try { MsgData newSendMsg = msgLog.getRawMsgWithCurrentViewSettings(message); newSendMsg.connectionNumber = connectionSelectionSendData; if (connection.Send(newSendMsg) == 1) { msgLog.messageWasSend(msgLog.getRawMsgWithCurrentViewSettings(message)); tbSendData.Text = ""; } } catch { // Configure the message box to be displayed string messageBoxText = "Die Eingaben passen nicht zu der aktuellen Darstellung. Bitte Eingaben überprüfen."; string caption = "Ungültige Eingabe für das Senden"; MessageBoxButton button = MessageBoxButton.OK; MessageBoxImage icon = MessageBoxImage.Warning; // Display message box MessageBox.Show(messageBoxText, caption, button, icon); } }
/// <summary> /// This function allows to convert the User Inut String before storing the data in the ringbuffer /// </summary> /// <param name="stringMessage"></param> public MsgData getRawMsgWithCurrentViewSettings(string stringMessage) { // Define the needed Variables MsgData message = new MsgData(); message.setCurrentTimeStamp(); // Variables for the Split string[] splitValues = new string[] { ",", " " }; string[] splitedMsg = stringMessage.Split(splitValues, 1024, StringSplitOptions.RemoveEmptyEntries); byte[] rawData = new byte[splitedMsg.Length]; // Convert the User Input to the Current Settings // Return the Msg with the Current View Configuration switch (viewSettings.dataPresentation) { default: // ASCII Encoded Strings message.value = Converty.specialAsciiStringToMsgData(stringMessage); break; case 1: // HEX Values of the Bytes recived for (int i = 0; i <= splitedMsg.Length - 1; i++) { rawData[i] = Convert.ToByte(splitedMsg[i], 16); } message.value = rawData; break; case 2: // DEC Values of the Bytes recived for (int i = 0; i <= splitedMsg.Length - 1; i++) { rawData[i] = Convert.ToByte(splitedMsg[i], 10); } message.value = rawData; break; case 3: // BIN Values of the Bytes recived for (int i = 0; i <= splitedMsg.Length - 1; i++) { rawData[i] = Convert.ToByte(splitedMsg[i], 2); } message.value = rawData; break; } return(message); }
/// <summary> /// /// </summary> /// <param name="msg"></param> /// <returns></returns> public static string msgDataToDecData(MsgData msg) { var sb = new StringBuilder(); foreach (char t in msg.value) { sb.Append(Convert.ToInt32(t).ToString("G") + " "); } return(sb.ToString()); }
/// <summary> /// /// </summary> /// <param name="msg"></param> /// <returns></returns> public static string msgDataToBinData(MsgData msg) { var sb = new StringBuilder(); foreach (byte t in msg.value) { sb.Append(Convert.ToString(t, 2) + " "); } return(sb.ToString()); }
/// <summary> /// Connect the Serial Port /// </summary> public void connect() { MsgData logMessage = new MsgData(); // Check if we have to close the Serial Port! if (pcSerialPort != null) { if (pcSerialPort.IsOpen) { pcSerialPort.Close(); } } else { pcSerialPort = new SerialPort(); } // Open the Serial Port try { // Set the Serial Paramter pcSerialPort.PortName = pcSerialParam.port; pcSerialPort.BaudRate = pcSerialParam.baud; pcSerialPort.DataBits = pcSerialParam.dataBits; pcSerialPort.Parity = pcSerialParam.parity; pcSerialPort.StopBits = pcSerialParam.stopBits; // Add a new ComPort on Recive Handler pcSerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); pcSerialPort.Open(); // Set the User Hint logMessage.value = Encoding.ASCII.GetBytes("Verbindung: " + pcSerialPort.PortName + " Erfolgreich aufgebaut"); logMessage.type = MsgData.messageType.infoPositive; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } catch (Exception) { // Set a User Hint logMessage.value = Encoding.ASCII.GetBytes("Verbindung: " + pcSerialPort.PortName + " Konnte nicht aufgebaut werden"); logMessage.type = MsgData.messageType.infoNegative; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } }
/// <summary> /// /// </summary> /// <param name="msg"></param> /// <returns></returns> public static string msgDataToHexData(MsgData msg) { var sb = new StringBuilder(); foreach (char t in msg.value) { //sb.Append(String.Format("{0:X}", t)); sb.Append(Convert.ToInt32(t).ToString("x2") + " "); } return(sb.ToString().ToUpper()); }
/// <summary> /// Try to send the Data to the Requested Connection /// </summary> /// <param name="message"></param> /// <returns></returns> public int Send(MsgData message) { if (message.connectionNumber == 1) { connection1.Send(message); } else { connection2.Send(message); } return(1); }
/// <summary> /// Update the ui With an Log Message and trigger the UpdateStatusBar /// </summary> /// <param name="rtbMsg">Message for the Log Window</param> /// <param name="msgType">Msg Type</param> private void updateUi(string rtbMsg, MsgData.messageType msgType) { // Set the User Hint to the TextBox MsgData logMessage = new MsgData(); logMessage.value = Encoding.ASCII.GetBytes(rtbMsg); logMessage.type = msgType; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); }
/// <summary> /// Send the Data to the Eventhandler.. To update the Main UI and send the Data to teh Connection /// </summary> private void SendData(string data) { // Set the User Hint to the TextBox MsgData _logMessage = new MsgData(); _logMessage.value = Converty.specialAsciiStringToMsgData(data); _logMessage.type = MsgData.messageType.send; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs _msgLogEventArgs = new MsgSendRecivedEventArgs(); _msgLogEventArgs.msgData = _logMessage; msgSendRecived(_msgLogEventArgs); }
/// <summary> /// Control of the Simulation Working State /// </summary> /// <param name="requestedState">Set the State of the Simulation State Stop = Stopping end ending the Thread // Pause = Stop the Simulation but dont end it // Run = Start the Simulation </param> public void RequestStateChange(Simulation_State requestedState) { switch (requestedState) { // Stop the Simulation Thread case Simulation_State.Stop: // If the Thread is Paused we wake him up to kill him! if (state == Simulation_State.Pause) { lastMsg = null; // Discard the recived Msg's if we got some during the Pause state simulationWorkingThread.Interrupt(); pauseThread = false; } stopThread = true; break; // Pause the Simulation Thread case Simulation_State.Pause: pauseThread = true; break; // Start the Simulation Thread case Simulation_State.Run: if (state == Simulation_State.Pause) { lastMsg = null; // Discard the recived Msg's if we got some during the Pause state simulationWorkingThread.Interrupt(); pauseThread = false; } else { simulationWorkingThread = new Thread(new ThreadStart(WorkingThread)); simulationWorkingThread.Start(); lastMsg = null; // Discard the recived Msg's if we got some during the Pause state } break; default: // Console.WriteLine("No valit Simulation State Request enterd"); break; } }
/// <summary> /// Blocking call to wait for a specific MSG to recive /// </summary> /// <param name="data">Msg Data to be recived</param> private bool WaitForMsg(string data) { bool returnVal = false; // Only check the Data if thei are Valid if (lastMsg != null && lastMsg.type == MsgData.messageType.recived) { if (compareRecivedAndSimMessage(lastMsg, data)) { lastMsg = null;// before leaving the loop erase the Data returnVal = true; } } return(returnVal); }
/// <summary> /// Try to send the Data to the Requested Connection /// </summary> /// <param name="message"></param> /// <returns>Not yet Implemented feature to return the Send was Completed or not</returns> public int Send(MsgData message) { message.type = MsgData.messageType.send; if (connectionSettings.functionSelect == 0) { singleConnection.Send(message); } else if (connectionSettings.functionSelect == 1) { multiConnection.Send(message); } return(1); }
/// <summary> /// Click of the Quick Button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void QuickButton_Click(object sender, RoutedEventArgs e) { Button _quickButton = sender as Button; // Set the User Hint to the TextBox MsgData logMessage = new MsgData(); logMessage.value = Converty.specialAsciiStringToMsgData((String)_quickButton.Resources["data"]); logMessage.type = MsgData.messageType.send; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); }
/// <summary> /// Send Data to the Client or Server /// </summary> /// <param name="message"></param> public void send(MsgData message) { if (tcpClient.Connected) { NetworkStream clientStream = tcpClient.GetStream(); clientStream.Write(message.value, 0, message.value.Length); clientStream.Flush(); message.setCurrentTimeStamp(); // Set the Time Stamp message.connectionNumber = interfaceNumber; // Set the reference to the Interface // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = message; msgSendRecived(msgLogEventArgs); } }
/// <summary> /// /// </summary> /// <param name="inputKey"></param> public void KeyInpuEvent(Key inputKey) { foreach (Button _button in buttonList) { if ((Key)_button.Resources["shortCut"] == inputKey) { // Set the User Hint to the TextBox MsgData logMessage = new MsgData(); logMessage.value = Converty.specialAsciiStringToMsgData((String)_button.Resources["data"]); logMessage.type = MsgData.messageType.send; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } } }
/// <summary> /// Try to send the Data to the Requested Connection /// </summary> /// <param name="message"></param> /// <returns></returns> public int Send(MsgData message) { if (connectionSettings.currentConnectionSetting == 1) { if (tcpConnection != null) { tcpConnection.send(message); } } else if (connectionSettings.currentConnectionSetting == 2) { if (serialConnection != null) { serialConnection.send(message); } } return(1); }
/// <summary> /// Compare the simulation Data with the recived Data. With all the Fancy Placeholders and Special ASCII Chars /// </summary> /// <param name="recivedMsg"></param> /// <param name="simulationMsg"></param> /// <returns></returns> private bool compareRecivedAndSimMessage(MsgData recivedMsg, string simulationMsg) { // Clocking the Thread till we found what we are Searching for string _myData = Converty.msgDataToSpecialAsciiString(lastMsg.value); // Check if we got an Spacer int the String if (simulationMsg.IndexOf(SPACE_VALUE.ToString()) > -1) { string[] _splittedSimulationMsg = simulationMsg.Split(new Char[] { SPACE_VALUE }); bool dataValid = true; string _myString = _myData; foreach (string simulationMsgPart in _splittedSimulationMsg) { if (!(_myString.IndexOf(simulationMsgPart) > -1)) { // Cut the String that we fount out of the Buffer. So in this case we will check the Abendency in the Messages _myString = _myString.Substring(_myString.IndexOf(simulationMsgPart) + simulationMsgPart.Length); dataValid = false; } } if (dataValid) { return(true); } else { return(false); } } else if (_myData == simulationMsg) { return(true); } else { return(false); } }
/// <summary> /// Disconnect the Serial Port /// </summary> public void disconnect() { // Check if we have to close the Serial Port! if (pcSerialPort != null) { if (pcSerialPort.IsOpen) { pcSerialPort.Close(); // Set the User hint MsgData logMessage = new MsgData(); logMessage.value = Encoding.ASCII.GetBytes("Verbindung: " + pcSerialPort.PortName + " Erfolgreich abgebaut"); logMessage.type = MsgData.messageType.infoNegative; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } } }
/// <summary> /// By sending a new Message this function is called /// And we check if the entered Msg is already Stored in the List then remove it and add it to the First Place /// </summary> /// <param name="sendMessage"></param> public void messageWasSend(MsgData sendMessage) { // Try to find the Send Msg in the History Log sendHistory.Remove(sendMessage); // This is not working! // Create the needed Variables List <int> ListToRemove = new List <int>(); // Finde the Duplicates in the send History for (int i = 0; i <= sendHistory.Count - 1; i++) { MsgData item = sendHistory.ElementAt <MsgData>(i); if (item.value.SequenceEqual(sendMessage.value)) { //Store the Index wie have to remove ListToRemove.Add(i); } } // Remove the found Duplicates from the History List for (int i = 0; i <= ListToRemove.Count - 1; i++) { sendHistory.RemoveAt(ListToRemove.ElementAt <int>(i)); } // Insert the new Message to the First Position of the Insert History sendHistory.Insert(0, sendMessage); // Remove the overlapping Data if (sendHistory.Count > 10) { sendHistory.RemoveAt(sendHistory.Count - 1); } // Init the Current viewed Histoy Message Index sendMsgHistoryCurrentIndex = -1; }
/// <summary> /// Data Recive Handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { MsgData logMessage = new MsgData(); byte[] message = new byte[4096]; int bytesRead; try { // Read the Data bytesRead = pcSerialPort.Read(message, 0, 4096); // Set the Current TimeStamp logMessage.setCurrentTimeStamp(); // Save the Data to the logMessage.value = new byte[bytesRead]; // Create an Array with the Size of readed Data Array.Copy(message, logMessage.value, bytesRead); // Copy the Data to the Array logMessage.type = MsgData.messageType.recived; //Set the Type to Recived Message logMessage.connectionNumber = interfaceNumber; // Set the Interface Reference // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } catch (Exception ex) { // Set an error Message to the UI logMessage.value = Encoding.ASCII.GetBytes("Konnte nicht empfangen werden: " + "\n" + ex); logMessage.type = MsgData.messageType.infoNegative; // Set the Event that the User Changed an Input MsgSendRecivedEventArgs msgLogEventArgs = new MsgSendRecivedEventArgs(); msgLogEventArgs.msgData = logMessage; msgSendRecived(msgLogEventArgs); } }
/// <summary> /// Returns the Data from the Next MSG in the Send History /// </summary> /// <returns></returns> public string getNextSendedMsg() { // Check if the History allready exist if (sendHistory.Count == 0) { return(""); } MsgData sendMsgHistoryItem = new MsgData(); // Decrement the Index of the History List if (sendMsgHistoryCurrentIndex <= 0) { sendMsgHistoryCurrentIndex = sendHistory.Count - 1;// Keep in mind that the list is 0 Based!!! } else { sendMsgHistoryCurrentIndex--; } sendMsgHistoryItem = sendHistory.ElementAt(sendMsgHistoryCurrentIndex); return(getMsgWithCurrentViewSettings(sendMsgHistoryItem)); }
/// <summary> /// Convert the given Msg to the current view Setting as a String /// </summary> /// <returns></returns> public string getMsgWithCurrentViewSettings(MsgData msg) { string returnMsg; // Only change the view to the Sended and Recived Data if (msg.type == MsgData.messageType.recived || msg.type == MsgData.messageType.send) { // Return the Msg with the Current View Configuration switch (viewSettings.dataPresentation) { case 1: returnMsg = Converty.msgDataToHexData(msg); break; case 2: returnMsg = Converty.msgDataToDecData(msg); break; case 3: returnMsg = Converty.msgDataToBinData(msg); break; // Default View String with ASCII Chars default: returnMsg = Converty.msgDataToSpecialAsciiString(msg.value); break; } } else { returnMsg = Converty.msgDataToAsciiChar(msg); } return(returnMsg); }
/// <summary> /// Change the View State /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ChangeViewDown_EventHandler(object sender, RoutedEventArgs e) { // Save the current SendBox Data with the Current View Settings try { currentSendData = msgLog.getRawMsgWithCurrentViewSettings(tbSendData.Text); } catch (Exception err) { currentSendData = msgLog.getRawMsgWithCurrentViewSettings(""); } if (settings.viewSettings.dataPresentation <= 0) { settings.viewSettings.dataPresentation = 3; } else { settings.viewSettings.dataPresentation--; } msgLog.viewSettings = settings.viewSettings; UpdateViewStateDependence(settings.viewSettings); }