Imports System
Imports System.IO.Ports
Imports System.Threading
Imports System.IO.Ports.SerialPort
Imports System.IO
Imports System.Text

Public Class AgingForm
    Private StartSwitch As Boolean = False

    Const CNT_CH As Integer = 10
    Public RunTime(0 To CNT_CH) As Long
    Public EnableRunConnect(0 To CNT_CH) As Boolean
    Public ConnTimeoutCnt(0 To CNT_CH) As Long
    Public DevConnectFlag(0 To CNT_CH) As Boolean
    Public DevPowerONFlag(0 To CNT_CH) As Boolean
    Public EnableRunTime(0 To CNT_CH) As Boolean
    Public RunPowerOnFlag(0 To CNT_CH) As Boolean
    Public PowerOnDelayTime(0 To CNT_CH) As Long
    Public PowerOnTimeoutCnt(0 To CNT_CH) As Long
    Public preVal(0 To CNT_CH) As Long
    Public preCnt(0 To CNT_CH) As Long
    Public FileSavePath(0 To CNT_CH) As String

    Public PowerOnTime As Integer = 1 ''2
    Public PowerOnTimeout As Integer = 20 ''20
    Public ConnTimeout As Long = 150 ''1
    Public cmdMessage As String
    Public rxMessage As String
    Public cmpMessage As String = "SUCCESS"
    Public tmpCmdMessage As String

    Public gpbInfo(CNT_CH + 1) As GroupBox
    Public btnRun(CNT_CH + 1) As Button
    Public txtBox(CNT_CH + 1) As TextBox
    Public txbMainSN(CNT_CH + 1) As TextBox
    Public txbCartSN(CNT_CH + 1) As TextBox
    Public txbStartTime(CNT_CH + 1) As TextBox
    Public txbEndTime(CNT_CH + 1) As TextBox
    Public txbShotCnt(CNT_CH + 1) As TextBox
    Public txtMainStartTemp(CNT_CH + 1) As TextBox
    Public txtCartStartTemp(CNT_CH + 1) As TextBox
    Public txtMainEndTemp(CNT_CH + 1) As TextBox
    Public txtCartEndTemp(CNT_CH + 1) As TextBox
    Public txbCmdWindow(CNT_CH + 1) As TextBox
    Public txbInfoBox(CNT_CH + 1) As TextBox
    Public lblEndRuntime(CNT_CH + 1) As Label
    Public chbAutoPowerOn(CNT_CH + 1) As CheckBox
    Public AutoPowerOnFlag(CNT_CH + 1) As Boolean

    Private error_check(CNT_CH) As Int16
    Private dev_data, cart_data, dev_limit, cart_limit As Double


    Private before_dev(CNT_CH) As Long
    Private before_cart(CNT_CH) As Long
    Private before_shot(CNT_CH) As Integer

    Private AG_DATE(0 To CNT_CH) As String
    Private AG_StartTime(0 To CNT_CH) As String
    Private AG_Device_SN(0 To CNT_CH) As String
    Private AG_Cart_SN(0 To CNT_CH) As String

    Private AG_ERROR(0 To CNT_CH) As String


    Private Sub AgingForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim portname() As String
        Dim i As Integer

        lblTime.Text = Now
        portname = SerialPort.GetPortNames

        For i = 1 To portname.Length
            cboComPort.Items.Add(portname(i - 1))
        Next i

        cboComPort.Text = "PRESS!"
        JsonFull_Reset()

        error_check(1) = 0
        error_check(2) = 0
        error_check(3) = 0
        error_check(4) = 0
        error_check(5) = 0
        error_check(6) = 0
        error_check(7) = 0
        error_check(8) = 0
        error_check(9) = 0
        error_check(10) = 0

        gpbInfo(1) = gpbInfo1
        gpbInfo(2) = gpbInfo2
        gpbInfo(3) = gpbInfo3
        gpbInfo(4) = gpbInfo4
        gpbInfo(5) = gpbInfo5
        gpbInfo(6) = gpbInfo6
        gpbInfo(7) = gpbInfo7
        gpbInfo(8) = gpbInfo8
        gpbInfo(9) = gpbInfo9
        gpbInfo(10) = gpbInfo10

        btnRun(1) = btnRun1
        btnRun(2) = btnRun2
        btnRun(3) = btnRun3
        btnRun(4) = btnRun4
        btnRun(5) = btnRun5
        btnRun(6) = btnRun6
        btnRun(7) = btnRun7
        btnRun(8) = btnRun8
        btnRun(9) = btnRun9
        btnRun(10) = btnRun10

        txbMainSN(1) = txbMainSN1
        txbMainSN(2) = txbMainSN2
        txbMainSN(3) = txbMainSN3
        txbMainSN(4) = txbMainSN4
        txbMainSN(5) = txbMainSN5
        txbMainSN(6) = txbMainSN6
        txbMainSN(7) = txbMainSN7
        txbMainSN(8) = txbMainSN8
        txbMainSN(9) = txbMainSN9
        txbMainSN(10) = txbMainSN10

        txbCartSN(1) = txbCartSN1
        txbCartSN(2) = txbCartSN2
        txbCartSN(3) = txbCartSN3
        txbCartSN(4) = txbCartSN4
        txbCartSN(5) = txbCartSN5
        txbCartSN(6) = txbCartSN6
        txbCartSN(7) = txbCartSN7
        txbCartSN(8) = txbCartSN8
        txbCartSN(9) = txbCartSN9
        txbCartSN(10) = txbCartSN10

        txbStartTime(1) = txbStartTime1
        txbStartTime(2) = txbStartTime2
        txbStartTime(3) = txbStartTime3
        txbStartTime(4) = txbStartTime4
        txbStartTime(5) = txbStartTime5
        txbStartTime(6) = txbStartTime6
        txbStartTime(7) = txbStartTime7
        txbStartTime(8) = txbStartTime8
        txbStartTime(9) = txbStartTime9
        txbStartTime(10) = txbStartTime10

        txbEndTime(1) = txbEndTime1
        txbEndTime(2) = txbEndTime2
        txbEndTime(3) = txbEndTime3
        txbEndTime(4) = txbEndTime4
        txbEndTime(5) = txbEndTime5
        txbEndTime(6) = txbEndTime6
        txbEndTime(7) = txbEndTime7
        txbEndTime(8) = txbEndTime8
        txbEndTime(9) = txbEndTime9
        txbEndTime(10) = txbEndTime10

        txbShotCnt(1) = txbShotCnt1
        txbShotCnt(2) = txbShotCnt2
        txbShotCnt(3) = txbShotCnt3
        txbShotCnt(4) = txbShotCnt4
        txbShotCnt(5) = txbShotCnt5
        txbShotCnt(6) = txbShotCnt6
        txbShotCnt(7) = txbShotCnt7
        txbShotCnt(8) = txbShotCnt8
        txbShotCnt(9) = txbShotCnt9
        txbShotCnt(10) = txbShotCnt10

        txtMainStartTemp(1) = txtMainStartTemp1
        txtMainStartTemp(2) = txtMainStartTemp2
        txtMainStartTemp(3) = txtMainStartTemp3
        txtMainStartTemp(4) = txtMainStartTemp4
        txtMainStartTemp(5) = txtMainStartTemp5
        txtMainStartTemp(6) = txtMainStartTemp6
        txtMainStartTemp(7) = txtMainStartTemp7
        txtMainStartTemp(8) = txtMainStartTemp8
        txtMainStartTemp(9) = txtMainStartTemp9
        txtMainStartTemp(10) = txtMainStartTemp10

        txtCartStartTemp(1) = txtCartStartTemp1
        txtCartStartTemp(2) = txtCartStartTemp2
        txtCartStartTemp(3) = txtCartStartTemp3
        txtCartStartTemp(4) = txtCartStartTemp4
        txtCartStartTemp(5) = txtCartStartTemp5
        txtCartStartTemp(6) = txtCartStartTemp6
        txtCartStartTemp(7) = txtCartStartTemp7
        txtCartStartTemp(8) = txtCartStartTemp8
        txtCartStartTemp(9) = txtCartStartTemp9
        txtCartStartTemp(10) = txtCartStartTemp10

        txtMainEndTemp(1) = txtMainEndTemp1
        txtMainEndTemp(2) = txtMainEndTemp2
        txtMainEndTemp(3) = txtMainEndTemp3
        txtMainEndTemp(4) = txtMainEndTemp4
        txtMainEndTemp(5) = txtMainEndTemp5
        txtMainEndTemp(6) = txtMainEndTemp6
        txtMainEndTemp(7) = txtMainEndTemp7
        txtMainEndTemp(8) = txtMainEndTemp8
        txtMainEndTemp(9) = txtMainEndTemp9
        txtMainEndTemp(10) = txtMainEndTemp10

        txtCartEndTemp(1) = txtCartEndTemp1
        txtCartEndTemp(2) = txtCartEndTemp2
        txtCartEndTemp(3) = txtCartEndTemp3
        txtCartEndTemp(4) = txtCartEndTemp4
        txtCartEndTemp(5) = txtCartEndTemp5
        txtCartEndTemp(6) = txtCartEndTemp6
        txtCartEndTemp(7) = txtCartEndTemp7
        txtCartEndTemp(8) = txtCartEndTemp8
        txtCartEndTemp(9) = txtCartEndTemp9
        txtCartEndTemp(10) = txtCartEndTemp10

        txbCmdWindow(1) = txbCmdWindow1
        txbCmdWindow(2) = txbCmdWindow2
        txbCmdWindow(3) = txbCmdWindow3
        txbCmdWindow(4) = txbCmdWindow4
        txbCmdWindow(5) = txbCmdWindow5
        txbCmdWindow(6) = txbCmdWindow6
        txbCmdWindow(7) = txbCmdWindow7
        txbCmdWindow(8) = txbCmdWindow8
        txbCmdWindow(9) = txbCmdWindow9
        txbCmdWindow(10) = txbCmdWindow10

        txbInfoBox(1) = txbInfoBox1
        txbInfoBox(2) = txbInfoBox2
        txbInfoBox(3) = txbInfoBox3
        txbInfoBox(4) = txbInfoBox4
        txbInfoBox(5) = txbInfoBox5
        txbInfoBox(6) = txbInfoBox6
        txbInfoBox(7) = txbInfoBox7
        txbInfoBox(8) = txbInfoBox8
        txbInfoBox(9) = txbInfoBox9
        txbInfoBox(10) = txbInfoBox10

        lblEndRuntime(1) = lblEndRuntime1
        lblEndRuntime(2) = lblEndRuntime2
        lblEndRuntime(3) = lblEndRuntime3
        lblEndRuntime(4) = lblEndRuntime4
        lblEndRuntime(5) = lblEndRuntime5
        lblEndRuntime(6) = lblEndRuntime6
        lblEndRuntime(7) = lblEndRuntime7
        lblEndRuntime(8) = lblEndRuntime8
        lblEndRuntime(9) = lblEndRuntime9
        lblEndRuntime(10) = lblEndRuntime10

        chbAutoPowerOn(1) = chbAutoPowerOn1
        chbAutoPowerOn(2) = chbAutoPowerOn2
        chbAutoPowerOn(3) = chbAutoPowerOn3
        chbAutoPowerOn(4) = chbAutoPowerOn4
        chbAutoPowerOn(5) = chbAutoPowerOn5
        chbAutoPowerOn(6) = chbAutoPowerOn6
        chbAutoPowerOn(7) = chbAutoPowerOn7
        chbAutoPowerOn(8) = chbAutoPowerOn8
        chbAutoPowerOn(9) = chbAutoPowerOn9
        chbAutoPowerOn(10) = chbAutoPowerOn10

        Me.Text = "DUALSONIC Aging Util V1.1.2"

        Read_ini()
    End Sub

    Private Sub JsonFull_Reset()
        For i = 0 To CNT_CH
            AG_Cart_SN(i) = Nothing
            AG_DATE(i) = Nothing
            AG_Device_SN(i) = Nothing
            AG_ERROR(i) = Nothing
            AG_StartTime(i) = Nothing
        Next
    End Sub

    Private Sub exit_Process()
        Try
            SerialPort1.Close()
            Save_ini()
            End
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub runTimeTimer_Tick(sender As System.Object, e As System.EventArgs) Handles runTimeTimer.Tick
        lblTime.Text = Now

        For cnt = 0 To CNT_CH
            If EnableRunTime(cnt) = True Then
                RunTime(cnt) = RunTime(cnt) + 1

                txbEndTime(cnt).Text = Format(Val((RunTime(cnt) - (RunTime(cnt) Mod 3600)) / 3600), "00") & ":" & Format(Val(((RunTime(cnt) Mod 3600) - (RunTime(cnt) Mod 60)) / 60), "00") & ":" & Format(Val(RunTime(cnt)) Mod 60, "00")
            End If
        Next cnt
    End Sub

    Private Sub JsonData_reset(i As Int16)
        AG_Cart_SN(i) = Nothing
        AG_DATE(i) = Nothing
        AG_Device_SN(i) = Nothing
        AG_ERROR(i) = Nothing
        AG_StartTime(i) = Nothing
    End Sub

    Private Function cmdRunButton(chNum As Integer)
        Dim txbChangeEnable As Boolean = True
        Dim dispStr As String
        Dim MainSN As String
        Dim CartSn As String


        If btnRun(chNum).Text = "시작" Then
            btnRun(chNum).Text = "중지"
            EnableRunConnect(chNum) = False
            DevConnectFlag(chNum) = False
            DevPowerONFlag(chNum) = False
            before_dev(chNum) = 0
            before_cart(chNum) = 0
            before_shot(chNum) = 0
            JsonData_reset(chNum)

            txbInfoBox(chNum).Text = "RUNNING"
            txbInfoBox(chNum).BackColor = Color.Blue
            txbInfoBox(chNum).Refresh()

            txbStartTime(chNum).Text = TimeOfDay
            EnableRunTime(chNum) = True

            btnRun(chNum).Enabled = True
            btnRun(chNum).Refresh()

            txbEndTime(chNum).Text = ""
            txbShotCnt(chNum).Text = ""
            txtMainStartTemp(chNum).Text = ""
            txtCartStartTemp(chNum).Text = ""
            txtMainEndTemp(chNum).Text = ""
            txtCartEndTemp(chNum).Text = ""
            txbCmdWindow(chNum).Text = ""
            txtMainEndTemp(chNum).ForeColor = Color.Blue
            txtCartEndTemp(chNum).ForeColor = Color.Blue

            txb_limit.ReadOnly = True
            txb_minimum.ReadOnly = True
            txb_maximum.ReadOnly = True
            txbCartTemp.ReadOnly = True
            txbDevTemp.ReadOnly = True

            If txbMainSN(chNum).Text = "Click" Then
                MainSN = "NA"
            Else
                MainSN = txbMainSN(chNum).Text
            End If

            If txbCartSN(chNum).Text = "Click" Then
                CartSn = "NA"
            Else
                CartSn = txbCartSN(chNum).Text
            End If

            AG_DATE(chNum) = DateAndTime.Year(Now) & "-" & DateAndTime.Month(Now) & "-" & DateAndTime.Day(Now)
            dispStr = "DATE" & "," & AG_DATE(chNum)  ''1번 MES DATE
            Save_CSV_Dir(chNum, dispStr)

            AG_StartTime(chNum) = (Format(TimeOfDay, "HH:mm:ss"))
            dispStr = "TIME" & "," & AG_StartTime(chNum) ''2번 MES TIME
            Save_CSV(chNum, dispStr)

            AG_Device_SN(chNum) = MainSN
            dispStr = "DEVICE SN" & "," & MainSN  ''3번 MES DEVICE_SN
            Save_CSV(chNum, dispStr)

            AG_Cart_SN(chNum) = CartSn
            dispStr = "CART SN" & "," & CartSn
            Save_CSV(chNum, dispStr)

            dispStr = "MAIN TEMP" & "," & txbDevTemp.Text
            Save_CSV(chNum, dispStr)

            dispStr = "CART TEMP" & "," & txbCartTemp.Text
            Save_CSV(chNum, dispStr)

            dispStr = "SHOT LIMIT" & "," & txb_limit.Text
            Save_CSV(chNum, dispStr)

            dispStr = "MIN SHOT CNT" & "," & txb_minimum.Text
            Save_CSV(chNum, dispStr)

            dispStr = "MAX SHOT CNT" & "," & txb_maximum.Text
            Save_CSV(chNum, dispStr)

            dispStr = ("TIME,CH,SHOT_CNT,EXT_TEMP,AMP_TEMP,CT_TEMP")
            Save_CSV(chNum, dispStr)

            tmpCmdMessage = "agenable"
            cmdMessage = "[" & tmpCmdMessage & " " & chNum & ",1]" + vbCrLf
            SendData(cmdMessage)

        ElseIf btnRun(chNum).Text = "중지" Then
            btnRun(chNum).Text = "시작"
            EnableRunTime(chNum) = False

            tmpCmdMessage = "agenable"
            cmdMessage = "[" & tmpCmdMessage & " " & chNum & ",0]" + vbCrLf
            SendData(cmdMessage)

            RunTime(chNum) = 0

            Dim OkNg As Boolean = False

            If Val(txtMainEndTemp(chNum).Text) < Val(txbDevTemp.Text) And Val(txtCartEndTemp(chNum).Text) < Val(txbCartTemp.Text) Then
                If Val(txbShotCnt(chNum).Text) >= Val(txb_minimum.Text) And Val(txbShotCnt(chNum).Text) <= Val(txb_maximum.Text) Then
                    txbInfoBox(chNum).Text = "합격"
                    txbInfoBox(chNum).BackColor = Color.Green
                    OkNg = True

                    dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "PASS"
                    Save_CSV(chNum, dispStr)
                Else
                    txbInfoBox(chNum).Text = "불합격"
                    txbInfoBox(chNum).BackColor = Color.Red
                    OkNg = False

                    dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "Shot Over"
                    Save_CSV(chNum, dispStr)
                End If

            Else
                If Val(txbShotCnt(chNum).Text) >= Val(txb_minimum.Text) And Val(txbShotCnt(chNum).Text) <= Val(txb_maximum.Text) Then

                    txbInfoBox(chNum).Text = "합격"
                    txbInfoBox(chNum).BackColor = Color.Green
                    OkNg = True

                    dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "PASS"
                    Save_CSV(chNum, dispStr)

                Else

                    txbInfoBox(chNum).Text = "불합격"
                    txbInfoBox(chNum).BackColor = Color.Red
                    OkNg = False

                    dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "SHOT FAIL"
                    Save_CSV(chNum, dispStr)

                End If

                If Val(txtMainEndTemp(chNum).Text) > Val(txbDevTemp.Text) Then
                    txtMainEndTemp(chNum).ForeColor = Color.Red
                End If

                If Val(txtCartEndTemp(chNum).Text) > Val(txbCartTemp.Text) Then
                    txtCartEndTemp(chNum).ForeColor = Color.Red
                End If

            End If

            txbInfoBox(chNum).Refresh()

            If PostgreUpdateReg(chNum, OkNg) Then
                MsgBox("MES 서버 등록 오류 !!", vbCritical)
            End If

            For i = 1 To 10
                If btnRun(i).Text = "중지" Then
                    txbChangeEnable = False
                End If
            Next

            If txbChangeEnable = True Then
                txb_limit.ReadOnly = False
                txb_minimum.ReadOnly = False
                txb_maximum.ReadOnly = False
                txbCartTemp.ReadOnly = False
                txbDevTemp.ReadOnly = False
            End If

            AutoPowerOnFlag(chNum) = False

        End If

        Return True

    End Function

    Private Function PostgreUpdateReg(chNum As Int16, OkNg As Boolean) As Boolean

        If txbShotCnt(chNum).Text = String.Empty Or txbShotCnt(chNum).Text = "0" Then
            Return False
        End If

        Dim DBCmd As String = "INSERT INTO temperature_chambers(jig_num, jig_ch, test_date, start_time, run_time, end_time, div_num, cart_num, test_result, limit_div_temp, limit_cart_temp, limit_shot, divtemp_start, carttemp_start, divtemp_end, carttemp_end, run_shot, error_code, created_at, updated_at) VALUES('" & nudJigNum.Value & "', '" & chNum & "', '" & AG_DATE(chNum) & "', '" & AG_StartTime(chNum) & "', '" & txbEndTime(chNum).Text & "', '" & Format(TimeOfDay, "HH:mm:ss") & "', '" & AG_Device_SN(chNum) & "', '" & AG_Cart_SN(chNum) & "', '" & OkNg & "', '" & txbDevTemp.Text & "', '" & txbCartTemp.Text & "','" & txb_limit.Text & "', '" & txtMainStartTemp(chNum).Text & "', '" & txtCartStartTemp(chNum).Text & "', '" & txtMainEndTemp(chNum).Text & "', '" & txtCartEndTemp(chNum).Text & "', '" & txbShotCnt(chNum).Text & "', '" & AG_ERROR(chNum) & "',  NOW(), NOW());"

        If pgDBCommand(DBCmd) Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function cmdAutoPowerOn(chNum As Integer)

        If btnRun(chNum).Text = "시작" Then
            txbInfoBox(chNum).Text = "부팅중"
            txbInfoBox(chNum).BackColor = Color.Red
            txbInfoBox(chNum).Refresh()
            'btnRun(chNum).Enabled = False
            btnRun(chNum).Refresh()

            PowerOnTimeoutCnt(chNum) = 0
            RunPowerOnFlag(chNum) = True
            tmpCmdMessage = "agtpmode"
            cmdMessage = "[" & tmpCmdMessage & " " & chNum & ",1]" + vbCrLf
            SendData(cmdMessage)
        End If

        Return True

    End Function

    Private Sub LiveTimer_Tick(sender As System.Object, e As System.EventArgs) Handles LiveTimer.Tick
        Try
            For cnt = 1 To CNT_CH
                If EnableRunTime(cnt) = True Then
                    If txbInfoBox(cnt).BackColor = Color.Red Then
                        txbInfoBox(cnt).BackColor = Color.Blue
                    Else
                        txbInfoBox(cnt).BackColor = Color.Red
                    End If
                    txbInfoBox(cnt).Refresh()
                End If

                If AutoPowerOnFlag(cnt) = True Then
                    If PowerOnDelayTime(cnt) = PowerOnTime Then
                        PowerOnDelayTime(cnt) = 0
                        AutoPowerOnFlag(cnt) = False
                        RunPowerOnFlag(cnt) = False
                        ''cmdRunButton(cnt)
                    End If
                    PowerOnDelayTime(cnt) += 1
                End If

                If RunPowerOnFlag(cnt) = True Then
                    If PowerOnTimeoutCnt(cnt) >= PowerOnTimeout Then
                        txbInfoBox(cnt).Text = "미연결"
                        txbInfoBox(cnt).BackColor = Color.Red
                        txbInfoBox(cnt).Refresh()

                        PowerOnTimeoutCnt(cnt) = 0
                        RunPowerOnFlag(cnt) = False

                        btnRun(cnt).Enabled = True
                        btnRun(cnt).Refresh()
                    End If
                    PowerOnTimeoutCnt(cnt) += 1
                End If
            Next cnt
        Catch ex As Exception
            MsgBox(Err.Description)
        End Try
    End Sub

    Private Sub ComportSetup()
        With SerialPort1
            .PortName = cboComPort.Text
            .BaudRate = 230400
            .DataBits = 8
            .Parity = IO.Ports.Parity.None
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
        End With
    End Sub

    Private Sub cmdSerial_Click(sender As System.Object, e As System.EventArgs) Handles cmdSerial.Click
        Dim portname() As String
        Dim i As Integer

        If cboComPort.Text = "" Then
            MsgBox("통신 Port를 선택하여 주세요.")
        Else
            If cmdSerial.Text = "열기" Then
                If SerialPort1.IsOpen = False Then
                    ComportSetup()
                    Try
                        SerialPort1.Open()
                        cmdSerial.Text = "닫기"

                        cboComPort.Enabled = False

                        For i = 1 To CNT_CH
                            gpbInfo(i).Enabled = True
                        Next i

                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                End If
            Else
                Try
                    cmdSerial.Text = "열기"
                    cboComPort.Enabled = True

                    For i = 1 To CNT_CH
                        If btnRun(i).Text = "중지" Then
                            cmdRunButton(i)
                        ElseIf btnRun(i).Text = "시작" Then
                            EnableRunConnect(i) = True
                            DevConnectFlag(i) = False
                            DevPowerONFlag(i) = False
                            ConnTimeoutCnt(i) = 0
                            '' NoUseAutoPwrOn(chNum)
                            CheckDevConnection(i)
                        End If
                        gpbInfo(i).Enabled = False
                    Next i

                    SerialPort1.Close()
                    cboComPort.Items.Clear()

                    portname = SerialPort.GetPortNames
                    For i = 1 To portname.Length
                        cboComPort.Items.Add(portname(i - 1))
                    Next i

                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            End If
        End If
    End Sub

    Private Sub cboComPort_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboComPort.SelectedIndexChanged
        cmdSerial.Enabled = True
    End Sub

    Private Function SendData(SendMessage As String) As Boolean
        Try
            If SerialPort1.IsOpen = True Then
                SerialPort1.DiscardInBuffer()
                SerialPort1.DiscardOutBuffer()
                SerialPort1.WriteTimeout = -1
                SerialPort1.WriteLine(SendMessage)

            Else
                MsgBox("통신 포트가 열리지 않았습니다.")
            End If
        Catch ex As Exception
            Return True
        End Try
        Return False
    End Function
    Private Function ReceiveData() As Boolean
        Dim cmdStr As String
        Dim cmdVal(0 To 5) As String
        Dim i As Integer
        Dim dispStr As String

        dispStr = ""

        Try
            If SerialPort1.IsOpen = True Then
                rxMessage = ""
                SerialPort1.ReadTimeout = 0
                rxMessage = SerialPort1.ReadLine()
                If rxMessage <> "" Then

                    If Mid(rxMessage, 1, 16) = "START DUALSONIC!" Then
                        AutoPowerOnFlag(Val(cmdVal(1))) = True
                        txbInfoBox(Val(cmdVal(1))).Text = "전원ON"
                        txbInfoBox(Val(cmdVal(1))).BackColor = Color.Green
                        txbInfoBox(Val(cmdVal(1))).Refresh()
                        Return True
                    End If

                    If Mid(rxMessage, 1, 1) = "[" Then
                        cmdMessage = Mid(rxMessage, 2, Len(rxMessage))


                        cmdStr = Mid(cmdMessage, 1, (InStr(rxMessage, " ") - 2))
                        cmdMessage = Mid(rxMessage, InStr(rxMessage, " ") + 1, Len(cmdMessage))

                        For i = 1 To 5
                            If InStr(cmdMessage, ",") <> 0 Then
                                cmdVal(i) = Mid(cmdMessage, 1, InStr(cmdMessage, ",") - 1)
                                cmdMessage = Mid(cmdMessage, InStr(cmdMessage, ",") + 1, Len(cmdMessage))
                            ElseIf InStr(cmdMessage, "]") <> 0 Then
                                cmdVal(i) = Mid(cmdMessage, 1, InStr(cmdMessage, "]") - 1)
                                cmdMessage = Mid(cmdMessage, InStr(cmdMessage, "]") + 1, Len(cmdMessage))
                            Else
                                Exit For
                            End If
                        Next i

                        Select Case cmdStr
                            Case "sendtemp"
                                If Val(cmdVal(1)) < 100 And Val(cmdVal(1)) > -100 Then
                                    dispStr = Format(Val(cmdVal(1) / 10), "0.0")
                                Else
                                    dispStr = Format(Val(cmdVal(1) / 10), "00.0")
                                End If

                                If Val(dispStr) <= -40.0 Then
                                    txtExtTemp1.Text = "N/A"
                                Else
                                    txtExtTemp1.Text = dispStr
                                End If

                                txtExtTemp1.Refresh()

                                If Val(cmdVal(2)) < 100 And Val(cmdVal(2)) > -100 Then
                                    dispStr = Format(Val(cmdVal(2) / 10), "0.0")
                                Else
                                    dispStr = Format(Val(cmdVal(2) / 10), "00.0")
                                End If

                                If Val(dispStr) <= -40.0 Then
                                    txtExtTemp2.Text = "N/A"
                                Else
                                    txtExtTemp2.Text = dispStr
                                End If
                                txtExtTemp2.Refresh()

                            Case "avalue"

                                If EnableRunTime(Val(cmdVal(1))) = True Then
                                    If cmdVal(3) < 0 Or cmdVal(4) < 0 Then

                                        txbShotCnt(Val(cmdVal(1))).Text = cmdVal(2)
                                        txtMainEndTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(3) / 10), "00.0")
                                        txtCartEndTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(4) / 10), "00.0")
                                        AG_ERROR(cmdVal(1)) = "600"

                                        cmdRunButton(Val(cmdVal(1)))
                                        txbInfoBox(Val(cmdVal(1))).Text = "Temp Error"
                                        txbInfoBox(Val(cmdVal(1))).BackColor = Color.DarkOrange
                                        txbInfoBox(Val(cmdVal(1))).Refresh()

                                        If txbCmdWindow(Val(cmdVal(1))).Text = "" Then
                                            dispStr = (TimeOfDay + " ERR TEMP")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                        Else
                                            dispStr = (vbCrLf + TimeOfDay + "ERR TEMP")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                        End If
                                        dispStr = (Format(TimeOfDay, "HH:mm:ss") + ",ERR TEMP")
                                        Save_CSV(cmdVal(1), dispStr)
                                    Else

                                        If cmdVal(2) = 1 Then

                                            AG_ERROR(cmdVal(1)) = "0"

                                            If before_dev(cmdVal(1)) = 0 And before_cart(cmdVal(1)) = 0 And before_shot(cmdVal(1)) = 0 Then
                                                txtMainStartTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(3) / 10), "00.0")
                                                txtCartStartTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(4) / 10), "00.0")
                                                before_shot(cmdVal(1)) = cmdVal(2)
                                                before_dev(cmdVal(1)) = cmdVal(3)
                                                before_cart(cmdVal(1)) = cmdVal(4)
                                            End If
                                        End If

                                        If Math.Abs(Val(before_dev(cmdVal(1))) - Val(cmdVal(3))) < Math.Abs(Val(nudErrRange.Value) * 10) And Math.Abs(Val(before_cart(cmdVal(1))) - Val(cmdVal(4))) < Math.Abs(Val(nudErrRange.Value) * 10) And Math.Abs(Val(before_shot(cmdVal(1))) - Val(cmdVal(2))) < Math.Abs(Val(nudErrRange.Value)) Then

                                            error_check(cmdVal(1)) = 0

                                            txbShotCnt(Val(cmdVal(1))).Text = cmdVal(2)
                                            txtMainEndTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(3) / 10), "00.0")
                                            txtCartEndTemp(Val(cmdVal(1))).Text = Format(Val(cmdVal(4) / 10), "00.0")

                                            before_shot(cmdVal(1)) = cmdVal(2)
                                            before_dev(cmdVal(1)) = cmdVal(3)
                                            before_cart(cmdVal(1)) = cmdVal(4)

                                            If txbCmdWindow(Val(cmdVal(1))).Text = "" Then
                                                dispStr = (TimeOfDay + " " + cmdVal(1) + "," + cmdVal(2) + "," + txtExtTemp1.Text + "," + txtMainEndTemp(Val(cmdVal(1))).Text + "," + txtCartEndTemp(Val(cmdVal(1))).Text)
                                                txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            Else
                                                dispStr = (vbCrLf + TimeOfDay + " " + cmdVal(1) + "," + cmdVal(2) + "," + txtExtTemp1.Text + "," + txtMainEndTemp(Val(cmdVal(1))).Text + "," + txtCartEndTemp(Val(cmdVal(1))).Text)
                                                txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            End If

                                            dispStr = (Format(TimeOfDay, "HH:mm:ss") + "," + cmdVal(1) + "," + cmdVal(2) + "," + txtExtTemp1.Text + "," + txtMainEndTemp(Val(cmdVal(1))).Text + "," + txtCartEndTemp(Val(cmdVal(1))).Text)

                                            Save_CSV(cmdVal(1), dispStr)

                                            If Val(txtMainEndTemp(Val(cmdVal(1))).Text) >= Val(txbDevTemp.Text) Or Val(txtCartEndTemp(Val(cmdVal(1))).Text) >= Val(txbCartTemp.Text) Or Val(txbShotCnt(Val(cmdVal(1))).Text) >= Val(txb_limit.Text) Then
                                                cmdRunButton(cmdVal(1))
                                            End If

                                        Else
                                            If error_check(Val(cmdVal(1))) = 5 Then
                                                AG_ERROR(cmdVal(1)) = "900"

                                                cmdRunButton(Val(cmdVal(1)))

                                                txbInfoBox(Val(cmdVal(1))).Text = "Data Error"
                                                txbInfoBox(Val(cmdVal(1))).BackColor = Color.DarkOrange
                                                txbInfoBox(Val(cmdVal(1))).Refresh()

                                                If txbCmdWindow(Val(cmdVal(1))).Text = "" Then
                                                    dispStr = (TimeOfDay + " ERR DATA")
                                                    txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                                Else
                                                    dispStr = (vbCrLf + TimeOfDay + "ERR DATA")
                                                    txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                                End If

                                                dispStr = (Format(TimeOfDay, "HH:mm:ss") + ",ERR DATA")
                                                Save_CSV(cmdVal(1), dispStr)

                                            Else
                                                error_check(cmdVal(1)) += 1

                                                If txbCmdWindow(Val(cmdVal(1))).Text = "" Then
                                                    txbCmdWindow(Val(cmdVal(1))).AppendText("Data Error(Skip)" & cmdVal(3) & "/" & cmdVal(4) & "/" & cmdVal(2) & "/" & before_dev(Val(cmdVal(1))) & "/" & before_cart(Val(cmdVal(1))) & "/" & before_shot(Val(cmdVal(1))))
                                                Else
                                                    txbCmdWindow(Val(cmdVal(1))).AppendText(vbCrLf + "Data Error(Skip)" & cmdVal(3) & "/" & cmdVal(4) & "/" & cmdVal(2) & "/" & before_dev(Val(cmdVal(1))) & "/" & before_cart(Val(cmdVal(1))) & "/" & before_shot(Val(cmdVal(1))))
                                                End If

                                                before_shot(cmdVal(1)) = cmdVal(2)
                                            End If

                                        End If

                                    End If

                                End If

                            Case "aenabler"
                                If EnableRunTime(Val(cmdVal(1))) = True Then

                                    If txbCmdWindow(Val(cmdVal(1))).Text = "0" Then
                                        If Val(cmdVal(2)) = 1 Then
                                            'dispStr = ("START TIME,CH,SC,EXT,AMP,CT")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            'dispStr = ("TIME,CH,SHOT_CNT,EXT_TEMP,AMP_TEMP,CT_TEMP")
                                            'Save_CSV(cmdVal(1), dispStr)
                                        Else
                                            dispStr = (TimeOfDay + " AGING STOP")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            dispStr = (Format(TimeOfDay, "HH:mm:ss") + ",AGING STOP")
                                            Save_CSV(cmdVal(1), dispStr)
                                        End If
                                    Else
                                        If Val(cmdVal(2)) = 1 Then
                                            'dispStr = (vbCrLf + "START TIME,CH,SC,EXT,AMP,CT")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            dispStr = ("TIME,CH,SHOT_CNT,EXT_TEMP,AMP_TEMP,CT_TEMP")
                                            Save_CSV(cmdVal(1), dispStr)
                                        Else
                                            dispStr = (vbCrLf + TimeOfDay + " AGING STOP")
                                            txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                            dispStr = (Format(TimeOfDay, "HH:mm:ss") + ",AGING STOP")
                                            Save_CSV(cmdVal(1), dispStr)
                                        End If
                                    End If

                                End If

                            Case "aerror"
                                If EnableRunTime(Val(cmdVal(1))) = True Then

                                    AG_ERROR(cmdVal(1)) = Val(cmdVal(2))

                                    cmdRunButton(Val(cmdVal(1)))

                                    txbInfoBox(Val(cmdVal(1))).Text = "ERR" + Format(Val(cmdVal(2)), "000")
                                    txbInfoBox(Val(cmdVal(1))).BackColor = Color.DarkOrange
                                    txbInfoBox(Val(cmdVal(1))).Refresh()

                                    If txbCmdWindow(Val(cmdVal(1))).Text = "" Then
                                        dispStr = (TimeOfDay + " ERR" + cmdVal(2))
                                        txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                    Else
                                        dispStr = (vbCrLf + TimeOfDay + " ERR" + cmdVal(2))
                                        txbCmdWindow(Val(cmdVal(1))).AppendText(dispStr)
                                    End If
                                    dispStr = (Format(TimeOfDay, "HH:mm:ss") + ",ERR" + cmdVal(2))
                                    Save_CSV(cmdVal(1), dispStr)

                                End If
                            Case "dsstart"
                                AutoPowerOnFlag(Val(cmdVal(1))) = True
                                txbInfoBox(Val(cmdVal(1))).Text = "전원ON"
                                txbInfoBox(Val(cmdVal(1))).BackColor = Color.Green
                                txbInfoBox(Val(cmdVal(1))).Refresh()

                            Case "chkpwron"
                                If cmdVal(2) = 1 Then
                                    DevConnectFlag(Val(cmdVal(1))) = True
                                    ConnTimeoutCnt(Val(cmdVal(1))) = 0
                                    CheckDevConnection(Val(cmdVal(1)))
                                Else
                                    DevConnectFlag(Val(cmdVal(1))) = False
                                    EnableRunConnect(Val(cmdVal(1))) = False
                                    txbInfoBox(Val(cmdVal(1))).Text = "미연결"
                                    txbInfoBox(Val(cmdVal(1))).BackColor = Color.Red
                                    txbInfoBox(Val(cmdVal(1))).Refresh()
                                End If
                            Case "dsfwver"
                                If cmdVal(2) <> "" Then
                                    DevPowerONFlag(Val(cmdVal(1))) = True
                                    ConnTimeoutCnt(Val(cmdVal(1))) = 0
                                    EnableRunConnect(Val(cmdVal(1))) = False
                                    NoUseAutoPwrOn(cmdVal(1))
                                    cmdRunButton(Val(cmdVal(1)))
                                Else
                                    DevPowerONFlag(Val(cmdVal(1))) = False
                                    EnableRunConnect(Val(cmdVal(1))) = False
                                End If
                        End Select
                        Return True
                    End If
                End If
            Else
                MsgBox("통신 포트가 열리지 않았습니다.")
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub save_config(UseCtr As String)
        Dim filepath As String
        Dim filename As String
        Dim objWriter As System.IO.StreamWriter
        Dim temStr As String

        On Error GoTo WR_File_Error

        filepath = System.AppDomain.CurrentDomain.BaseDirectory() & "\config"

        '디렉토리가 없을 경우
        If Dir(filepath, vbDirectory) = "" Then
            MkDir(filepath)
        End If

        filename = filepath & "\" & "QC_Component_Config" & ".ini"

        temStr = temStr + UseCtr + vbCrLf

        System.IO.File.Delete(filename)
        objWriter = New System.IO.StreamWriter(filename, True)
        objWriter.Flush()
        objWriter.WriteLine(temStr)

        objWriter.Close()
        Exit Sub

