/// <summary> /// Liest die vom COM-Port erhaltenden Daten und schreibt sie in eine TextBox. /// </summary> /// <param name="sender"></param> /// <param name="e">Empfangene Daten</param> void GsmTrafficLogger(object sender, SerialDataEventArgs e) { //Quelle: https://stackoverflow.com/questions/4016921/wpf-invoke-a-control int maxTextLength = 1000; // maximum text length in text box string textBoxContent = string.Empty; //für Inhalt der TextBox this.Gsm_TextBox_SerialPortResponse.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { textBoxContent = this.Gsm_TextBox_SerialPortResponse.Text; })); if (textBoxContent.Length > maxTextLength) { textBoxContent = textBoxContent.Remove(0, textBoxContent.Length - maxTextLength); } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); //Gsm_TextBox_SerialPortResponse.Text = text + str; this.Gsm_TextBox_SerialPortResponse.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { this.Gsm_TextBox_SerialPortResponse.Text = textBoxContent + str; })); //Antworten protokollieren using (System.IO.StreamWriter file = System.IO.File.AppendText(TextLogPath)) { file.WriteLine("\r\n" + DateTime.Now.ToShortTimeString() + ":\r\n" + str); } }
void CheckForIncomingSmsIndication(object sender, SerialDataEventArgs e) { Task.Run(() => { string str = Encoding.ASCII.GetString(e.Data); //Empfangshinweis für eingehende Nachricht ? if (str.Contains("+CMTI:")) { string smsIdStr = System.Text.RegularExpressions.Regex.Match(str, @"\d+").Value; if (int.TryParse(smsIdStr, out int smsId)) { GsmCommandQueue.Add("AT+CMGF=1"); GsmCommandQueue.Add("AT+CPMS=\"MT\""); SpManager.NewSerialDataRecieved += ReadIncomingMessagePart1; GsmCommandQueue.Add("AT+CMGR=" + smsId); } else { Log(Topic.SMS, Prio.Fehler, 2003221714, "Die ID der eingegangenen SMS konnte nicht ausgelesen werden aus >" + str + "< "); } } }); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } // This application is connected to a GPS sending ASCCI characters, so data is converted to text strData = null; strData = Encoding.ASCII.GetString(e.Data); if (strData == "=") { _Weight = null; _Weight = ""; } if (strData != "B" && strData != "C" && strData != "=") { _Weight = _Weight + strData; } if (strData == "B" || strData == "C") { txtWeight.Text = _Weight.Trim(); } }
/// <summary> /// Event Handler que permite recibir los datos reportados por el SerialPortManager para su utilizacion /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void spManager_NewSerialDataRecievedRFID(object sender, SerialDataEventArgs e) { try { string strEnd = spManagerRFID.ObtenerLeturaRFID(e.Data); if (strEnd.Trim() == string.Empty) { return; } rfidCapturadoGlobal = strEnd; //Aquie es para que se este reflejando la lectura en el display Dispatcher.BeginInvoke(new Action(CapturarAreteRFID), DispatcherPriority.Background); } catch (FormatException ex) { Logger.Error(ex); SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal], Properties.Resources.CorteGanado_ErrorCapturaRFID, MessageBoxButton.OK, MessageImage.Error); } catch (Exception ex) { Logger.Error(ex); SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal], Properties.Resources.CorteGanado_ErrorCapturaRFID, MessageBoxButton.OK, MessageImage.Error); } }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } sb.Clear(); //StringBuilder sb = new StringBuilder(); // Now declared fo full scope for (int i = 0; i < e.Data.Length; i++) { sb.AppendFormat("{0:X2} \n", e.Data[i]); } badData.AppendText(sb.ToString()); response = CheckResponse(e.Data); if (response) { decodeModbus(sb); } else // CRC check has failed then do this { badData.AppendText("Error Detected \n"); } }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } something_new = true; int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) { tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); byte[] ascii = Encoding.ASCII.GetBytes(str); foreach (byte b in ascii) { j.Add(b); tbData.AppendText((char)(b) + " "); } }
private void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { Thread.Sleep(100); if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } //int maxTextLength = 1000; // maximum text length in text box //if (tbData.TextLength > maxTextLength) // tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); //string str = Encoding.ASCII.GetString(e.Data); //DisplayWeight(str); for (int i = 0; i < e.Data.Length; i++) { char kk = (char)e.Data[i]; if (kk == 2) { //Found Start sumText = ""; } else if (kk == 3) { //Found Stop DisplayWeight(sumText); } else { sumText += kk.ToString(); } } }
/// <summary> /// Event Handler que permite recibir los datos reportados por el SerialPortManager para su utilizacion /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void SpManagerNewSerialDataRecieved(object sender, SerialDataEventArgs e) { try { string str = Encoding.ASCII.GetString(e.Data); if (!string.IsNullOrWhiteSpace(str)) { var valores = str.Split(','); //Se agrega validacion, ya que recibe 2 llamada de datos, una con los datos de la humedad, y otro con datos de control if (valores.Count() > 7) { var humedad = valores[3]; //Aquie es para que se este reflejando la humedad del Dickey John Dispatcher.BeginInvoke(new Action(() => { dudHumedad.Value = Convert.ToDecimal(humedad); dudHumedad.IsEnabled = false; }), null); } } } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Event Handler que permite recibir los datos reportados por el SerialPortManager para su utilizacion /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { string strEnd = "", peso = ""; double val; try { strEnd = spManager.ObtenerLetura(e.Data); if (strEnd.Trim() != "") { val = double.Parse(strEnd.Replace(',', '.'), CultureInfo.InvariantCulture); // damos formato al valor peso para presentarlo peso = String.Format(CultureInfo.CurrentCulture, "{0:0}", val).Replace(",", "."); //Aquie es para que se este reflejando la bascula en el display Dispatcher.BeginInvoke(new Action(() => { txtDisplay.Text = peso.ToString(CultureInfo.InvariantCulture); }), null); } } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Triggerato quando ci sono nuovi dati da leggere. La variabile pesata viene concatenata fino a quando ci sono dati sulla seriale da leggere. /// </summary> /// <param name="e">Oggetto che contiene i dati</param> private void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { string data = Encoding.ASCII.GetString(e.Data); _pesata += data; //int dataInCoda = _spManager.SerialPort.BytesToRead; }
void ReadIncomingMessagePart1(object sender, SerialDataEventArgs e) { string str = Encoding.ASCII.GetString(e.Data); //Empfange Nachricht ? if (str.Contains("+CMGR:")) { //+CMGR: "REC READ","+4915142265412",,"20/03/30,13:44:56+08"\r\n string[] smsHeader = str.Remove(0, 7).Replace("\"", string.Empty).Replace("\r\n", string.Empty).Split(','); Contact contact = Sql.GetContactFromDb(0, "", "", smsHeader[1], ""); DateTime recDate = DateTime.ParseExact(smsHeader[3], "yy/MM/dd", CultureInfo.InvariantCulture); TimeSpan recDateTime = TimeSpan.Parse(smsHeader[4].Substring(0, 7)); IncomingMessage = new Message() { From = contact, RecieveTime = recDate.Add(recDateTime), Status = MessageType.RecievedFromSms }; WaitForSmsContent = true; return; } if (WaitForSmsContent) { MessageBox.Show(str); //Nachrichteninhalt? if (!str.StartsWith("AT+") && !str.StartsWith("+") && !str.StartsWith("\r\nOK")) //&& str.Contains("\r\n\r\n") { string messageContent = str.Replace("\r", string.Empty).Replace("\n", string.Empty); if (messageContent.EndsWith("OK")) { messageContent = messageContent.Substring(0, messageContent.Length - 3); } IncomingMessage.Content = messageContent; if (str.EndsWith("OK\r\n")) { Sql.CreateMessageEntry(IncomingMessage); //TODO: Nachricht weiterleiten MessageBox.Show("SMS Empfangen"); IncomingMessage = null; WaitForSmsContent = false; SpManager.NewSerialDataRecieved -= ReadIncomingMessagePart1; } } } }
private void OnSerialDataIncoming(object sender, SerialDataEventArgs e) { var receivedString = e.ReceivedStrChunk; if (receivedString.Length == _parameterStore.ChunkSize) { if (_measChunkCreator.IsValidStrChunk(receivedString)) { var measChunk = _measChunkCreator.CreateMeasChunk(receivedString, DateTime.Now); MeasReceivedEvent?.Invoke(this, new MeasChunkEventArgs(measChunk)); } } }
private void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } string str = Encoding.UTF8.GetString(e.Data); BarcodeParseOperation(str); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } //This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); if (str.Contains("\n")) { if (strReadFromCOM.Contains("\r") && strReadFromCOM != "") { //string[] multiMessage = strReadFromCOM.Split('!'); //if (multiMessage.Length > 2 && multiMessage.Last().Contains("AI")) //{ // foreach (string msg in multiMessage) // { // string tmp = "!"; // if (msg == "") // continue; // tmp += msg; // //Shows the lines generated and should display the same as the NemaFileReader Program // Debug.Print(tmp); // AISDataCollectionClass.ParseToTextFromCOM(tmp); // } //} //else //{ //Shows the lines generated and should display the same as the NemaFileReader Program Debug.Print(strReadFromCOM); AISDataCollectionClass.ParseToTextFromCOM(strReadFromCOM); //} UpdateTable(AISDataCollectionClass.CleanAndSortAISDataList()); strReadFromCOM = ""; } } else { strReadFromCOM += str; } }
void OnNewSerialDataReceived(object sender, SerialDataEventArgs e) { Statistics.ReceivedPackets++; try { ParseData(e.Data); } catch (Exception) { Debug.WriteLine("Corrupt packet: dropped + (" + (e.Data) + ")"); Statistics.CorruptPackets++; } }
void spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (readings.TextLength > maxTextLength) { readings.Text = readings.Text.Remove(0, readings.TextLength - maxTextLength); } string str = Encoding.ASCII.GetString(e.Data); try { interpreter.ParseInput(str); } catch (Exception ex) { sw3.WriteLine("Exception Message: " + ex.Message); sw3.WriteLine("Exception Source: " + ex.Source); sw3.WriteLine("Exception InnerException: " + ex.InnerException); sw3.WriteLine("Exception TargetSite: " + ex.TargetSite); sw3.WriteLine("#######################################"); } if (sensorReading != interpreter.CurrentReading) { sensorReading = interpreter.CurrentReading; UpdateManometers(); readings.AppendText("\r\n" + str); readings.ScrollToCaret(); string s = string.Format("TEMP:{0} | HUM:{1} | CO:{2} | CO2:{3}", sensorReading.Temperature, sensorReading.Humidity, sensorReading.COLevel, sensorReading.CO2Level); formattedReadings.AppendText("\r\n" + s); formattedReadings.ScrollToCaret(); sw2.WriteLine(s); } sw1.WriteLine(str); }
void spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler<SerialDataEventArgs>(spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (readings.TextLength > maxTextLength) readings.Text = readings.Text.Remove(0, readings.TextLength - maxTextLength); string str = Encoding.ASCII.GetString(e.Data); try { interpreter.ParseInput(str); } catch (Exception ex) { sw3.WriteLine("Exception Message: " + ex.Message); sw3.WriteLine("Exception Source: " + ex.Source); sw3.WriteLine("Exception InnerException: " + ex.InnerException); sw3.WriteLine("Exception TargetSite: " + ex.TargetSite); sw3.WriteLine("#######################################"); } if (sensorReading != interpreter.CurrentReading) { sensorReading = interpreter.CurrentReading; UpdateManometers(); readings.AppendText("\r\n" + str); readings.ScrollToCaret(); string s = string.Format("TEMP:{0} | HUM:{1} | CO:{2} | CO2:{3}", sensorReading.Temperature, sensorReading.Humidity, sensorReading.COLevel, sensorReading.CO2Level); formattedReadings.AppendText("\r\n" + s); formattedReadings.ScrollToCaret(); sw2.WriteLine(s); } sw1.WriteLine(str); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); // MessageBox.Show(str); GrossWeightTextEdit.Text = String.Format("{0:0.000}", Convert.ToDouble(str)); GrossWeightTextEdit.ScrollToCaret(); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); tbData.AppendText(str); tbData.ScrollToCaret(); }
// public for unit testing public void OnSerialData(object sender, SerialDataEventArgs e) { var AxisOffset = 0; var SliderOffset = AxisOffset + mLastData.Axis.Length; var ButtonOffset = SliderOffset + mLastData.Slider.Length; var POVOffset = ButtonOffset + mLastData.Button.Length; var DialOffset = POVOffset + mLastData.POV.Length; lock (mLock) { var data = e.Data.Split(new[] { ArduinoReceiver.RS, ArduinoReceiver.ETX }, StringSplitOptions.RemoveEmptyEntries); // crack data and convert to input // Axis x6 for (var i = 0; i < mLastData.Axis.Length; i++) { mLastData.Axis[i] = short.Parse(data[AxisOffset + i]); } // Slider x6 for (var i = 0; i < mLastData.Slider.Length; i++) { mLastData.Slider[i] = short.Parse(data[SliderOffset + i]); } // Button x32 for (var i = 0; i < mLastData.Button.Length; i++) { mLastData.Button[i] = ToByte(int.Parse(data[ButtonOffset + i])); } // POV x2 for (var i = 0; i < mLastData.POV.Length; i++) { mLastData.POV[i] = ToByte(int.Parse(data[POVOffset + i])); } // Dial x8 for (var i = 0; i < mLastData.Dial.Length; i++) { mLastData.Dial[i] = ToByte(int.Parse(data[DialOffset + i])); } } }
/* * Input plot new data recieved event handling function. Update of 'PlotInput' chart. * @param sender - contains a reference to the control/object * @param e - contains the serial port event data */ void _spManager_NewPlotDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewPlotDataRecieved), new object[] { sender, e }); return; } // Byte array to string string hex = Encoding.ASCII.GetString(e.Data); _outValue_Str += hex; // if buffer holds at least one message if (_outValue_Str.Length >= _spMsgSize) { try { // parse first message as hex value UInt16 reg = UInt16.Parse(_outValue_Str.Substring(0, _spMsgSize), NumberStyles.HexNumber); _outValue_Str = _outValue_Str.Remove(0, _spMsgSize); outValue = reg; if (_plotTime > _plotTimeMax) { chart1.Series[0].Points.RemoveAt(1); chart1.ChartAreas[0].AxisX.Minimum = _plotTime - _plotTimeMax; chart1.ChartAreas[0].AxisX.Maximum = _plotTime; } chart1.Series[0].Points.AddXY(_plotTime, outValue); if (saving_to_file) { _saveDataToCsvFile(_plotTime, set_val, outValue, max_val, min_val, path_to_csv_file, file_name); } _plotTime += _plotTimeStep; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (sendbuffer.Length > 0) { _spManager.SerialSend(sendbuffer); sendbuffer = ""; } if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); parse_data(str); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) { tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); } string readData = Encoding.ASCII.GetString(e.Data); tbData.AppendText("Read on " + inPortNameComboBox.Text + " : " + readData + "\r\n"); tbData.AppendText(_spManager.Check(readData) + "\r\n"); tbData.ScrollToCaret(); }
void GetOutgoingSmsStatus(object sender, SerialDataEventArgs e) { string str = Encoding.ASCII.GetString(e.Data); //Sendebestätigung für ausgegangene Nachricht ? if (str.Contains("+CMGS:")) { if (str.EndsWith("\r\nOK\r\n")) { MainWindow.OutMsgsSinceStartup++; } else { Log(Topic.SMS, Prio.Fehler, 2003221729, "Eine SMS konnte nicht versendet werden: " + str); } SpManager.NewSerialDataRecieved -= GetOutgoingSmsStatus; } }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) { tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); } Console.WriteLine(e.Data.Length.ToString()); if (e.Data.Length != 29) { return; } int pan_e = _HexToInt(e.Data[2], e.Data[3], e.Data[4]); int tilt_e = _HexToInt(e.Data[5], e.Data[6], e.Data[7]); int zoom = _HexToInt(e.Data[20], e.Data[21], e.Data[22]); int focus = _HexToInt(e.Data[23], e.Data[24], e.Data[25]); float pan = (float)pan_e / 32768; float tilt = (float)tilt_e / 32768; float zoom_min = 524352; float zoom_max = 598444; float focus_min = 524447; float focus_max = 646137; float zoom_per = (zoom - zoom_min) / (zoom_max - zoom_min); float focus_per = (focus - focus_min) / (focus_max - focus_min); tbData.Text = "pan =" + pan + "\n " + "tilt=" + tilt; UpdateUI(tb_pan, dou2str(pan, "F", 2)); UpdateUI(tb_tilt, dou2str(tilt, "F", 2)); UpdateUI(tb_zoom, zoom.ToString() + "(" + dou2str(zoom_per * 100, "F", 1) + "%)"); UpdateUI(tb_focus, focus.ToString() + "(" + dou2str(focus_per * 100, "F", 1) + "%)"); // tbData.ScrollToCaret(); }
internal static void CheckForOutgoingSmsIndication(object sender, SerialDataEventArgs e) { var t = Task.Run(() => { string str = Encoding.ASCII.GetString(e.Data); //Sendehinweis für ausgegangene Nachricht ? if (str.Contains("+CMGS:") && str.Contains("\r\nOK\r\n")) { MessageBox.Show("200411 1327 Rükmeldung SMS versendet."); BlockSmsSending = false; } else if (str.Contains("+CMGS:") && str.Contains("ERROR")) { MainWindow.Log(Topic.SMS, Prio.Fehler, 2004131211, "Fehler beim Senden einer SMS: " + str); BlockSmsSending = false; } }); }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } /* * int maxTextLength = 1000; // maximum text length in text box * if (tbData.TextLength > maxTextLength) * tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); * * // This application is connected to a GPS sending ASCCI characters, so data is converted to text * string str = Encoding.ASCII.GetString(e.Data); * tbData.AppendText(str); * tbData.ScrollToCaret(); */ }
/// <summary> /// Liest die vom COM-Port erhaltenden Daten und schreibt sie in eine TextBox. /// </summary> /// <param name="sender"></param> /// <param name="e">Empfangene Daten</param> void GsmTrafficLogger(object sender, SerialDataEventArgs e) { //Quelle: https://stackoverflow.com/questions/4016921/wpf-invoke-a-control int maxTextLength = 1000; // maximum text length in text box string textBoxContent = string.Empty; //für Inhalt der TextBox var t = Task.Run(() => { this.Gsm_TextBox_SerialPortResponse.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { textBoxContent = this.Gsm_TextBox_SerialPortResponse.Text; })); textBoxContent = textBoxContent.Replace("\r\n\r\n", "\r\n").Replace("\r\r", "\r"); if (textBoxContent.Length > maxTextLength) { textBoxContent = textBoxContent.Remove(0, textBoxContent.Length - maxTextLength); } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); if (str.Contains("ERROR")) { Log(Topic.SMS, Prio.Fehler, 2003272054, "Fehler Antwort GSM-Modem: " + str.Replace("\r\n", " ")); } this.Gsm_TextBox_SerialPortResponse.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { this.Gsm_TextBox_SerialPortResponse.Text = textBoxContent + str; })); //Antworten protokollieren //string dir = System.IO.Path.GetDirectoryName(TextLogPath); //if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir); //using (System.IO.StreamWriter file = System.IO.File.AppendText(TextLogPath)) //{ // file.WriteLine("\r\n" + DateTime.Now.ToShortTimeString() + ":\r\n" + str); //} }); t.Wait(2000); }
void CheckForIncomingSms(object sender, SerialDataEventArgs e) { string str = Encoding.ASCII.GetString(e.Data); //Empfangshinweis für eingehende Nachricht ? if (str.Contains("+CMTI:")) { string smsIdStr = System.Text.RegularExpressions.Regex.Match(str, @"\d+").Value; if (int.TryParse(smsIdStr, out int smsId)) { PortComandExe("AT+CMGR=" + smsId); MessageBox.Show(smsId.ToString()); //TODO: Eingegangene SMS in Datenbank schreiben } else { Log(Topic.SMS, Prio.Fehler, 2003221714, "Die ID der eingegangenen SMS konnte nicht ausgelesen werden aus >" + str + "< "); } } }
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) { tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); } // This application is connected to a GPS sending ASCCI characters, so data is converted to text string str = Encoding.ASCII.GetString(e.Data); tbData.AppendText(str); tbData.ScrollToCaret(); // 更新电压图 try { string cur = str; //if (cur.Length != 137) return; cur = cur.Substring(8, 126); // 去头去尾 string[] tmp = cur.Split(','); float[] NewVoltage = new float[18]; for (int i = 0; i < 18; i++) { NewVoltage[i] = float.Parse(tmp[i]); } UpdateChart(NewVoltage); } catch (Exception) { } }
/// <summary> /// Ermittelt die momentane Netzqualität für das GSM-Netz und schreibt den Wert in eine ProgressBar /// </summary> /// <param name="sender"></param> /// <param name="e">Antwort aus GSM-Modem</param> private void ShowGsmSignalQuality(object sender, SerialDataEventArgs e) { string portResponse = Encoding.ASCII.GetString(e.Data); //Antwort OK? if (portResponse.Contains("CSQ:")) { try { //Finde Zahlenwerte Regex rS = new Regex(@"CSQ:\s[0-9]+,"); Match m = rS.Match(portResponse); if (!m.Success) { Log(Topic.SMS, Prio.Warnung, 2003230749, "Antwort von GSM-Modem auf Signalqualität konnte nicht verarbeitet werden:\r\n" + portResponse); return; } //Mögliche Werte: 2 - 9 marginal, 10 - 14 OK, 15 - 19 Good, 20 - 30 Excellent, 99 = kein Signal int.TryParse(m.Value.Remove(0, 4).Trim(','), out int signalQuality); this.Gsm_TextBox_SerialPortResponse.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { this.Status_ProgressBar_SignalQuality.Value = signalQuality; })); StatusClass.GsmSignalQuality = signalQuality; //Wenn signalQuality zu gering ist: Nachricht an Admin if (signalQuality < MinRequieredSignalQuality) { Messages.Create_SignalQualityMessage(signalQuality); } } finally { //Ereignisabbonement kündigen. SpManager.NewSerialDataRecieved -= ShowGsmSignalQuality; } } }
/* * New serial port data recived event handlig function. Update of "tbDataReceive" text box. * @param sender - contains a reference to the control/object that raised the event. * @param e - contains the serial port event data. */ void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway. this.BeginInvoke(new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbDataReceive.TextLength > maxTextLength) { tbDataReceive.Text = tbDataReceive.Text.Remove(0, tbDataReceive.TextLength - maxTextLength); } // Byte array to string string str = Encoding.ASCII.GetString(e.Data); tbDataReceive.AppendText(str); tbDataReceive.ScrollToCaret(); }
/// <summary> /// New serial data is received and gets processed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void NewSerialDataRecieved(object sender, SerialDataEventArgs e) { //Reset Timer for disconnect dcTime = DateTime.Now; foreach (byte t in e.Data) { //Import Byte and convert if one package complete if (processData.ImportByte(t)) { processData.Convert2Byte(); //Reset all Values if its the very first package that arrives if (firstPackage) { firstPackage = false; processData.SetPackageNumber(); stopWatch.Reset(); processData.packageCount=0; } //Check package number else { if (!processData.CheckPackageNumber()) UpdateStatus(this, new UpdateStatusEvent("Paket verloren gegangen")); if (!processData.CheckPackageNumber() && save) { saveData.FillMissingData(processData.lostPackages); processData.packageCount += processData.lostPackages; } } //Start Stop Watch the first time if (!stopWatch.IsRunning){stopWatch.Reset();stopWatch.Start();} //Count till 2500 Packages have arrive (which should be 10 Seconds) processData.packageCount++; if (processData.packageCount >= 250*10) { processData.packageCount -= 250*10; stopWatch.Stop(); //Add time deviation to ensure time synchronic if(save) saveData.AddLostTime(stopWatch,10); //Reset and Start Stop Watch again stopWatch.Reset(); stopWatch.Start(); } //IMU processData.CalculateIMU(); //FFT if (processData.Buffering()) { // Send data to Form if (NewDataAvailable != null) { //snore //if (processData.snore) UpdateStatus(this, new UpdateStatusEvent("Schnarch")); NewDataAvailable(this, new NewDataAvailableEvent(processData.audioArray, processData.fft, processData.activity, processData.sleepPosition, processData.snore)); //if (snorecounter > 20) //{ // UpdateStatus(this, // new UpdateStatusEvent(Convert.ToString(processData.volume) + ' ' + // Convert.ToString(processData.length) + ' ' + // Convert.ToString(processData.freq))); // snorecounter = 0; //} //snorecounter++; } } //Save Data if (save) { if (Statics.complexSave) { for (int i = 0; i < 3; i++) { saveData.sendData(i + 3, processData.gyro[i]); saveData.sendData(i + 6, processData.accelerationRaw[i]); } } saveData.sendData(1, (short)processData.activity); saveData.sendData(2, (short)processData.sleepPosition); saveData.sendData(0, processData.audio); } } } }