Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Threading
Imports System
Imports Snap7
Imports Keyence.AutoID.SDK
Imports System.Diagnostics.Eventing
Imports System.Data.OleDb
Public Class Form1
    Dim AppSettings = ConfigurationManager.AppSettings
    Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim ConnDB As New SqlConnection(ConfigurationManager.ConnectionStrings("DBSQL_Traceability").ConnectionString)
    Dim ConnDBA As New OleDbConnection(ConfigurationManager.ConnectionStrings("DBA_Recipt").ConnectionString)

    Dim ClientS7 As Snap7.S7Client

    Dim m_reader As ReaderAccessor = New ReaderAccessor()

    Dim stcamconn As String

    Dim ReaderErrorCode(99) As String

    Dim dtca, dtmodel As New DataTable
    Dim Qrcode, EvaDescription, Joint, ResQR, ResDB, ResSC, ResALL, DatetimeTrigger As String
    Dim ResModel, ResJoint, Aux1, Aux2, Aux3, Aux4 As Integer
    Dim CoreH, CoreW As Single
    Dim countreadok, countreadko, countdbok, countdbko, countscok, countscko, flagdtcount, plcstatus As Integer

    Dim ThrendPLCrw As Threading.Thread
    Dim ThrendMainProcess As Threading.Thread
    Dim ThrendStartShift As Threading.Thread

    Delegate Sub UpdateFormDelegate()
    Public UpdateForm As UpdateFormDelegate
    Dim objlockdt As New Object

    Private Structure StructFromPLC
        Public BitLife As Boolean
        Public DataRequest As Boolean
    End Structure

    Private Structure StructToPLC
        Public BitLife As Boolean
        Public DataReady As Boolean
        Public ResQRRead As Integer
        Public ResModel As Integer
        Public ResOverall As Integer
        Public CoreH As Single
        Public CoreW As Single
        Public ResJoint As Integer
        Public Aux1 As Integer
        Public Aux2 As Integer
        Public Aux3 As Integer
        Public Aux4 As Integer
        Public QRCode As String
        Public Description As String
        Public joint As String
    End Structure

    Dim FromPLC As New StructFromPLC
    Dim ToPLC As New StructToPLC


    Public Sub New()
        InitializeComponent()
        ClientS7 = New S7Client
        If IntPtr.Size = 4 Then
            Text = Text + " - Esecuzione Codice a 32 bit"
        Else
            Text = Text + " - Esecuzione Codice a 64 bit"
        End If
    End Sub

    Sub PLCrw()
        Dim ReadBuff(30) As Byte
        Dim WriteBuff(72) As Byte
        Dim DbPLC As Integer


        Try
            DbPLC = CInt(AppSettings("DB_COMM"))
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

        Do
            ClientS7.PlcGetStatus(plcstatus)

            SyncLock objlockdt

                If plcstatus = 8 Then
                    'Read Data DB From PLC
                    ClientS7.DBRead(DbPLC, 72, 30, ReadBuff)
                    FromPLC.BitLife = S7.GetBitAt(ReadBuff, 0, 0)
                    FromPLC.DataRequest = S7.GetBitAt(ReadBuff, 0, 4)

                    'Write Data DB To PLC
                    S7.SetBitAt(WriteBuff, 0, 0, ToPLC.BitLife)
                    S7.SetBitAt(WriteBuff, 0, 4, ToPLC.DataReady)
                    S7.SetIntAt(WriteBuff, 2, ToPLC.ResQRRead)
                    S7.SetIntAt(WriteBuff, 4, ToPLC.ResModel)
                    S7.SetIntAt(WriteBuff, 6, ToPLC.ResOverall)
                    S7.SetRealAt(WriteBuff, 8, ToPLC.CoreH)
                    S7.SetRealAt(WriteBuff, 12, ToPLC.CoreW)
                    S7.SetIntAt(WriteBuff, 16, ToPLC.ResJoint)
                    S7.SetIntAt(WriteBuff, 18, ToPLC.Aux1)
                    S7.SetIntAt(WriteBuff, 20, ToPLC.Aux2)
                    S7.SetIntAt(WriteBuff, 22, ToPLC.Aux3)
                    S7.SetIntAt(WriteBuff, 24, ToPLC.Aux4)
                    S7.SetStringAt(WriteBuff, 26, 10, Strings.Left(ToPLC.QRCode, 10))
                    S7.SetStringAt(WriteBuff, 38, 20, Strings.Left(ToPLC.Description, 20))
                    S7.SetStringAt(WriteBuff, 60, 10, Strings.Left(ToPLC.joint, 10))
                    ClientS7.DBWrite(DbPLC, 0, 72, WriteBuff)
                Else
                    ClientS7.Connect()
                End If

            End SyncLock

            Threading.Thread.Sleep(200)

        Loop
    End Sub
    Sub StartShift()

        Do
            If (AppSettings("RES_COUNT_ST_SHIFT") = "True") And (Hour(Now) = 6 Or Hour(Now) = 14 Or Hour(Now) = 22) And Minute(Now) = 0 Then
                countreadok = 0
                countreadko = 0
                countdbok = 0
                countdbko = 0
                countscok = 0
                countscko = 0
                flagdtcount = 2
            End If
            Threading.Thread.Sleep(60 * 1000)
        Loop

    End Sub
    Sub MainProcess()
        'INIT
        Dim OnsRequest As Boolean = False
        Dim TimeoutLON As Int32

        TimeoutLON = CInt(AppSettings("TIMEOUT_LON"))

        'MAIN
        Do


            If FromPLC.DataRequest = True And OnsRequest = False Then

                SyncLock objlockdt

                    OnsRequest = True


                    Qrcode = ""
                    EvaDescription = "                    "
                    Joint = "          "
                    CoreH = 0.0
                    CoreW = 0.0
                    ResQR = ""
                    ResDB = ""
                    ResSC = ""
                    ResModel = 0
                    ResJoint = 0
                    Aux1 = 0
                    Aux2 = 0
                    Aux3 = 0
                    Aux4 = 0
                    ResALL = ""
                    DatetimeTrigger = ""

                    DataGridViewFnd.DataSource = Nothing

                    dtca.Clear()
                    dtca.Rows.Clear()
                    dtca.Columns.Clear()


                    DatetimeTrigger = DateTime.Now

                    stcamconn = m_reader.ExecCommand("KEYENCE")
                    stcamconn = Strings.Left(stcamconn, 2)

                    If stcamconn = "OK" Then
                        Qrcode = m_reader.ExecCommand("LON", TimeoutLON)
                        Qrcode = Strings.Left(Qrcode, 10)
                    Else
                        If AppSettings("LOG_REC") = "True" Then
                            LogWrite("Errore Connessione Camera ora: " & DateTime.Now)
                        End If
                        CAMERA_Connect()
                    End If


                    If Len(Qrcode) >= 1 Then
                        ResQR = "OK"



                        Using cmd As New SqlCommand("Select id, serialnumber, station, id_model, datetime, scrap_codes From workings Where (station = 'CORE1' OR station = 'CORE2') AND serialnumber = '" & Qrcode & "' Order by id asc", ConnDB)
                            Try
                                ConnDB.Open()
                                Dim readca As SqlDataReader = cmd.ExecuteReader()
                                If readca.HasRows Then
                                    dtca.Load(readca)
                                    ResDB = "OK"
                                    Try
                                        If dtca.Rows(0).Item(1) = dtca.Rows(1).Item(1) Then
                                            ResSC = "KO"
                                        End If
                                    Catch ex As Exception
                                        ResSC = "OK"
                                        ResModel = dtca.Rows(0).Item(3)
                                    End Try

                                    dtca.Columns(0).ColumnName = "id"
                                    dtca.Columns(1).ColumnName = "QR_Code"
                                    dtca.Columns(2).ColumnName = "macchina"
                                    dtca.Columns(3).ColumnName = "modello"
                                    dtca.Columns(4).ColumnName = "data ora"
                                    dtca.Columns(5).ColumnName = "scarto"

                                Else
                                    ResDB = "KO"
                                    ResSC = "ND"

                                    dtca.Columns.Add()
                                    dtca.Rows.Add()
                                    dtca.Columns(0).ColumnName = "Info"
                                    dtca.Rows(0).Item(0) = "Dati Non Trovati per QR: " & Qrcode

                                End If

                            Catch ex As Exception
                                MessageBox.Show(ex.Message)
                            Finally
                                ConnDB.Close()
                            End Try

                        End Using


                    Else
                        m_reader.ExecCommand("LOFF")
                        ResQR = "KO"
                        Qrcode = "          "
                    End If


                    'Take data from recipt
                    Try

                        If ResModel <> 0 Then

                            Dim DataRecipt() As DataRow = dtmodel.Select("Codice = " & ResModel & "")

                            If Not DataRecipt Is Nothing Then

                                EvaDescription = DataRecipt(0).Item(1)
                                Joint = DataRecipt(0).Item(4)

                                CoreH = DataRecipt(0).Item(2)
                                CoreW = DataRecipt(0).Item(3)

                                Select Case DataRecipt(0).Item(4)
                                    Case "STD-R"
                                        ResJoint = 1
                                    Case "STD-L"
                                        ResJoint = 2
                                    Case "BLOCK-P"
                                        ResJoint = 3
                                    Case "BLOCK-Q"
                                        ResJoint = 4
                                    Case "PLUMBING-P"
                                        ResJoint = 5
                                    Case "PLUMBING-Q"
                                        ResJoint = 6
                                    Case "SHORT-R"
                                        ResJoint = 7
                                    Case "SHORT-L"
                                        ResJoint = 8
                                    Case Else
                                        ResJoint = 0
                                End Select

                                If ResModel <> 0 And ResQR = "OK" And ResSC = "OK" Then
                                    ResALL = "OK"
                                End If

                                Aux1 = DataRecipt(0).Item(5)
                                Aux2 = DataRecipt(0).Item(6)
                                Aux3 = DataRecipt(0).Item(7)
                                Aux4 = DataRecipt(0).Item(8)

                            Else
                                ResALL = "KO"
                            End If

                        End If

                    Catch ex As Exception
                        MessageBox.Show(ex.Message)
                    End Try


                    'Write Result to PLC
                    If ResQR = "OK" Then
                        ToPLC.ResQRRead = 1
                    Else
                        ToPLC.ResQRRead = 2
                    End If

                    If ResALL = "OK" Then
                        ToPLC.ResOverall = 1
                    Else
                        ToPLC.ResOverall = 2
                    End If

                    ToPLC.ResModel = ResModel
                    ToPLC.ResJoint = ResJoint

                    ToPLC.CoreH = CoreH
                    ToPLC.CoreW = CoreW

                    ToPLC.Aux1 = Aux1
                    ToPLC.Aux2 = Aux2
                    ToPLC.Aux3 = Aux3
                    ToPLC.Aux4 = Aux4

                    ToPLC.QRCode = Strings.Left(Qrcode, 10)
                    ToPLC.Description = Strings.Left(EvaDescription, 20)
                    ToPLC.joint = Strings.Left(Joint, 10)


                    'Increase Counter
                    If ResQR = "OK" Then
                        countreadok = countreadok + 1
                    ElseIf ResQR = "KO" Then
                        countreadko = countreadko + 1
                    End If

                    If ResDB = "OK" Then
                        countdbok = countdbok + 1
                    ElseIf ResDB = "KO" Then
                        countdbko = countdbko + 1
                    End If

                    If ResSC = "OK" Then
                        countscok = countscok + 1
                    ElseIf ResSC = "KO" Then
                        countscko = countscko + 1
                    End If


                    ToPLC.DataReady = True

                    If AppSettings("LOG_REC") = "True" Then
                        LogWrite(Qrcode & ";" & ResQR & ";" & ResSC)
                    End If

                End SyncLock

            End If

            If FromPLC.DataRequest = False Then
                OnsRequest = False
                ToPLC.DataReady = False
            End If

            Threading.Thread.Sleep(200)
            SubUpdateForm()

        Loop


    End Sub


    Private Sub LogWrite(ByVal Testo As String)
        Dim strdate As String
        strdate = DateTime.Now.ToString("dd-MM-yyyy")

        Try

            If Not System.IO.Directory.Exists(My.Application.Info.DirectoryPath & "\Log") Then
                System.IO.Directory.CreateDirectory(My.Application.Info.DirectoryPath & "\Log")
            End If

            If Not System.IO.File.Exists(My.Application.Info.DirectoryPath & "\Log\Log_" & strdate & ".txt") Then
                My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\Log\Log_" & strdate & ".txt",
                "Datetime; QR_Code; QR Read Result; QR Single Result" & vbCrLf, True)
            End If

            My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\Log\Log_" & strdate & ".txt",
            DateTime.Now.ToString("dd\/MM\/yyyy HH\:mm\:ss") & " " & Testo & vbCrLf, True)

        Catch ex As Exception

            MessageBox.Show("LogWrite: " & ex.Message)

        End Try

    End Sub

    Sub CloseProcess()
        ThrendMainProcess.Abort()
        ThrendStartShift.Abort()
        If ThrendPLCrw Is Nothing = False Then
            ThrendPLCrw.Abort()
        End If
        PLC_Disconnect()
        CAMERA_Disconnect()
        liveviewForm1.Dispose()
    End Sub

    Private Sub form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        e.Cancel = True
    End Sub

    Private Sub ChiudiToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChiudiToolStripMenuItem.Click
        Select Case MsgBox("Sei Sicuro Di Volere Chiudere L'Applicazione?", MsgBoxStyle.YesNoCancel, "Chiusura Applicazione")
            Case MsgBoxResult.Yes
                CloseProcess()
                Application.Exit()
        End Select
    End Sub

    Private Sub RicetteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RicetteToolStripMenuItem.Click
        FormRicette.ShowDialog()
    End Sub

    Private Sub SettingToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingToolStripMenuItem.Click
        FormSetting.ShowDialog()
    End Sub


    Public Sub PLC_Connect()
        Dim Result As Integer
        Dim Rack As Integer = System.Convert.ToInt32(AppSettings("PLC_RACK"))
        Dim Slot As Integer = System.Convert.ToInt32(AppSettings("PLC_SLOT"))
        Result = ClientS7.ConnectTo(AppSettings("PLC_IP"), Rack, Slot)

        If ClientS7.ErrorText(Result) = "OK" Then
            ConnettiToolStripMenuItem.Enabled = False
            DisconnettiToolStripMenuItem.Enabled = True
            ThrendPLCrw = New Threading.Thread(AddressOf PLCrw)
            ThrendPLCrw.Start()
        Else
            ConnettiToolStripMenuItem.Enabled = True
            DisconnettiToolStripMenuItem.Enabled = False
            MsgBox(ClientS7.ErrorText(Result))
        End If
    End Sub

    Public Sub PLC_Disconnect()
        Try
            If ThrendPLCrw.IsAlive Then
                ThrendPLCrw.Abort()
            End If
            ClientS7.Disconnect()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Exit Sub
        End Try
        ConnettiToolStripMenuItem.Enabled = True
        DisconnettiToolStripMenuItem.Enabled = False
    End Sub

    Public Sub CAMERA_Connect()
        Dim stconn As Boolean
        Try
            'Stop liveview.
            liveviewForm1.EndReceive()
            'Set ip address of liveview.
            liveviewForm1.IpAddress = AppSettings("CAMERA_IP")
            'Start liveview.
            liveviewForm1.BeginReceive()

            'Set ip address of ReaderAccessor.
            m_reader.IpAddress = AppSettings("CAMERA_IP")
            'Connect TCP/IP.
            'm_reader.Connect(AddressOf ReceivedDataAction)
            stconn = m_reader.Connect()
            If stconn = True Then
                stcamconn = "OK"
            Else
                stcamconn = "KO"
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Public Sub CAMERA_Disconnect()
        'Dispose before closing Form for avoiding error.
        liveviewForm1.EndReceive()
        m_reader.ExecCommand("LOFF")
        m_reader.Disconnect()
        m_reader.Dispose()

        stcamconn = "KO"
    End Sub


    Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False

        'Initialize Reader Error List
        ReaderErrorCode(0) = "Comando non definito ricevuto"
        ReaderErrorCode(1) = "Formato del comando non corrispondente (numero di parametri non valido)"
        ReaderErrorCode(2) = "Il valore del parametro 1 supera il valore impostato"
        ReaderErrorCode(3) = "Il valore del parametro 2 supera il valore impostato"
        ReaderErrorCode(4) = "Il parametro 2 non è impostato nel codice HEX (esadecimale)"
        ReaderErrorCode(5) = "Parametro 2 impostato in codice HEX (esadecimale) ma supera il valore impostato"
        ReaderErrorCode(10) = "Ce ne sono 2 o più! contrassegni nei dati preimpostati i dati preimpostati non sono corretti"
        ReaderErrorCode(11) = "I dati di specifica dell'area non sono corretti"
        ReaderErrorCode(12) = "Il file specificato non esiste"
        ReaderErrorCode(13) = """mm"" per il comando% Tmm-LON, bb supera l'intervallo di impostazione."
        ReaderErrorCode(14) = "Impossibile controllare la comunicazione con il comando% Tmm-KEYENCE."
        ReaderErrorCode(20) = "Questo comando non è eseguibile nello stato corrente (errore di esecuzione)"
        ReaderErrorCode(21) = "Il buffer è andato in overflow, quindi i comandi non possono essere eseguiti"
        ReaderErrorCode(22) = "Si è verificato un errore durante il caricamento o il salvataggio dei parametri, quindi i comandi non possono essere eseguito"
        ReaderErrorCode(23) = "I comandi inviati da RS-232C non possono essere ricevuti perché AutoID Network Il navigatore è in fase di connessione."
        ReaderErrorCode(99) = "Il Lettore SR-2000 potrebbe essere difettoso. Contatta l'ufficio vendite KEYENCE più vicino."


        'Read Model
        Try
            Dim strquery As String
            ConnDBA.Open()
            strquery = "SELECT * FROM Modelli order by Codice asc"
            Dim QCommand As New OleDbCommand(strquery, ConnDBA)
            Dim InsRead = QCommand.ExecuteReader
            dtmodel.Load(InsRead)
            ConnDBA.Close()
        Catch ex As Exception
            MessageBox.Show("Errore Lettura Database Ricette: " & ex.Message)
            Application.Exit()
        End Try


        ThrendMainProcess = New Threading.Thread(AddressOf MainProcess)
        ThrendMainProcess.Start()

        ThrendStartShift = New Threading.Thread(AddressOf StartShift)
        ThrendStartShift.Start()

        PLC_Connect()

        CAMERA_Connect()

        flagdtcount = 1

    End Sub


    Public Sub SubUpdateForm()

        If Me.InvokeRequired Then
            UpdateForm = New UpdateFormDelegate(AddressOf SubUpdateForm)
            Me.BeginInvoke(UpdateForm)
        Else

            SyncLock objlockdt
                'Label Last Acquisition
                LabelUAStDTTrigger.Text = DatetimeTrigger

                If ResQR = "KO" Then
                    LabelUAStQRCode.Text = "Timeout Lettura QR Code"
                Else
                    LabelUAStQRCode.Text = Qrcode
                End If

                LabelUAStResSCQRcode.Text = ResSC

                Select Case ResSC
                    Case = "OK"
                        LabelUAStDescSCQRcode.Text = "QR Singolo"
                    Case = "KO"
                        LabelUAStDescSCQRcode.Text = "QR Ripetuto"
                    Case = "ND"
                        LabelUAStDescSCQRcode.Text = "Dati non presenti"
                    Case Else
                        LabelUAStDescSCQRcode.Text = ""
                End Select


                'Label Recipt

                If ResModel = 0 Then
                    LabelUAStCodMod.Text = ""
                    LabelUAStDescMod.Text = ""
                    LabelUAStDescMod.Text = ""
                    LabelUAStCoreH.Text = ""
                    LabelUAStCoreW.Text = ""
                    LabelUAStCodJoint.Text = ""
                    LabelUAStDescJoint.Text = ""
                    LabelUAStAux1.Text = ""
                    LabelUAStAux2.Text = ""
                    LabelUAStAux3.Text = ""
                    LabelUAStAux4.Text = ""
                Else
                    LabelUAStCodMod.Text = ResModel
                    LabelUAStDescMod.Text = EvaDescription
                    LabelUAStCoreH.Text = CoreH
                    LabelUAStCoreW.Text = CoreW
                    LabelUAStCodJoint.Text = ResJoint
                    LabelUAStDescJoint.Text = Joint
                    LabelUAStAux1.Text = Aux1
                    LabelUAStAux2.Text = Aux2
                    LabelUAStAux3.Text = Aux3
                    LabelUAStAux4.Text = Aux4
                End If


                'Label CAMERA

                If stcamconn = "OK" Then
                    LabelLettStConn.Text = "OK"
                    LabelLettStConn.BackColor = Color.FromArgb(128, 255, 128)
                Else
                    LabelLettStConn.Text = "KO"
                    LabelLettStConn.BackColor = Color.FromArgb(255, 128, 128)
                End If

                'Label PLC

                If plcstatus = 8 Then
                    'Status PLC Conneciton
                    LabelPLCStConn.Text = "OK"
                    LabelPLCStConn.BackColor = Color.FromArgb(128, 255, 128)

                    'Bitlife From PLC
                    If FromPLC.BitLife = True Then
                        LabelPLCStBitlife.Text = "_|¯"
                        LabelPLCStBitlife.BackColor = Color.FromArgb(128, 255, 128)
                    Else
                        LabelPLCStBitlife.Text = "¯|_"
                        LabelPLCStBitlife.BackColor = Color.Silver
                    End If
                    'Trigger From PLC
                    If FromPLC.DataRequest = True Then
                        LabelPLCStTrigger.Text = "1"
                        LabelPLCStTrigger.BackColor = Color.FromArgb(128, 255, 128)
                    Else
                        LabelPLCStTrigger.Text = "0"
                        LabelPLCStTrigger.BackColor = Color.Silver
                    End If
                    'Data Ready To PLC
                    If ToPLC.DataReady = True Then
                        LabelPLCStDataReady.Text = "1"
                        LabelPLCStDataReady.BackColor = Color.FromArgb(128, 255, 128)
                    Else
                        LabelPLCStDataReady.Text = "0"
                        LabelPLCStDataReady.BackColor = Color.Silver
                    End If

                Else
                    LabelPLCStConn.Text = "KO"
                    LabelPLCStConn.BackColor = Color.FromArgb(255, 128, 128)

                    LabelPLCStBitlife.Text = "/"
                    LabelPLCStBitlife.BackColor = Color.Silver

                    LabelPLCStTrigger.Text = "/"
                    LabelPLCStTrigger.BackColor = Color.Silver

                    LabelPLCStDataReady.Text = "/"
                    LabelPLCStDataReady.BackColor = Color.Silver
                End If


                'Update Datagridview
                DataGridViewFnd.DataSource = dtca
                DataGridViewFnd.AutoResizeColumns()


                'Update Chart
                ChartCountResult.Series("OK").Points.Clear()
                ChartCountResult.Series("KO").Points.Clear()
                ChartCountResult.Series("OK").Points.AddXY("DB Find", countdbok)
                ChartCountResult.Series("KO").Points.AddXY("DB Find", countdbko)
                ChartCountResult.Series("OK").Points.AddXY("Sing. QR", countscok)
                ChartCountResult.Series("KO").Points.AddXY("Sing. QR", countscko)
                ChartCountResult.Series("OK").Points.AddXY("Letti", countreadok)
                ChartCountResult.Series("KO").Points.AddXY("Letti", countreadko)

                'Update Last Reset Chart
                If flagdtcount <> 0 Then
                    Select Case flagdtcount
                        Case 1
                            LabelCountResultReset.Text = "Ultimo Avvio: " & DateTime.Now
                        Case 2
                            LabelCountResultReset.Text = "Reset Inizio Turno: " & Hour(Now) & ":" & Minute(Now)
                        Case 3
                            LabelCountResultReset.Text = "Ultimo Reset Manuale: " & DateTime.Now
                    End Select
                    flagdtcount = 0
                End If
            End SyncLock
        End If


    End Sub

    Private Sub TimerBitlife_Tick(sender As Object, e As EventArgs) Handles TimerBitlife.Tick
        If ToPLC.BitLife = False Then
            ToPLC.BitLife = True
        Else
            ToPLC.BitLife = False
        End If
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        MessageBox.Show(
                "Applicazione: QRCode Evaporator Search" & vbCrLf &
                "Versione: 1.0" & vbCrLf &
                "Sviluppatore: Vincenzo Niespolo" & vbCrLf &
                "Email: niespotech@gmail.com" & vbCrLf &
                "Cell: +39 3349113322"
                )
    End Sub
    Private Sub ButtonChartReset_Click(sender As Object, e As EventArgs) Handles ButtonChartReset.Click
        countreadok = 0
        countreadko = 0
        countdbok = 0
        countdbko = 0
        countscok = 0
        countscko = 0
        ChartCountResult.Series("OK").Points.Clear()
        ChartCountResult.Series("KO").Points.Clear()

        flagdtcount = 3

    End Sub
    Private Sub ConnettiToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ConnettiToolStripMenuItem.Click
        PLC_Connect()
    End Sub
    Private Sub DisconnettiToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DisconnettiToolStripMenuItem.Click
        PLC_Disconnect()
    End Sub
    Private Sub ConnettiToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ConnettiToolStripMenuItem1.Click
        CAMERA_Connect()
    End Sub
    Private Sub DisconnettiToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles DisconnettiToolStripMenuItem1.Click
        CAMERA_Disconnect()
    End Sub
    Private Sub EseguiToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles EseguiToolStripMenuItem1.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("TEST1")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Test Lettura Abilitato")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If

    End Sub
    Private Sub EsciToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EsciToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("QUIT")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Modalità Test Lettura Terminata")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub
    Private Sub RiavviaLettoreToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RiavviaLettoreToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("RESET")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Reset Lettore Eseguito")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If

    End Sub
    Private Sub AutofocusToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AutofocusToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("FTUNE")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Autofocus Abilitato")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If

    End Sub
    Private Sub VersioneLettoreToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VersioneLettoreToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("KEYENCE")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show(errsplt(1) & " " & errsplt(2) & " Versione: " & errsplt(3))
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub

    Private Sub FiltroPolarizzanteAbilitatoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FiltroPolarizzanteAbilitatoToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("VCALIB,1")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Calibrazione Abilitata")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub

    Private Sub FiltroPolarizzanteDisabilitatoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FiltroPolarizzanteDisabilitatoToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("VCALIB,2")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Calibrazione Abilitata")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub

    Private Sub TuttiGliIlluminatoriAlilitatiToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TuttiGliIlluminatoriAlilitatiToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("VCALIB,3")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("Calibrazione Abilitata")
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub
    Private Sub MACAddressLettoreToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MACAddressLettoreToolStripMenuItem.Click
        Dim fbkstr As String
        Dim errsplt() As String

        fbkstr = m_reader.ExecCommand("EMAC")
        errsplt = Strings.Split(fbkstr, ",")

        If errsplt(0) = "OK" Then
            MessageBox.Show("MAC Address: " & errsplt(2))
        ElseIf errsplt(0) = "ER" Then
            MessageBox.Show(ReaderErrorCode(CInt(errsplt(2))))
        ElseIf errsplt(0) = "" Then
            MessageBox.Show("Errore, Nessuna risposta dal Lettore QR")
        End If
    End Sub

End Class