WR_File_Error:
        MsgBox("Config Save Fail!")

    End Sub

    Private Function CheckDevConnection(chNum As Integer) As Boolean
        Try
            If SerialPort1.IsOpen = True Then
                If DevConnectFlag(chNum) = False Then
                    DevPowerONFlag(chNum) = False
                    tmpCmdMessage = "chkpwron"
                    cmdMessage = "[" & tmpCmdMessage & " " & chNum & "]" + vbCrLf
                    SendData(cmdMessage)

                Else
                    tmpCmdMessage = "dsfwver"
                    cmdMessage = "[" & tmpCmdMessage & " " & chNum & "]" + vbCrLf
                    SendData(cmdMessage)

                End If
            Else
                MsgBox("통신 포트가 열리지 않았습니다.")
                Return True
            End If
        Catch ex As Exception
            Return True
        End Try
    End Function
    Private Sub cmdTimer_Tick(sender As System.Object, e As System.EventArgs) Handles cmdTimer.Tick
        Dim dispStr As String

        If SerialPort1.IsOpen = True Then
            ReceiveData()
            For i = 1 To 10
                If btnRun(i).Text = "시작" Then
                    If EnableRunConnect(i) = True Then
                        If ConnTimeoutCnt(i) >= ConnTimeout Then
                            ConnTimeoutCnt(i) = 0
                            EnableRunConnect(i) = False
                            cmdAutoPowerOn(i)
                        End If
                        ConnTimeoutCnt(i) += 1
                    End If
                ElseIf btnRun(i).Text = "중지" Then
                    If txbCmdWindow(i).Text = "" And RunTime(i) >= 20 Then ''20
                        cmdRunButton(i)
                        txbInfoBox(i).Text = "에러"
                        txbInfoBox(i).BackColor = Color.DarkOrange
                        txbInfoBox(i).Refresh()
                        dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "ERROR"
                        Save_CSV(i, dispStr)
                    End If

                    If preVal(i) = Val(txbShotCnt(i).Text) Then
                        If (RunTime(i) - preCnt(i)) >= 35 Then ''35
                            cmdRunButton(i)
                            txbInfoBox(i).Text = "에러"
                            txbInfoBox(i).BackColor = Color.Aquamarine
                            txbInfoBox(i).Refresh()
                            dispStr = (Format(TimeOfDay, "HH:mm:ss")) & "," & "ERROR"
                            Save_CSV(i, dispStr)
                        End If
                    Else
                        preVal(i) = Val(txbShotCnt(i).Text)
                        preCnt(i) = RunTime(i)
                    End If

                End If
            Next
        End If
    End Sub

    Private Sub btnRunButton1_Click(sender As System.Object, e As System.EventArgs) Handles btnRun1.Click
        Dim chNum As Integer = 1
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)

        End If
    End Sub

    Private Sub btnRun2_Click(sender As System.Object, e As System.EventArgs) Handles btnRun2.Click
        Dim chNum As Integer = 2
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun3_Click(sender As System.Object, e As System.EventArgs) Handles btnRun3.Click
        Dim chNum As Integer = 3
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun4_Click(sender As System.Object, e As System.EventArgs) Handles btnRun4.Click
        Dim chNum As Integer = 4
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun5_Click(sender As System.Object, e As System.EventArgs) Handles btnRun5.Click
        Dim chNum As Integer = 5

        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)

        End If

    End Sub

    Private Sub btnRun6_Click(sender As System.Object, e As System.EventArgs) Handles btnRun6.Click
        Dim chNum As Integer = 6
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun7_Click(sender As System.Object, e As System.EventArgs) Handles btnRun7.Click
        Dim chNum As Integer = 7
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun8_Click(sender As System.Object, e As System.EventArgs) Handles btnRun8.Click
        Dim chNum As Integer = 8
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun9_Click(sender As System.Object, e As System.EventArgs) Handles btnRun9.Click
        Dim chNum As Integer = 9
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub

    Private Sub btnRun10_Click(sender As System.Object, e As System.EventArgs) Handles btnRun10.Click
        Dim chNum As Integer = 10
        If btnRun(chNum).Text = "시작" Then
            cmdRunButton(chNum)
        ElseIf btnRun(chNum).Text = "중지" Then
            cmdRunButton(chNum)
        End If
    End Sub
    Private Sub txbDevTemp_Click(sender As Object, e As EventArgs) Handles txbDevTemp.Click
        If txbDevTemp.ReadOnly = False Then txbDevTemp.Text = ""
    End Sub
    Private Sub txbCartTemp_Click(sender As Object, e As EventArgs) Handles txbCartTemp.Click
        If txbCartTemp.ReadOnly = False Then txbCartTemp.Text = ""
    End Sub

    Private Sub Save_CSV(ch As Integer, SaveData As String)
        Dim FilePath As String
        Dim syear As String
        Dim smonth As String
        Dim sday As String
        Dim FileCnt As Long
        Dim runFlag As Boolean = True


        Dim FileName As String

        Dim objWriter As System.IO.StreamWriter

        On Error GoTo WR_File_Error

        syear = DateAndTime.Year(Now)
        smonth = DateAndTime.Month(Now)
        sday = DateAndTime.Day(Now)

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "Dualsonic_Log"

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "Dualsonic_Log\" & DateAndTime.Year(Now) & "_" & DateAndTime.Month(Now) & "_" & DateAndTime.Day(Now)

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        FileName = FileSavePath(ch)

        'System.IO.File.Delete(FileName)
        objWriter = New System.IO.StreamWriter(FileName, True)
        objWriter.WriteLine(SaveData)

        objWriter.Close()

        Exit Sub

