public Ser_Port_Listener(Form1 frmBattMon, string strIn_SerPortName) // serial port handling class ctor { Debug.WriteLine("++Ser_Port_Listener(" + strIn_SerPortName + ") ctor"); bSerPortOkay = false; _portName = strIn_SerPortName; m_liErrCnt = 0; m_dataparser = new batt_data_parser(); // copy supplied argument (form pointer) to local variable m_frmBattMon = frmBattMon; // construct new instance of 1 serial port try { m_serptMcSerPort = new SerialPort(strIn_SerPortName, m_baudRate, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); bSerPortOkay = true; Debug.WriteLine("Ser_Port_Listener() ctor Created serial port " + _portName + "," + m_baudRate.ToString() + "," + System.IO.Ports.Parity.None.ToString() + ",8," + System.IO.Ports.StopBits.One.ToString()); // find out ser port read buffer size (comes from device driver through .net framework) iSerPortreadBuffSize = m_serptMcSerPort.ReadBufferSize; // 4 kb or so Debug.WriteLine("Ser_Port_Listener() ctor SerPort Buf size=" + iSerPortreadBuffSize.ToString()); // Initialize a buffer to hold the received data buffer = new byte[iSerPortreadBuffSize]; // configure flow control for serial connection between PC and microcontroller if (m_serptMcSerPort.Handshake == Handshake.None) { // to moderate data flow control from microcontroller, use one of flow control ways // software flow control - XonXoff // Debug.WriteLine("Ser_Port_Listener() ctor SerPort flow control=None, setting to XonXoff"); // m_serptMcSerPort.Handshake=Handshake.XOnXOff; // hardware flow control - CTS/RTS or DTR/DTD // m_serptMcSerPort.Handshake=Handshake.RequestToSend; // Debug.WriteLine("Ser_Port_Listener() ctor SerPort flow control="+m_serptMcSerPort.Handshake.ToString()); } ; } catch (IOException ioex) { bSerPortOkay = false; // before showing message box to user, also swicth state from started to stopped // frmBattMon.bOnStopMonitoring(true); // now show message box to user - it is modal dialog which will stay MessageBox.Show("Unable to open COM port!\r\nI\\O Error", "No MC connection", MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.WriteLine("Ser_Port_Listener ctor(): Unable to open COM port!" + ioex.ToString() + " Check settings..."); }; try { // create batt mon log file name using ser port name and current date-time strBatMonLogFileName = strIn_SerPortName + "_batt_mon_" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + ".log"; // open battery logging file m_OutLogfile = new System.IO.StreamWriter(strBatMonLogFileName, true); m_bLoggingToFile = true; } catch (IOException ioex) { Debug.WriteLine("Ser_Port_Listener() ctor: Error " + ioex.ToString() + "! Cannot open log file"); m_OutLogfile = null; m_bLoggingToFile = false; }; if (false == bSerPortOkay) { Debug.WriteLine("Ser_Port_Listener(ERR) ctor failed to open serial port"); } ; Debug.WriteLine("--Ser_Port_Listener() ctor"); }
// private void FromFileRadioButton1_CheckedChanged(object sender, EventArgs e) { Debug.WriteLine("++Form1::OnFromFileRadioButton1()"); int iFromRecordedFuelGaugeLvl = -1; int iFuelGaugeLvl_D = -1; int iFuelGaugeLvl_NL = -1; int iFuelGaugeLvl_C = -1; // if selected if (true == FromFileRadioButton1.Checked) { if (true == bIsRunning) { // stop if running bOnStopMonitoring(true); // disable start button } ; StartStopButton.Enabled = false; SerPortNameTextBox.Enabled = false; this.Text = "Battery Monitor - Recorded data; file "; // clear chart // CurrentVoltageChart.Series.Clear(); // clear data stored in voltage and current series CurrentVoltageChart.Series[0].Points.Clear(); CurrentVoltageChart.Series[1].Points.Clear(); // then restore zoom window view of X axis // load data from file into chart StreamReader strmReader = null; OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (strPreviousOpenedFileDir.Length != 0) { openFileDialog1.InitialDirectory = strPreviousOpenedFileDir; // path as in "c:\\" ; openFileDialog1.RestoreDirectory = true; } ; // open CFile dialog and navigate to batt_mon log file on PC openFileDialog1.Filter = "Batt mon log files (*.log)|*.log|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; // OR read from SD card from arduino microcontroller if (openFileDialog1.ShowDialog() == DialogResult.OK) { Debug.WriteLine("Form1::OnFromFileRadioButton1() CFile dialog : file selected=" + openFileDialog1.FileName.ToString()); try { strmReader = new StreamReader(openFileDialog1.FileName); if (null != strmReader) { batt_data_parser prsDataparser = new batt_data_parser(); Debug.WriteLine("Form1::OnFromFileRadioButton1() Opened file " + openFileDialog1.FileName.ToString() + " ok."); this.Text += openFileDialog1.SafeFileName; // save folder name of successfully opened file strPreviousOpenedFileDir = System.IO.Path.GetDirectoryName(openFileDialog1.FileName); using (strmReader) { // store the current battery information for later comparison int iCurrNumOfDischChrgCycles = m_batBattery.iGetNumStartingCycles(); String strOneDatapacketFromFile = null; int iLineCntr = 0; int iErrorCntFromFile = 0; ErrorCountTextBox.Text = " "; // start busy cursor // Cursor.Current = Cursors.WaitCursor; UseWaitCursor = true; // clear out SoC bar indicators iUpdate3ChangePcntBars(0, 0, 0); ChargeProgressBarD.BackColor = Color.Gray; ChargeProgressBarNL.BackColor = Color.Gray; ChargeProgressBarC.BackColor = Color.Gray; // code to read the stream here. while (strmReader.Peek() >= 0) { strOneDatapacketFromFile = strmReader.ReadLine().ToString(); if (strOneDatapacketFromFile.Length > 0) { // Debug.WriteLine("Form1::OnFromFileRadioButton1() Line: ["+iLineCntr.ToString() + "] " +strOneDatapacketFromFile); // parse one data packet into fields if (true == prsDataparser.bParseOneDataLine(strOneDatapacketFromFile)) { // if fields are okay, then feed chart series with it m_stRecentBattData = prsDataparser.stbtGetParsedData(); bAddBattDataToChart(m_stRecentBattData); // be sure we process starter mtr load case if there is one m_batBattery.bValuateBatteryData(m_stRecentBattData, iLineCntr); // and then update text fields for R and CA accordingly iLineCntr += 1; if (iLineCntr % 100 == 0) { Debug.WriteLine("Form1::OnFromFileRadioButton1() Added " + iLineCntr.ToString() + " Data packets"); // Debug.WriteLine("Form1::OnFromFileRadioButton1() Batt average current="+m_batBattery.getLastAveCurrent().ToString("+0.0;-0.0;0")+" A"); } ; // update counts live on the form m_slMeasIterCnt += 1; IterCntTextBox.Text = m_slMeasIterCnt.ToString(); // determine SoC level and battery state iFromRecordedFuelGaugeLvl = iGetBattLifePrc(); // update SoC bar indicators accordingly switch (m_stRecentBattData.chBattState) { case 'D': if (-1 != iFromRecordedFuelGaugeLvl) { iFuelGaugeLvl_D = iFromRecordedFuelGaugeLvl; } break; case 'I': if (-1 != iFromRecordedFuelGaugeLvl) { iFuelGaugeLvl_NL = iFromRecordedFuelGaugeLvl; } break; case 'C': if (-1 != iFromRecordedFuelGaugeLvl) { iFuelGaugeLvl_C = iFromRecordedFuelGaugeLvl; } break; default: Debug.WriteLine("Form1::OnFromFileRadioButton1() Chrg% error! Unknown battery state " + m_stRecentBattData.chBattState); break; } ; if (iLineCntr % 10 == 0) { iUpdate3ChangePcntBars(iFuelGaugeLvl_C, iFuelGaugeLvl_NL, iFuelGaugeLvl_D); System.Threading.Thread.Sleep(10); } ; } else { // data bad, ignore iErrorCntFromFile += 1; Debug.WriteLine("Form1::OnFromFileRadioButton1() Failed to parse Line: [" + iLineCntr.ToString() + "] " + strOneDatapacketFromFile); ErrorCountTextBox.Text = iErrorCntFromFile.ToString(); // count errors }; } ; // end IF of if(strOneDatapacketFromFile.Length // Release build only // add some responsiveness Application.DoEvents(); } ; // end of while(strmReader.Peek()) // end busy cursor // Cursor.Current = Cursors.Default; UseWaitCursor = false; // we finished adding data from file. We may get new discharge-charge cycles added, so Debug.WriteLine("Form1::OnFromFileRadioButton1() Finished reading batery data from " + openFileDialog1.FileName.ToString()); Debug.WriteLine("Form1::OnFromFileRadioButton1() Processed " + iLineCntr.ToString() + " lines of data."); Debug.WriteLine("Form1::OnFromFileRadioButton1() Found " + iErrorCntFromFile.ToString() + " errors."); string strTemp = null; strTemp = "Finished reading batery data from " + openFileDialog1.FileName.ToString() + "\r\n"; strTemp += "Processed " + iLineCntr.ToString() + " lines of data.\r\n"; strTemp += "Found " + iErrorCntFromFile.ToString() + " errors.\r\n"; int iNumOfNewDchrgChrgCyles = m_batBattery.iGetNumStartingCycles() - iCurrNumOfDischChrgCycles; // tell user what kind of information was added to our battery class instance if (iNumOfNewDchrgChrgCyles > 0) { Debug.WriteLine("Form1::OnFromFileRadioButton1() Added " + iNumOfNewDchrgChrgCyles.ToString() + " new discharge-charge cycles."); strTemp += "Added " + iNumOfNewDchrgChrgCyles.ToString() + " new discharge-charge cycles."; } else { Debug.WriteLine("Form1::OnFromFileRadioButton1() Did not find any new discharge-charge cycles."); strTemp += " Did not find any new discharge-charge cycles."; }; MessageBox.Show(strTemp); // update listbox from discharge-charge cycles array bUpdateListBoxAndCntFromMmapDschrgChrgCycles(); // once all data are added, resize X axis zoom and scale bResizeXAxisAndZoom(CurrentVoltageChart, CurrentVoltageChart.Series[0]); // and also update R and CA if there was any starting cycle detected if (true == m_batBattery.bWasEngineStarted()) { R_Ohm_TextBox1.Text = "<=" + m_batBattery.dblGetBattInternalResistance().ToString("0.000"); CA_textBox2.Text = ">=" + m_batBattery.dblGetBattCA().ToString("#") + " A"; // at " + stcBattDatStarterOff.dblBattTemp.ToString("+#;-#;0")+ "°C"; } ; // Debug.WriteLine("Form1::OnFromFileRadioButton1() Batt Current ave="+m_batBattery.getLastAveCurrent().ToString("+#.#;-#.#;0")); }; // end of using(strmReader) } else { Debug.WriteLine("Form1::OnFromFileRadioButton1() FAILED to open file " + openFileDialog1.FileName.ToString() + " !"); }; } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); }; } else { Debug.WriteLine("Form1::OnFromFileRadioButton1() CFile dialog CANCELLed"); }; } ; Debug.WriteLine("--Form1::OnFromFileRadioButton1()"); } // end of FromFileRadioButton1_CheckedChanged()
// serial port handling class ctor public Ser_Port_Listener(Form1 frmBattMon, string strIn_SerPortName) { Debug.WriteLine("++Ser_Port_Listener("+strIn_SerPortName+") ctor"); bSerPortOkay = false; _portName=strIn_SerPortName; m_liErrCnt=0; m_dataparser=new batt_data_parser(); // copy supplied argument (form pointer) to local variable m_frmBattMon=frmBattMon; // construct new instance of 1 serial port try { m_serptMcSerPort = new SerialPort(strIn_SerPortName, m_baudRate,System.IO.Ports.Parity.None,8, System.IO.Ports.StopBits.One); bSerPortOkay=true; Debug.WriteLine("Ser_Port_Listener() ctor Created serial port "+_portName+","+m_baudRate.ToString()+","+System.IO.Ports.Parity.None.ToString()+",8,"+System.IO.Ports.StopBits.One.ToString()); // find out ser port read buffer size (comes from device driver through .net framework) iSerPortreadBuffSize = m_serptMcSerPort.ReadBufferSize; // 4 kb or so Debug.WriteLine("Ser_Port_Listener() ctor SerPort Buf size="+iSerPortreadBuffSize.ToString()); // Initialize a buffer to hold the received data buffer = new byte[iSerPortreadBuffSize]; // configure flow control for serial connection between PC and microcontroller if(m_serptMcSerPort.Handshake==Handshake.None) { // to moderate data flow control from microcontroller, use one of flow control ways // software flow control - XonXoff // Debug.WriteLine("Ser_Port_Listener() ctor SerPort flow control=None, setting to XonXoff"); // m_serptMcSerPort.Handshake=Handshake.XOnXOff; // hardware flow control - CTS/RTS or DTR/DTD // m_serptMcSerPort.Handshake=Handshake.RequestToSend; // Debug.WriteLine("Ser_Port_Listener() ctor SerPort flow control="+m_serptMcSerPort.Handshake.ToString()); }; } catch(IOException ioex) { bSerPortOkay=false; // before showing message box to user, also swicth state from started to stopped // frmBattMon.bOnStopMonitoring(true); // now show message box to user - it is modal dialog which will stay MessageBox.Show("Unable to open COM port!\r\nI\\O Error", "No MC connection", MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.WriteLine("Ser_Port_Listener ctor(): Unable to open COM port!"+ioex.ToString()+" Check settings..."); }; try { // create batt mon log file name using ser port name and current date-time strBatMonLogFileName=strIn_SerPortName + "_batt_mon_" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + ".log"; // open battery logging file m_OutLogfile=new System.IO.StreamWriter(strBatMonLogFileName, true); m_bLoggingToFile=true; } catch(IOException ioex) { Debug.WriteLine("Ser_Port_Listener() ctor: Error "+ ioex.ToString() +"! Cannot open log file"); m_OutLogfile=null; m_bLoggingToFile=false; }; if(false == bSerPortOkay) { Debug.WriteLine("Ser_Port_Listener(ERR) ctor failed to open serial port"); }; Debug.WriteLine("--Ser_Port_Listener() ctor"); }