using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; using Microsoft.WindowsAPICodePack.Dialogs; using System.Threading; //using Microsoft.Office.Interop.Excel; namespace APL_TestCheck { public partial class Main : Form { public string Serial_Name { get => serialPort.PortName; set => serialPort.PortName = value; } public Main() { InitializeComponent(); } private void panel_PanelMode_MouseLeave(object sender, EventArgs e) { System.Windows.Forms.Panel Panel = (System.Windows.Forms.Panel)sender; Panel.BackColor = Color.FromArgb(0, 159, 200); label_GPSTest_MouseLeave(null, null); } private void panel_PanelMode_MouseMove(object sender, MouseEventArgs e) { System.Windows.Forms.Panel Panel = (System.Windows.Forms.Panel)sender; Panel.BackColor = Color.FromArgb(0, 159, 255); } private void label_GPSTest_MouseLeave(object sender, EventArgs e) { if (panel_GpsTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_Catm1Test.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SensorTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_MergeMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SnCheckMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } } private void label_Catm1Test_MouseLeave(object sender, EventArgs e) { if (panel_GpsTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_Catm1Test.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SensorTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_MergeMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SnCheckMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } } private void label_SensorTest_MouseLeave(object sender, EventArgs e) { if (panel_GpsTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_Catm1Test.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SensorTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_MergeMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SnCheckMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } } private void label_Merge_MouseLeave(object sender, EventArgs e) { if (panel_GpsTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_Catm1Test.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SensorTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_MergeMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if(panel_SnCheckMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } } private void label_SnCheck_MouseLeave(object sender, EventArgs e) { if (panel_GpsTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_Catm1Test.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SensorTest.Visible == true) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_MergeMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 200); } else if (panel_SnCheckMain.Visible == true) { panel_Merge.BackColor = Color.FromArgb(0, 159, 200); panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 200); panel_SensorMode.BackColor = Color.FromArgb(0, 159, 200); panel_GpsMode.BackColor = Color.FromArgb(0, 159, 200); panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } } private void label_SnCheck_MouseMove(object sender, MouseEventArgs e) { panel_SnCheck.BackColor = Color.FromArgb(0, 159, 255); } private void label_Merge_MouseMove(object sender, MouseEventArgs e) { panel_Merge.BackColor = Color.FromArgb(0, 159, 255); } private void label_Catm1Test_MouseMove(object sender, MouseEventArgs e) { panel_Catm1Mode.BackColor = Color.FromArgb(0, 159, 255); } private void label_SensorTest_MouseMove(object sender, MouseEventArgs e) { panel_SensorMode.BackColor = Color.FromArgb(0, 159, 255); } private void label_GPSTest_MouseMove(object sender, MouseEventArgs e) { panel_GpsMode.BackColor = Color.FromArgb(0, 159, 255); } public struct POINT { public int X, Y; } [DllImport("user32.dll")] // 현재 마우스 위치를 얻기위한 API함수. public extern static void GetCursorPos(out POINT point); System.Drawing.Point FormLocation; // 현재 폼 위치 POINT LastLocation = new POINT(); // 방금 전의 마우스 위치 POINT CurrentLocation = new POINT(); // 현재 마우스 위치 // 폼이 움직일 양 = CurrentLocation - LastLocation. bool IsMouseMoveStart = false; // 현재 마우스 움직이기 기능이 켜져있는가. // 만약 이게 없으면 그냥 폼위에서 private void panel_Main_MouseDown(object sender, MouseEventArgs e) { GetCursorPos(out CurrentLocation); FormLocation = this.Location; IsMouseMoveStart = true; } private void panel_Main_MouseMove(object sender, MouseEventArgs e) { if (!IsMouseMoveStart) return; GetCursorPos(out LastLocation); FormLocation.X -= (CurrentLocation.X - LastLocation.X); FormLocation.Y -= (CurrentLocation.Y - LastLocation.Y); this.Location = FormLocation; CurrentLocation = LastLocation; } private void panel_Main_MouseUp(object sender, MouseEventArgs e) { IsMouseMoveStart = false; } private void pictureBox_min_red_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void pictureBox_X_red_Click(object sender, EventArgs e) { //Application.Exit(); } private void label_GPSTest_Click(object sender, EventArgs e) { panel_GpsTest.Visible = true; panel_SensorTest.Visible = false; panel_Catm1Test.Visible = false; panel_MergeMain.Visible = false; panel_SnCheckMain.Visible = false; } private void label_Catm1Test_Click(object sender, EventArgs e) { panel_GpsTest.Visible = false; panel_SensorTest.Visible = false; panel_Catm1Test.Visible = true; panel_MergeMain.Visible = false; panel_SnCheckMain.Visible = false; } private void label_SensorTest_Click(object sender, EventArgs e) { panel_GpsTest.Visible = false; panel_SensorTest.Visible = true; panel_Catm1Test.Visible = false; panel_MergeMain.Visible = false; panel_SnCheckMain.Visible = false; } private void Main_Load(object sender, EventArgs e) { Serial_Initialize(ref comboBox_Port); dataGridView_Gps.RowCount = 1; dataGridView_Catm1.RowCount = 1; dataGridView_Sensor.RowCount = 1; panel_GpsTest.Visible = true; panel_SensorTest.Visible = false; panel_Catm1Test.Visible = false; panel_MergeMain.Visible = false; pictureBox_Check1.Visible = false; pictureBox_Check2.Visible = false; pictureBox_Check3.Visible = false; pictureBox_Check4.Visible = false; } public void Serial_Initialize(ref ComboBox cb_port) { this.serialPort = new System.IO.Ports.SerialPort(); this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.sPort_DataReceived); cb_port.BeginUpdate(); foreach (string comport in SerialPort.GetPortNames())//foreach (string comport in SerialPort_TestProgram.GetPortNames()) { cb_port.Items.Add(comport); } cb_port.EndUpdate(); //SerialPort 초기 설정. // serialPort.Encoding = Encoding.GetEncoding("Windows-1252"); cb_port.DataSource = SerialPort.GetPortNames(); try { serialPort.PortName = Serial_Name = cb_port.SelectedItem.ToString(); serialPort.BaudRate = (int)115200; serialPort.DataBits = (int)8; serialPort.Parity = System.IO.Ports.Parity.None; serialPort.StopBits = StopBits.One; } catch { } } private delegate void StringSend(string Text); private delegate void ByteSend(byte[] Text); string startStr ="V"; string endStr = "\n"; public void Serial_DataRecvFunction(object sender, SerialDataReceivedEventArgs e) { int TmpLength = 0; //System.Threading.Thread.Sleep(50); int nLnegth = serialPort.BytesToRead; byte[] btdata = new byte[nLnegth]; serialPort.Read(btdata, 0, nLnegth); string data = Encoding.Default.GetString(btdata); if (checkBox_TerminalStop.Checked == true) return; // string data = serialPort.ReadExisting(); if (panel_SensorTest.Visible == true) { if (data.Contains(startStr)) { data = data.Substring(data.IndexOf(startStr)); if (data.Contains(endStr)) { this.Invoke(new StringSend(Data_Recv_Str), data); } } } else { this.Invoke(new StringSend(Data_Recv_Str), data); } /*try { this.Invoke(new ByteSend(Data_Recv_Str), btdata); } catch { }*/ /**** *메모리 누수 방지용 코드 */ System.GC.Collect(0, GCCollectionMode.Forced); System.GC.WaitForFullGCComplete(); } int offset = 0; byte[] rxBuffer; private void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (offset == 0) { rxBuffer = new byte[4096]; } string rxString = ""; int intRecSize = serialPort.BytesToRead; if (intRecSize != 0) { serialPort.Read(rxBuffer, offset, intRecSize); offset += intRecSize; for (int iTemp = 0; iTemp < offset; iTemp++) { rxString += Convert.ToChar(rxBuffer[iTemp]); } if (rxString.Contains(startStr)) { rxString = rxString.Substring(rxString.IndexOf(startStr)); if (rxString.Contains(endStr)) { this.Invoke(new StringSend(Data_Recv_Str), rxString); //program.dataReceived(rxString, "Receive"); offset = 0; } } } } private void label_Port_MouseClick(object sender, MouseEventArgs e) { } int LineLimit = 500; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam); private const int WM_SETREDRAW = 11; public void Data_Recv_Str(string text) { System.Windows.Forms.RichTextBox tbReceived = null; if (panel_GpsTest.Visible == true) { tbReceived = richTextBox_Gps; } else if (panel_Catm1Test.Visible == true) { tbReceived = richTextBox_catm1; } else if (panel_SensorTest.Visible == true) { tbReceived = richTextBox_Sensor; } int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수 try { try { SendMessage(this.Handle, WM_SETREDRAW, false, 0); } catch (Exception e) { MessageBox.Show(e.StackTrace); } if (tbReceived.Lines.Length > nLimitLines) { LinkedList tempLines = new LinkedList(tbReceived.Lines); while ((tempLines.Count - nLimitLines) > 0) { tempLines.RemoveFirst(); } tbReceived.Lines = tempLines.ToArray(); } try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } if (checkBox_GPGSV.Checked == true && panel_GpsTest.Visible == true) { tbReceived.AppendText(GPS_TestFunc(text)); } else if(panel_SensorTest.Visible == true) { Sensor_TestFunc(text); tbReceived.AppendText(text); } else { tbReceived.AppendText(text); } tbReceived.SelectionStart = tbReceived.Text.Length;//맨 마지막 선택... tbReceived.ScrollToCaret(); } catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } } } public void Data_Recv_Str(byte[] text) { string strtext = Encoding.Default.GetString(text); System.Windows.Forms.RichTextBox tbReceived = null; if (panel_GpsTest.Visible == true) { tbReceived = richTextBox_Gps; } else if (panel_Catm1Test.Visible == true) { tbReceived = richTextBox_catm1; } else if (panel_SensorTest.Visible == true) { tbReceived = richTextBox_Sensor; } int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수 try { try { SendMessage(this.Handle, WM_SETREDRAW, false, 0); } catch (Exception e) { MessageBox.Show(e.StackTrace); } if (tbReceived.Lines.Length > nLimitLines) { LinkedList tempLines = new LinkedList(tbReceived.Lines); while ((tempLines.Count - nLimitLines) > 0) { tempLines.RemoveFirst(); } tbReceived.Lines = tempLines.ToArray(); } try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } if (checkBox_GPGSV.Checked == true && panel_GpsTest.Visible == true) { tbReceived.AppendText(GPS_TestFunc(Encoding.Default.GetString(text))); } else if (panel_SensorTest.Visible == true) { Sensor_TestFunc(strtext); tbReceived.AppendText(strtext); } else { tbReceived.AppendText(strtext); } tbReceived.SelectionStart = tbReceived.Text.Length;//맨 마지막 선택... tbReceived.ScrollToCaret(); } catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } } } public int WordNum(String data, String fixdata) { MatchCollection matches = Regex.Matches(data, fixdata); return matches.Count; } double GPS_TestSnRValue = 0; int Gps_CurrentCount = 0; int TestVal = 0; private string GPS_TestFunc(string data) { int Gps_Count, Sentence, SnrIndex = 3; // string tmpstr = "$GPGSV,2,1,08,10,69,246,47,12,50,082,43,15,12,108,29,20,49,190,45*77\r\n"; // string tmpstr1 = "$GPGSV,2,2,08,24,36,052,37,25,48,159,42,31,17,245,,32,46,312,45*74\r\n"; string[] tmpstr = new String[3]; string splitstr = null, str = data; string[] sp = str.Split(','); int Losscount = 0; int location1, location2, LastLocation, SentenceCount; try { /* if(TestVal == 0) { str = tmpstr; TestVal++; } else { str = tmpstr1; TestVal = 0; } */ location1 = str.IndexOf("$GPGSV"); SentenceCount = WordNum(str, "GPGSV"); GPS_TestSnRValue = 0; Gps_CurrentCount = 0; if (location1 != -1) { for (int ii = 0; ii < SentenceCount; ii++) { SnrIndex = 3; if (ii != 0) str = splitstr; location1 = str.IndexOf("$GPGSV"); str = str.Substring(location1); location2 = str.IndexOf("\r\n"); splitstr = str.Substring(location2 + 2); tmpstr[ii] = str = str.Substring(0, location2 + 2); sp = str.Split(','); if (sp[3].Contains("*")) { sp[3] = sp[3].Substring(0, 2); dataGridView_Gps.Rows[0].Cells[1].Value = sp[3]; return str; } else { Sentence = Convert.ToInt32(sp[2]); Gps_Count = Convert.ToInt32(sp[3]); for (int i = 0; i < 4; i++) { SnrIndex += 4; if (sp[SnrIndex].Contains("*")) { LastLocation = sp[SnrIndex].IndexOf("*") - 2; sp[SnrIndex] = sp[SnrIndex].Substring(0, 2); GPS_TestSnRValue += Convert.ToInt32(sp[SnrIndex]); } else { if (sp[SnrIndex] == "") { sp[SnrIndex] = "0"; Losscount++; } GPS_TestSnRValue += Convert.ToInt32(sp[SnrIndex]); } Gps_CurrentCount++; if (Gps_CurrentCount == Gps_Count) { GPS_TestSnRValue /= (Gps_Count - Losscount); GPS_TestSnRValue = Math.Round(GPS_TestSnRValue, 1); dataGridView_Gps.Rows[0].Cells[1].Value = GPS_TestSnRValue.ToString(); break; } } } } str = null; for (int a = 0; a < SentenceCount; a++) str += tmpstr[a]; return str; } return ""; } catch (Exception e) { /*MessageBox.Show(e.StackTrace); */} return ""; } string SensorData = null; private void Sensor_TestFunc(string data) { string str = data; string[] sp = new string[11]; try { if (data.Contains("\r\n") == false) { return; } else { SensorData += data; str = SensorData; } if (dataGridView_Sensor.Rows[0].Cells[0].Value != null) { //location1 = str.IndexOf("\r\n"); //str = str.Substring(0, location1); sp = str.Split(','); if (sp[0].Contains("V") == false/* || sp.Length != 11*/) { SensorData = null; return; } dataGridView_Sensor.Rows[0].Cells[5].Value = sp[0]; //version dataGridView_Sensor.Rows[0].Cells[2].Value = sp[2]; //,IMEI dataGridView_Sensor.Rows[0].Cells[3].Value = sp[3];//, Phone Number, dataGridView_Sensor.Rows[0].Cells[4].Value = sp[4];//USIM Number dataGridView_Sensor.Rows[0].Cells[6].Value = sp[5];//, Battery Voltage, dataGridView_Sensor.Rows[0].Cells[7].Value = sp[6];// System Voltage, dataGridView_Sensor.Rows[0].Cells[8].Value = sp[7];//Temp, BMA400 값 출력 x, y, z dataGridView_Sensor.Rows[0].Cells[9].Value = sp[8];//Temp, BMA400 값 출력 x, y, z dataGridView_Sensor.Rows[0].Cells[10].Value = sp[9];//Temp, BMA400 값 출력 x, y, z if (sp[10].Contains("\r")) { int loc = sp[10].IndexOf("\r"); sp[10] = sp[10].Substring(0, loc); } dataGridView_Sensor.Rows[0].Cells[11].Value = sp[10];//Temp, BMA400 값 출력 x, y, z SensorData = null; string value = ""; if (checkBox_Edit.Checked == false) { if (InputBox("번호 입력", "일련 번호:", ref value) == DialogResult.OK) { // SN dataGridView_Sensor.Rows[0].Cells[1].Value = Name = value; serialPort.Write(value); button_SensorTestSave(); for (int i = 0; i < 12; i++) dataGridView_Sensor.Rows[0].Cells[i].Value = null; } } dataGridView_Sensor.Refresh(); } return; } catch (Exception ex) { /*MessageBox.Show(ex.StackTrace); */ } } private void label_Port_MouseLeave(object sender, EventArgs e) { panel_Port.BackColor = Color.FromArgb(0, 159, 200); } private void label_Port_MouseMove(object sender, MouseEventArgs e) { panel_Port.BackColor = Color.FromArgb(0, 159, 255); } private void label_Port_Click(object sender, EventArgs e) { // Boolean ret = false; try { if (serialPort.IsOpen) // 이미 포트가 열려 있을 때 { //When the port is open serialPort.Close(); label_Port.Text = "Port Open"; //ret = true; } else//When the port is close //포트가 열려 있지 않을 때 { if (comboBox_Port.Text != "") { serialPort.PortName = Serial_Name = comboBox_Port.SelectedItem.ToString(); serialPort.BaudRate = Convert.ToInt32(comboBox_bps.Text); serialPort.Open(); label_Port.Text = "Port Close"; // Debug.Debug_Main_Form_Get(this.main_form); } else { MessageBox.Show("Port is not set"); // ret = true; } } } catch { MessageBox.Show("Port Open Faile" + Serial_Name); } // return ret; } public static DialogResult InputBox(string title, string promptText, ref string value) { Form form = new Form(); System.Windows.Forms.Label label = new System.Windows.Forms.Label(); System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox(); System.Windows.Forms.Button buttonOk = new System.Windows.Forms.Button(); System.Windows.Forms.Button buttonCancel = new System.Windows.Forms.Button(); form.Text = title; label.Text = promptText; textBox.Text = value; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; label.SetBounds(9, 20, 372, 13); textBox.SetBounds(12, 36, 372, 20); buttonOk.SetBounds(228, 72, 75, 23); buttonCancel.SetBounds(309, 72, 75, 23); label.AutoSize = true; textBox.Anchor = textBox.Anchor | AnchorStyles.Right; buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(396, 107); form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; DialogResult dialogResult = form.ShowDialog(); value = textBox.Text; return dialogResult; } private void button_Clear_Click(object sender, EventArgs e) { System.Windows.Forms.RichTextBox tbReceived = null; if (panel_GpsTest.Visible == true) { tbReceived = richTextBox_Gps; } else if (panel_Catm1Test.Visible == true) { tbReceived = richTextBox_catm1; } else if (panel_SensorTest.Visible == true) { tbReceived = richTextBox_Sensor; } tbReceived.Text = ""; } string FileSaveSet = null; private void button_GpsTestSave_Click(object sender, EventArgs e) { string CheckProductionNum = null; try { CheckProductionNum = dataGridView_Gps.Rows[0].Cells[0].Value.ToString(); } catch { } try { if (!CheckProductionNum.Contains("BL-VITE00-V")) { MessageBox.Show("잘못된 생산 번호 입니다."); return; } }catch { MessageBox.Show("생산번호를 적어주세요."); } string Ref_Xls_File = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath).ToString(); string Dst_Xls_File = null; Ref_Xls_File = Ref_Xls_File + @"\APL_200221.xls"; FileInfo SrcfileInfo = new FileInfo(Ref_Xls_File); FileInfo DstfileInfo; if (dataGridView_Gps.Rows[0].Cells[0].Value != null && dataGridView_Gps.Rows[0].Cells[1].Value != null) { if (SrcfileInfo.Exists) { if (FileSaveSet == null) { button_Path_Click(null, null); return; // MessageBox.Show("레퍼런스 엑셀 파일이 존재하지 않습니다. \r\n강차장님에게 문의 하세요."); } else { // File Copy 후 Data 입력 Dst_Xls_File = FileSaveSet + @"\" + dataGridView_Gps.Rows[0].Cells[0].Value.ToString() + @".xls"; DstfileInfo = new FileInfo(Dst_Xls_File); if (DstfileInfo.Exists) { if (MessageBox.Show("이미 파일이 있습니다.\r\n 덮어씌우겠습니까?", "YesOrNo", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { // File.Copy(Ref_Xls_File, Dst_Xls_File, true); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); return; } } else { //MessageBox.Show("아니요 클릭"); return; // 아니오시 Return; } } else { File.Copy(Ref_Xls_File, Dst_Xls_File); } } } else { MessageBox.Show("레퍼런스 엑셀 파일이 존재하지 않습니다. \r\n강차장님에게 문의 하세요."); return; } } else { MessageBox.Show("생산번호/GPS SNR 값이 제대로 입력 되지 않았습니다.\r\n확인후 다시 저장하세요."); return; } Gps_DataxlsWrite(Dst_Xls_File); dataGridView_Gps.Rows[0].Cells[0].Value = null; dataGridView_Gps.Rows[0].Cells[1].Value = null; dataGridView_Gps.Refresh(); // if (!di.Exists) { di.Create(); } //string tmppath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); #if false if (dataGridView_Gps.Rows[0].Cells[1].Value != null) { string path = @"xxxx.txt"; FileInfo file = new FileInfo(path); if (file.Exists) { //파일이 있는지 //복사(경로,덮어쓰기 옵션 기본값 false) //만약 덮어쓰기 false일 때 파일이 존재하면 에러남. file.CopyTo(@"xxx2.txt", true); } } #endif } private void button_SensorTestSave() { string CheckProductionNum = null; try { CheckProductionNum = dataGridView_Sensor.Rows[0].Cells[0].Value.ToString(); } catch { } try { if (!CheckProductionNum.Contains("BL-VITE00-V")) { MessageBox.Show("잘못된 생산 번호 입니다."); return; } } catch { MessageBox.Show("생산번호를 적어주세요."); } string Ref_Xls_File = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath).ToString(); string Dst_Xls_File = null; Ref_Xls_File = Ref_Xls_File + @"\APL_200221.xls"; FileInfo SrcfileInfo = new FileInfo(Ref_Xls_File); FileInfo DstfileInfo; if (dataGridView_Sensor.Rows[0].Cells[0].Value != null) { if (SrcfileInfo.Exists) { if (FileSaveSet == null) { button_Path_Click(null, null); return; // MessageBox.Show("레퍼런스 엑셀 파일이 존재하지 않습니다. \r\n강차장님에게 문의 하세요."); } else { // File Copy 후 Data 입력 Dst_Xls_File = FileSaveSet + @"\" + dataGridView_Sensor.Rows[0].Cells[0].Value.ToString() + @".xls"; DstfileInfo = new FileInfo(Dst_Xls_File); if (DstfileInfo.Exists) { if (MessageBox.Show("이미 파일이 있습니다.\r\n 덮어씌우겠습니까?", "YesOrNo", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { // File.Copy(Ref_Xls_File, Dst_Xls_File, true); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); return; } } else { //MessageBox.Show("아니요 클릭"); return; // 아니오시 Return; } } else { File.Copy(Ref_Xls_File, Dst_Xls_File); } } } else { MessageBox.Show("레퍼런스 엑셀 파일이 존재하지 않습니다. \r\n강차장님에게 문의 하세요."); return; } } else { MessageBox.Show("생산번호 값이 제대로 입력 되지 않았습니다.\r\n확인후 다시 저장하세요."); return; } Sensor_DataxlsWrite(Dst_Xls_File); // dataGridView_Sensor.Rows[0].Cells[0].Value = null; // dataGridView_Sensor.Rows[0].Cells[1].Value = null; // if (!di.Exists) { di.Create(); } //string tmppath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); #if false if (dataGridView_Gps.Rows[0].Cells[1].Value != null) { string path = @"xxxx.txt"; FileInfo file = new FileInfo(path); if (file.Exists) { //파일이 있는지 //복사(경로,덮어쓰기 옵션 기본값 false) //만약 덮어쓰기 false일 때 파일이 존재하면 에러남. file.CopyTo(@"xxx2.txt", true); } } #endif } Excel.Application ExcelApp = null; Excel.Workbook wb = null; Excel.Worksheet ws = null; private void Gps_DataxlsWrite(string dst) { //Write //파일이 존재 한다면..삭제 하고.. /*if (File.Exists("C:\\Test.xls")) { File.Delete("C:\\Test.xls"); }*/ try { ExcelApp = new Excel.Application(); wb = ExcelApp.Workbooks.Open(dst, 0, false, 5, Missing.Value, Missing.Value, false, Missing.Value, Missing.Value, true, false, Missing.Value, false, false, false); ws = wb.Worksheets["Sheet1"] as Excel.Worksheet; //엑셀 시트 인덱스 번호는 0,0 부터 시작 하는 것이 아니라 1,1 A1 부터 시작 함. 0,0 으로 시작하면 오류... //시트에 값 쓰기... ws.Cells[8, 9] = dataGridView_Gps.Rows[0].Cells[0].Value; ws.Cells[8, 11] = dataGridView_Gps.Rows[0].Cells[1].Value; /*ws.Cells[1, 3] = "123"; ws.Cells[1, 4] = "1234"; ws.Cells[2, 1] = "Test1"; //A2 ws.Cells[3, 1] = "Test12"; //A3 ws.Cells[4, 1] = "Test123"; //A4*/ //다른 이름으로 저장하기... wb.Save(); // => 오픈한 파일 그대로 저장... /* wb.SaveAs("C:\\Test.xls", Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); */ //파일 닫기... wb.Close(false, Type.Missing, Type.Missing); wb = null; ExcelApp.Quit(); } catch (Exception ex) { //객체들 메모리 해제 ReleaseExcelObject(ws); ReleaseExcelObject(wb); ReleaseExcelObject(ExcelApp); GC.Collect(); } finally { //객체들 메모리 해제 ReleaseExcelObject(ws); ReleaseExcelObject(wb); ReleaseExcelObject(ExcelApp); GC.Collect(); } } private void Sensor_DataxlsWrite(string dst) { //Write //파일이 존재 한다면..삭제 하고.. /*if (File.Exists("C:\\Test.xls")) { File.Delete("C:\\Test.xls"); }*/ try { ExcelApp = new Excel.Application(); wb = ExcelApp.Workbooks.Open(dst, 0, false, 5, Missing.Value, Missing.Value, false, Missing.Value, Missing.Value, true, false, Missing.Value, false, false, false); ws = wb.Worksheets["Sheet1"] as Excel.Worksheet; //엑셀 시트 인덱스 번호는 0,0 부터 시작 하는 것이 아니라 1,1 A1 부터 시작 함. 0,0 으로 시작하면 오류... //시트에 값 쓰기... ws.Cells[8, 9] = dataGridView_Sensor.Rows[0].Cells[0].Value; // 제조 번호 ws.Cells[8, 4] = dataGridView_Sensor.Rows[0].Cells[1].Value; // 일련번호 ws.Cells[8, 6] = dataGridView_Sensor.Rows[0].Cells[2].Value; //IMEI ws.Cells[8, 7] = dataGridView_Sensor.Rows[0].Cells[3].Value;// PHONE ws.Cells[8, 8] = dataGridView_Sensor.Rows[0].Cells[4].Value;//USIM ws.Cells[8, 10] = dataGridView_Sensor.Rows[0].Cells[5].Value;//VER ws.Cells[8, 13] = dataGridView_Sensor.Rows[0].Cells[6].Value;//BATT ws.Cells[8, 14] = dataGridView_Sensor.Rows[0].Cells[7].Value;//SYS ws.Cells[8, 15] = dataGridView_Sensor.Rows[0].Cells[8].Value;//TEMP ws.Cells[8, 16] = dataGridView_Sensor.Rows[0].Cells[9].Value;//BMA ws.Cells[8, 17] = dataGridView_Sensor.Rows[0].Cells[10].Value;//BMA ws.Cells[8, 18] = dataGridView_Sensor.Rows[0].Cells[11].Value;//BMA /*ws.Cells[1, 3] = "123"; ws.Cells[1, 4] = "1234"; ws.Cells[2, 1] = "Test1"; //A2 ws.Cells[3, 1] = "Test12"; //A3 ws.Cells[4, 1] = "Test123"; //A4*/ //다른 이름으로 저장하기... wb.Save(); // => 오픈한 파일 그대로 저장... /* wb.SaveAs("C:\\Test.xls", Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); */ //파일 닫기... wb.Close(false, Type.Missing, Type.Missing); wb = null; ExcelApp.Quit(); } catch (Exception ex) { //객체들 메모리 해제 ReleaseExcelObject(ws); ReleaseExcelObject(wb); ReleaseExcelObject(ExcelApp); GC.Collect(); } finally { //객체들 메모리 해제 ReleaseExcelObject(ws); ReleaseExcelObject(wb); ReleaseExcelObject(ExcelApp); GC.Collect(); } } private void ReleaseExcelObject(object obj) { try { if (obj != null) { Marshal.ReleaseComObject(obj); obj = null; } } catch (Exception ex) { obj = null; throw ex; } finally { GC.Collect(); } } // CommonOpenFileDialog 클래스 생성 CommonOpenFileDialog dialog = new CommonOpenFileDialog(); private void button_Path_Click(object sender, EventArgs e) { // 처음 보여줄 폴더 설정(안해도 됨) //dialog.InitialDirectory = ""; dialog.IsFolderPicker = true; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { FileSaveSet = dialog.FileName; // label.Text = dialog.FileName; // 테스트용, 폴더 선택이 완료되면 선택된 폴더를 label에 출력 } } private void dataGridView_Gps_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button_GpsTestSave_Click(null,null); //to do } else { return; } } private void button_PrevFile_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { foreach (string x in openFileDialog.FileNames) { listBox_PreviousFile.Items.Add(x); } } } private void button_AfterFile_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { foreach (string x in openFileDialog.FileNames) { listBox_AfterFile.Items.Add(x); } } } private void label_Merge_Click(object sender, EventArgs e) { panel_GpsTest.Visible = false; panel_SensorTest.Visible = false; panel_Catm1Test.Visible = false; panel_MergeMain.Visible = true; panel_SnCheckMain.Visible = false; } private void label_SnCheck_Click(object sender, EventArgs e) { panel_GpsTest.Visible = false; panel_SensorTest.Visible = false; panel_Catm1Test.Visible = false; panel_MergeMain.Visible = false; panel_SnCheckMain.Visible = true; } private void button_FileFindLoad_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { /*foreach (string x in openFileDialog.FileNames) { listBox_Previous.Items.Add(x); }*/ } } private void button_Merge_Click(object sender, EventArgs e) { OpenExcelFile(listBox_PreviousFile.Items[0].ToString()); } #region /// /// 엑셀 정식 파일 형식이 아닌 파일 읽기 /// /// 파일명.확장자 /// public void OpenExcelFile(string FileName) { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook; Excel.Worksheet worksheet; Excel.Range range; workbook = excelApp.Workbooks.Open(FileName); //Environment.CurrentDirectory+ "\\Excel.xlsx"); worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"]; try { //MessageWrite(LogTraceLevel.Info, "OpenExcelFile 함수가 시작 되었습니다.", exception); int column = 0; int row = 0; string sTmpColumnName = "SKT 일련번호"; string[] colHeader = sTmpColumnName.Split(','); range = worksheet.UsedRange; String data = ""; data += ((range.Cells[4, 5] as Excel.Range).Value2.ToString() + " "); /* for (int i = 1; i <= range.Rows.Count; ++i) { for (int j = 1; j <= range.Columns.Count; ++j) { data += ((range.Cells[i, j] as Excel.Range).Value2.ToString() + " "); } data += "\n"; }*/ workbook.Close(false, Type.Missing, Type.Missing); excelApp.Quit(); //MessageBox.Show("OpenExcelFile 함수가 종료 되었습니다."); } catch (Exception ex) { MessageBox.Show("OpenExcelFile오류가 발생되었습니다.[{0}]"); excelApp.Quit(); //throw new Exception(ex.Message); } } #endregion } }