WR_File_Error:
        MsgBox("Aging Data Save Fail!")
    End Sub
    Private Sub Save_CSV_Dir(ch As Integer, SaveData As String)
        Dim FilePath As String
        Dim syear As String
        Dim smonth As String
        Dim sday As String
        Dim FileCnt As Long
        Dim runFlag As Boolean = True
        Dim FileName As String
        Dim FrontFileName As String
        Dim MainSN As String
        Dim CartSN As String

        Dim objWriter As System.IO.StreamWriter

        On Error GoTo WR_File_Error

        syear = DateAndTime.Year(Now)
        smonth = DateAndTime.Month(Now)
        sday = DateAndTime.Day(Now)

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "Dualsonic_Log"

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "Dualsonic_Log\" & DateAndTime.Year(Now) & "_" & DateAndTime.Month(Now) & "_" & DateAndTime.Day(Now)

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        If txbMainSN(ch).Text = "Click" Then
            MainSN = "DEV_NA"
        Else
            MainSN = txbMainSN(ch).Text
        End If

        If txbCartSN(ch).Text = "Click" Then
            CartSN = "CART_NA"
        Else
            CartSN = txbCartSN(ch).Text
        End If

        FrontFileName = FilePath & "\" & MainSN & "_" & CartSN & "_CH_" & Format(ch, "00")

        FileName = FrontFileName & ".CSV"

        Do
            If File.Exists(FileName) = True Then
                FileCnt = FileCnt + 1
                FileName = FrontFileName & "_" & FileCnt & ".CSV"
                runFlag = False
            Else
                runFlag = True
            End If
        Loop Until (runFlag)

        FileSavePath(ch) = FileName

        'System.IO.File.Delete(FileName)
        objWriter = New System.IO.StreamWriter(FileName, True)
        objWriter.WriteLine(SaveData)

        objWriter.Close()

        Exit Sub

WR_File_Error:
        MsgBox("Aging Data Save Fail!")
    End Sub
    Private Sub Read_ini()
        Dim FilePath As String
        Dim FileName As String
        Dim ConifgStr As String
        Dim DevTemp As String
        Dim ShotCount As String
        Dim CartTemp As String
        Dim objReader As System.IO.StreamReader

        On Error GoTo RD_File_Error

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "\Dualsonic Config"

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        FileName = FilePath & "\" & "DS_Config" & ".ini"

        If File.Exists(FileName) = True Then
            objReader = New System.IO.StreamReader(FileName, True)
            ConifgStr = objReader.ReadLine()
            objReader.Close()

            txbDevTemp.Text = Mid(ConifgStr, 1, InStr(ConifgStr, ",") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, ",") + 1, Len(ConifgStr))

            txbCartTemp.Text = Mid(ConifgStr, 1, InStr(ConifgStr, ",") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, ",") + 1, Len(ConifgStr))

            txb_limit.Text = Mid(ConifgStr, 1, InStr(ConifgStr, ",") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, ",") + 1, Len(ConifgStr))

            txb_minimum.Text = Mid(ConifgStr, 1, InStr(ConifgStr, "~") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, "~") + 1, Len(ConifgStr))

            txb_maximum.Text = Mid(ConifgStr, 1, InStr(ConifgStr, ",") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, ",") + 1, Len(ConifgStr))

            nudErrRange.Value = Mid(ConifgStr, 1, InStr(ConifgStr, ",") - 1)
            ConifgStr = Mid(ConifgStr, InStr(ConifgStr, ",") + 1, Len(ConifgStr))

            nudJigNum.Value = ConifgStr

        Else
            Save_ini()
        End If

        Exit Sub

RD_File_Error:
        MsgBox("Config Load Fail!")
    End Sub

    Private Sub Save_ini()
        Dim FilePath As String
        Dim FileName As String
        Dim ConifgStr As String
        Dim objWriter As System.IO.StreamWriter

        On Error GoTo WR_File_Error

        FilePath = System.AppDomain.CurrentDomain.BaseDirectory() & "\Dualsonic Config"

        '디렉토리가 없을 경우
        If Dir(FilePath, vbDirectory) = "" Then
            MkDir(FilePath)
        End If

        FileName = FilePath & "\" & "DS_Config" & ".ini"


        If txbDevTemp.Text = "" Then txbDevTemp.Text = 48.0
        If txbCartTemp.Text = "" Then txbCartTemp.Text = 48.0
        If txb_limit.Text = "" Then txb_limit.Text = 330
        If txb_maximum.Text = "" Then txb_maximum.Text = 300
        If txb_minimum.Text = "" Then txb_minimum.Text = 200
        If nudErrRange.Value.ToString = "" Then nudErrRange.Value = 4

        ConifgStr = txbDevTemp.Text & "," & txbCartTemp.Text & "," & txb_limit.Text & "," & txb_minimum.Text & "~" & txb_maximum.Text & "," & nudErrRange.Value.ToString & "," & nudJigNum.Value.ToString

        System.IO.File.Delete(FileName)
        objWriter = New System.IO.StreamWriter(FileName, True)

        objWriter.Flush()
        objWriter.WriteLine(ConifgStr)

        objWriter.Close()

        Exit Sub

WR_File_Error:
        MsgBox("Config Save Fail!")
    End Sub


    Private Sub txbMainSN1_Click(sender As Object, e As EventArgs) Handles txbMainSN1.Click
        txbMainSN1.Text = ""
    End Sub

    Private Sub txbCartSN1_Click(sender As Object, e As EventArgs) Handles txbCartSN1.Click
        txbCartSN1.Text = ""
    End Sub

    Private Sub txbMainSN2_Click(sender As Object, e As EventArgs) Handles txbMainSN2.Click
        txbMainSN2.Text = ""
    End Sub

    Private Sub txbCartSN2_Click(sender As Object, e As EventArgs) Handles txbCartSN2.Click
        txbCartSN2.Text = ""
    End Sub

    Private Sub txbMainSN3_Click(sender As Object, e As EventArgs) Handles txbMainSN3.Click
        txbMainSN3.Text = ""
    End Sub

    Private Sub txbCartSN3_Click(sender As Object, e As EventArgs) Handles txbCartSN3.Click
        txbCartSN3.Text = ""
    End Sub

    Private Sub txbMainSN4_Click(sender As Object, e As EventArgs) Handles txbMainSN4.Click
        txbMainSN4.Text = ""
    End Sub

    Private Sub txbCartSN4_Click(sender As Object, e As EventArgs) Handles txbCartSN4.Click
        txbCartSN4.Text = ""
    End Sub

    Private Sub txbMainSN5_Click(sender As Object, e As EventArgs) Handles txbMainSN5.Click
        txbMainSN5.Text = ""
    End Sub

    Private Sub txbCartSN5_Click(sender As Object, e As EventArgs) Handles txbCartSN5.Click
        txbCartSN5.Text = ""
    End Sub


    Private Sub txbMainSN6_Click(sender As Object, e As EventArgs) Handles txbMainSN6.Click
        txbMainSN6.Text = ""
    End Sub
    Private Sub txbCartSN6_Click(sender As Object, e As EventArgs) Handles txbCartSN6.Click
        txbCartSN6.Text = ""
    End Sub

    Private Sub txbMainSN7_Click(sender As Object, e As EventArgs) Handles txbMainSN7.Click
        txbMainSN7.Text = ""
    End Sub

    Private Sub txbCartSN7_Click(sender As Object, e As EventArgs) Handles txbCartSN7.Click
        txbCartSN7.Text = ""
    End Sub

    Private Sub txbMainSN8_Click(sender As Object, e As EventArgs) Handles txbMainSN8.Click
        txbMainSN8.Text = ""
    End Sub

    Private Sub txbCartSN8_Click(sender As Object, e As EventArgs) Handles txbCartSN8.Click
        txbCartSN8.Text = ""
    End Sub

    Private Sub txbMainSN9_Click(sender As Object, e As EventArgs) Handles txbMainSN9.Click
        txbMainSN9.Text = ""
    End Sub

    Private Sub txbCartSN9_Click(sender As Object, e As EventArgs) Handles txbCartSN9.Click
        txbCartSN9.Text = ""
    End Sub

    Private Sub txbMainSN10_Click(sender As Object, e As EventArgs) Handles txbMainSN10.Click
        txbMainSN10.Text = ""
    End Sub

    Private Sub txbCartSN10_Click(sender As Object, e As EventArgs) Handles txbCartSN10.Click
        txbCartSN10.Text = ""
    End Sub

    Private Sub NoUseAutoPwrOn(ChNum As Integer)
        tmpCmdMessage = "chgpinon"
        cmdMessage = "[" & tmpCmdMessage & " " & ChNum & ",0]" + vbCrLf
        SendData(cmdMessage)

        tmpCmdMessage = "idpinon"
        cmdMessage = "[" & tmpCmdMessage & " " & ChNum & ",1]" + vbCrLf
        SendData(cmdMessage)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For cnt = 1 To CNT_CH
            cmdRunButton(cnt)
            Threading.Thread.Sleep(30)
        Next cnt
    End Sub

    Private Sub btn_shot_Click(sender As Object, e As EventArgs) Handles btn_shot.Click
        gb_shot_range.Location = New Point(1180, 12)
        gb_shot_range.Size = New Size(533, 75)
        gb_shot_range.Visible = True
        gb_limit.Visible = False
    End Sub

    Private Sub btn_shot_ok_Click(sender As Object, e As EventArgs) Handles btn_shot_ok.Click
        gb_shot_range.Visible = False
        Save_ini()
    End Sub

    Private Sub txb_minimum_Click(sender As Object, e As EventArgs) Handles txb_minimum.Click
        If txb_minimum.ReadOnly = False Then txb_minimum.Text = ""
    End Sub

    Private Sub nudJigNum_ValueChanged(sender As Object, e As EventArgs) Handles nudJigNum.ValueChanged
        If StartSwitch = True Then
            Save_ini()
        Else
            StartSwitch = True
        End If
    End Sub

    Private Sub txb_maximum_Click(sender As Object, e As EventArgs) Handles txb_maximum.Click
        If txb_maximum.ReadOnly = False Then txb_maximum.Text = ""
    End Sub

    Private Sub btn_limit_Click(sender As Object, e As EventArgs) Handles btn_limit.Click
        gb_limit.Location = New Point(1180, 12)
        gb_limit.Size = New Size(533, 75)
        gb_limit.Visible = True
        gb_shot_range.Visible = False
    End Sub

    Private Sub btn_limit_save_Click(sender As Object, e As EventArgs) Handles btn_limit_save.Click
        gb_limit.Visible = False
        Save_ini()
    End Sub
End Class