Public Class frmSmaFingerTester
    Public WithEvents m_oSFReader As GIGATMS.SFReader  'GIGATMS.SFReader       'SmaFinger Reader Object
    Public WithEvents m_oMFReader As GIGATMS.NCF.SFMAD          'PCR310U Reader Object
    Private WithEvents m_oFPEnrollResult As clsResult           'return Enroll Finger Result Class
    Private WithEvents m_oFPVerifyResult As clsResult           'return Verify Finger Result Class
    Private WithEvents m_oFPIdentifyResult As clsResult         'return Indentify Finger Result Class
    Private WithEvents m_oFPEnrollResult2 As clsResult          'return Enroll Finger for Issue Card Result Class

    Private m_bIsShowFinger As Boolean, m_iFingerID As Integer, m_lFingerBufferCount As Long, m_iIssueMachine As Integer, m_bFingerBuffers() As Byte
    Private m_bAuto As Boolean                                  'Auto Testing
    Public m_bTCFingerClose As Boolean                          'to Close Enroll Window
    Private m_szAutoStep As String                              'Store current Step of Auto Testing
    Private m_szAppTitle As String                              'Application Title
    Private m_szSetPort As String
    Private m_iNewRID As Integer
    Private m_bContinuePolling As Boolean, m_bPolling As Boolean
    Private m_bUserData() As Byte

    Private Const FINGER_NO_FOR_TEST As Integer = 1

    Class ReaderContent
        Private iRID As Integer
        Private bXID(3) As Byte
        Private iBufferCount As Integer
        Private bBuffer() As Byte
        Private iCheckPolling As Integer
        Public Sub New(ByVal iXID As Integer)
            XIDInt = iXID
        End Sub
        Public Sub New(ByVal szXID As String)
            XIDStr = szXID
        End Sub
        Public Property RID() As Integer
            Get
                Return iRID
            End Get
            Set(ByVal value As Integer)
                iRID = value
            End Set
        End Property
        Public Property XID() As Byte()
            Get
                Return bXID
            End Get
            Set(ByVal value As Byte())
                If value.Length = 4 Then
                    Array.Copy(value, bXID, 4)
                End If
            End Set
        End Property
        Public Property XIDStr() As String
            Get
                Dim szResult As String
                szResult = System.BitConverter.ToString(bXID, 0, 4)
                Return Replace(szResult, "-", "")
            End Get
            Set(ByVal value As String)
                If Val("&H" & value) <> 0 Then
                    Dim bValue() As Byte
                    bValue = System.BitConverter.GetBytes(Val("&H" & value))
                    Array.Reverse(bValue)
                    Array.Copy(bValue, bValue.Length - 4, bXID, 0, 4)
                End If
            End Set
        End Property
        Public Property XIDInt() As Integer
            Get
                Dim bValue(3) As Byte
                Array.Copy(bXID, bValue, 4)
                Array.Reverse(bValue)
                Return System.BitConverter.ToInt32(bValue, 0)
            End Get
            Set(ByVal value As Integer)
                Dim bValue() As Byte
                bValue = System.BitConverter.GetBytes(value)
                Array.Reverse(bValue)
                Array.Copy(bValue, bValue.Length - 4, bXID, 0, 4)
            End Set
        End Property
        Public Overrides Function toString() As String
            Dim szResult As String
            szResult = iRID & "," & XIDInt & "(" & BufferCount & ")" & Choose(iCheckPolling + 1, "  ", "--", " \", " |", " /")
            Return szResult
        End Function
        Public Property BufferCount() As Integer
            Get
                Return iBufferCount
            End Get
            Set(ByVal value As Integer)
                iBufferCount = value
            End Set
        End Property
        Public WriteOnly Property Polling() As Boolean
            Set(ByVal value As Boolean)
                If value Then
                    iCheckPolling += 1
                    iCheckPolling = iCheckPolling Mod 5
                End If
            End Set
        End Property
        Public Property LastBuffer() As Byte()
            Get
                Return bBuffer
            End Get
            Set(ByVal value As Byte())
                bBuffer = value
            End Set
        End Property
    End Class

    Private Sub cmdAutoTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAutoTest.Click
        Dim iType As GIGATMS.SFReader.MachineTypeConstants, iModal As GIGATMS.SFReader.ReaderModal
        iType = GIGATMS.SFReader.MachineTypeConstants.Any
        iModal = GIGATMS.SFReader.ReaderModal.Any
        Dim I As Integer
        I = m_oSFReader.NumberOfPorts()
        m_oSFReader.IsMonitorIO = True

        If m_oSFReader.AutoScan(iType, iModal, m_szSetPort, chkOnlyTestSet.Checked) Then
            txtResult.SelectedText = IIf(iModal = GIGATMS.SFReader.ReaderModal.SF500, "SF500 series", "SF600 series") & " " & IIf(iType = GIGATMS.SFReader.MachineTypeConstants.Programer, "Programmer", "Reader")
            txtResult.SelectedText = vbCrLf & "Delete All Fingerprints..."
            Windows.Forms.Cursor.Current = Cursors.WaitCursor
            m_szAutoStep = "Delete All"
            m_oSFReader.Delete(&HFFFF)
            Windows.Forms.Cursor.Current = Cursors.Default
            txtResult.SelectedText = "OK"
            m_bAuto = True
            m_szAutoStep = "Info"
        Else
            MsgBox("Do not find SmaFinger Reader!", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "No Reader")
        End If

    End Sub

    Private Sub frmSmaFingerTester_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Not m_oSFReader Is Nothing Then
            If m_oSFReader.PortOpen Then
                m_oSFReader.AutoMode(True)
            End If
        End If
        If Not m_oMFReader Is Nothing Then
            If m_oMFReader.MFReader.CommPort.PortOpen Then
                m_oMFReader.MFReader.CommPort.PortOpen = False
            End If
        End If
    End Sub

    Private Sub frmSmaFingerTester_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        m_szAppTitle = "Test SmaFinger"

        m_oSFReader = New GIGATMS.SFReader()
        m_oMFReader = New GIGATMS.NCF.SFMAD
        m_bAuto = False
        m_bTCFingerClose = True
        m_bContinuePolling = False

        cboCommport.Items.AddRange(m_oSFReader.EnumCommPortEx)

        If cboCommport.Items.Count > 0 Then
            cboCommport.SelectedIndex = 0
        End If

    End Sub

    Private Sub cmdInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdInfo.Click
        showResult("Information : " & m_oSFReader.Settings)
        showResult("Information : " & m_oSFReader.GetVersion())
        showResult("Information : Max BIO Timeout = " & m_oSFReader.BIOTimeout)
        showResult("Information : Max Template Size = " & m_oSFReader.MaxTemplateSize)
        showResult("Information : Max Template Count on Card = " & m_oSFReader.MaxTemplateOnCard)
        showResult("Information : Max Template Count on Reader = " & m_oSFReader.MaxTemplateOnReader)
        'ReDim m_bUserData(6)
        'm_bUserData(0) = Year(Now) \ 100
        'm_bUserData(1) = Year(Now) Mod 100
        'm_bUserData(2) = Month(Now)
        'm_bUserData(3) = Microsoft.VisualBasic.DateAndTime.Day(Now)
        'm_bUserData(4) = Hour(Now)
        'm_bUserData(5) = Minute(Now)
        'm_bUserData(6) = Second(Now)
        m_bUserData = BitConverter.GetBytes(10056932)
        'Array.Reverse(m_bUserData)

        cmdEnrollFP.Enabled = True
        If m_bAuto Then
            m_szAutoStep = "EnrollFP"
        End If
    End Sub

    Private Sub showResult(ByVal szResult As String, Optional ByVal bNewLine As Boolean = True)
        If bNewLine Then txtResult.SelectedText = vbCrLf
        txtResult.SelectedText = szResult
    End Sub

    Private Sub cmdEnrollFP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEnrollFP.Click
        m_oFPEnrollResult = Nothing
        m_oFPEnrollResult = New clsResult

        frmTCFinger.m_oParent = Me
        frmTCFinger.ShowFinger(m_oSFReader, m_oFPEnrollResult)
    End Sub

    Private Sub m_oFPEnrollResult_OnResult() Handles m_oFPEnrollResult.OnResult
        Dim bResult As Boolean
        m_bIsShowFinger = True
        bResult = False
        If m_oFPEnrollResult.Result Then
            m_lFingerBufferCount = m_oFPEnrollResult.Value("FingerBufferCount")
            m_bFingerBuffers = m_oFPEnrollResult.Value("FingerBuffers")
            m_iIssueMachine = m_oFPEnrollResult.Value("IssueMachine")
            bResult = True
        End If

        showResult("Enroll Finger : " & IIf(bResult, "OK", "NG"))
        If bResult Then
            cmdVerifyFP.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "VerifyFP"
            End If
        End If

    End Sub

    Private Sub cmdVerifyFP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdVerifyFP.Click
        m_oFPVerifyResult = Nothing
        m_oFPVerifyResult = New clsResult
        frmTCFinger.m_oParent = Me
        frmTCFinger.VerifyFinger(m_oSFReader, m_oFPVerifyResult, m_bFingerBuffers)

    End Sub

    Private Sub m_oFPVerifyResult_OnResult() Handles m_oFPVerifyResult.OnResult
        Dim bResult As Boolean
        bResult = False
        If m_oFPVerifyResult.Result Then
            If m_oFPVerifyResult.Value("VerifyResult") Then
                bResult = True
            End If
        End If
        showResult("Verify Finger : " & IIf(bResult, "OK", "NG"))
        If bResult Then
            cmdStoreFP.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "StoreFP"
            End If
        End If
    End Sub

    Private Sub cmdStoreFP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStoreFP.Click
        Dim bResult As Boolean

        m_iFingerID = m_oSFReader.AppendFinger(m_bFingerBuffers, FINGER_NO_FOR_TEST, m_bUserData, "SFTest UserName")
        m_oSFReader.AppendFinger(m_bFingerBuffers, FINGER_NO_FOR_TEST + 1, m_bUserData, "SFTest UserName")
        bResult = (m_iFingerID > 0)

        If bResult Then
            showResult("Stroe Finger : " & "FID = " & m_iFingerID)
        End If
        showResult(" Stroe Finger" & IIf(bResult, "OK", "NG"), False)
        If bResult Then
            cmdIdentifyFP.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "IdentifyFP"
            End If
        End If
    End Sub

    Private Sub cmdIdentifyFP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdIdentifyFP.Click
        m_oFPIdentifyResult = Nothing
        m_oFPIdentifyResult = New clsResult

        frmTCFinger.m_oParent = Me
        frmTCFinger.Identify(m_oSFReader, m_oFPIdentifyResult)

    End Sub

    Private Sub m_oFPIdentifyResult_OnResult() Handles m_oFPIdentifyResult.OnResult
        Dim bResult As Boolean, iFID As Integer
        bResult = False
        If m_oFPIdentifyResult.Result Then
            If m_oFPIdentifyResult.Value("IdentifyResult") Then
                iFID = m_oFPIdentifyResult.Value("FingerID")
                bResult = True
            End If
        End If
        If bResult Then
            bResult = (m_iFingerID = iFID)
        End If
        If bResult Then
            showResult("Identify : " & "FID = " & iFID)
        End If
        showResult(" Identify Finger " & IIf(bResult, "OK", "NG"), False)
        If bResult Then
            cmdUserData.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "CheckUserData"
            End If
        End If

    End Sub

    Private Sub cmdUserData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUserData.Click
        Dim bResult As Boolean, bUserData As Byte() = Nothing
        Dim bFingerNo As Byte, iFPCount As Integer, iU_Index As Integer
        If m_oSFReader.MachineType = GIGATMS.SFReader.MachineTypeConstants.Programer Then
            showResult("Check User Data : Programer don't check UserData")
            bResult = True
        Else

            If m_oSFReader.NewStoreFingerFunc Then
                'for SF650
                bResult = False
                bFingerNo = FINGER_NO_FOR_TEST
                bUserData = m_bUserData
                iU_Index = m_oSFReader.GetUserIndex(bUserData, iFPCount)
                If iFPCount > 0 Then
                    bResult = (m_iFingerID = m_oSFReader.FindFIDEx(bFingerNo, bUserData, , True))
                End If
            Else
                bResult = m_oSFReader.GetUserData(m_iFingerID, bFingerNo, bUserData)
            End If

            If bResult Then
                bResult = (BitConverter.ToString(bUserData) = BitConverter.ToString(m_bUserData))
            End If

            If bResult Then
                showResult("Check User Data : FID = " & m_iFingerID)

            End If
            showResult(" Check User Data " & IIf(bResult, "OK", "NG"), False)
        End If
        If bResult Then
            cmdReadFinger.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "ReadFP"
            End If
        End If

    End Sub

    Private Sub cmdDeleteFP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDeleteFP.Click
        Dim bResult As Boolean
        bResult = m_oSFReader.Delete(m_iFingerID)

        showResult("Delete Finger : " & m_iFingerID & " " & IIf(bResult, "OK", "NG"))
        If bResult Then
            If m_bAuto Then
                MsgBox("Test Success!!", MsgBoxStyle.OkOnly And MsgBoxStyle.Information, "Auto Test")
            End If
        End If
        If m_oSFReader.PortOpen Then
            m_oSFReader.AutoMode(True)
        End If
        m_oSFReader.PortOpen = False
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If m_oSFReader.PortOpen OrElse m_oSFReader.AutoScan(, , m_szSetPort) Then
            MsgBox(m_oSFReader.Buzzer(5, 3, 50))
        Else
            MsgBox("Do not find SmaFinger Reader!", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "No Reader")
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If m_oSFReader.PortOpen OrElse m_oSFReader.AutoScan(, , m_szSetPort) Then
            MsgBox(m_oSFReader.GetFingerCount())
        Else
            MsgBox("Do not find SmaFinger Reader!", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "No Reader")
        End If
    End Sub

    Private Sub timerAuto_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerAuto.Tick
        Dim szStep As String, iCount As Integer
        If m_szAutoStep <> "" Then
            If InStr(m_szAutoStep, ",") > 0 Then
                szStep = Split(m_szAutoStep, ",")(0)
                iCount = CInt(Split(m_szAutoStep, ",")(1))
            Else
                szStep = m_szAutoStep
            End If
            m_szAutoStep = ""
            Select Case szStep
                Case "Info"
                    cmdInfo.PerformClick()
                Case "EnrollFP"
                    cmdEnrollFP.PerformClick()
                Case "VerifyFP"
                    cmdVerifyFP.PerformClick()
                Case "StoreFP"
                    cmdStoreFP.PerformClick()
                Case "IdentifyFP"
                    cmdIdentifyFP.PerformClick()
                Case "CheckUserData"
                    cmdUserData.PerformClick()
                Case "ReadFP"
                    cmdReadFinger.PerformClick()
                Case "DeleteFP"
                    cmdDeleteFP.PerformClick()
                Case "Delete All"
                    If iCount > 50 Then
                        iCount = 1
                        txtResult.SelectedText = "."
                    End If
                    m_szAutoStep = "Delete All," & CStr(iCount + 1)
            End Select
        End If
    End Sub

    Private Sub cmdAutoScan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAutoScan.Click
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        If m_oMFReader.AutoScan Then
            Windows.Forms.Cursor.Current = Cursors.Default
            Me.Text = m_szAppTitle & " MF RWD ON " & m_oMFReader.MFReader.CommPort.PortName
            m_oMFReader.MFReader.mfRequestEx(0)
            m_oMFReader.MFReader.mfAutoMode(True)
        Else
            Windows.Forms.Cursor.Current = Cursors.Default
            MsgBox("Do not find Mifare Reader!", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "No Reader")
        End If

    End Sub

    Private Sub cmdFormat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdFormat.Click
        With m_oMFReader
            Windows.Forms.Cursor.Current = Cursors.WaitCursor

            .MadAdminKey = "FFFFFFFFFFF0"
            .AppAdminKey = "FFFFFFFFFFF1"
            .AppUserKey = "FFFFFFFFFFF2"
            .AppAID = 4703
            If .MFReader.mfSelectCardEx() <> 0 Then
                .MFReader.mfAddTryKey("FFFFFFFFFFF2")
                .MFReader.mfAddTryKey("FFFFFFFFFFF3")
                .MFReader.mfAddTryKey("FFFFFFFFFFF4")
                .MFReader.mfAddTryKey("FFFFFFFFFFF5")
                .MFReader.mfAddTryKey("FFFFFFFFFFF6")
                .MFReader.mfAddTryKey("FFFFFFFFFFF7")
                .MFReader.mfAddTryKey("FFFFFFFFFFF8")
                If .madFormat Then
                    MsgBox("Format OK")
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.APP_AID) Then
                        MsgBox("Assign APP AID OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1000", "FFFFFFFFFFF2", 1) Then
                        MsgBox("Assign 1000 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1001", "FFFFFFFFFFF3", 1) Then
                        MsgBox("Assign 1001 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1002", "FFFFFFFFFFF4", 1) Then
                        MsgBox("Assign 1002 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1003", "FFFFFFFFFFF5", 1) Then
                        MsgBox("Assign 1003 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1004", "FFFFFFFFFFF6", 1) Then
                        MsgBox("Assign 1004 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1005", "FFFFFFFFFFF7", 1) Then
                        MsgBox("Assign 1005 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.CT_AID, "1006", "FFFFFFFFFFF8", 1) Then
                        MsgBox("Assign 1006 OK")
                    End If
                    If .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.FP_AID) Then
                        MsgBox("Assign Fingerprint AID OK")
                    End If
                End If
            End If

            m_oMFReader.MFReader.mfAutoMode(True)
            Windows.Forms.Cursor.Current = Cursors.Default
        End With
    End Sub

    Private Function getCardEventString(ByVal iEvent As GIGATMS.NCF.MifareReader.iCARD_EVENTS) As String
        Dim szResult As String = ""
        Select Case iEvent
            Case GIGATMS.NCF.MifareReader.iCARD_EVENTS.CARD_REMOVE
                szResult = "Card Remove"
            Case GIGATMS.NCF.MifareReader.iCARD_EVENTS.CARD_PRESENT
                szResult = "Card Present"
        End Select
        Return szResult
    End Function
    Private Sub m_oMFReader_OnCardEvent(ByVal iEvent As GIGATMS.NCF.MifareReader.iCARD_EVENTS) Handles m_oMFReader.OnCardEvent
        showResult("Card Event : " & getCardEventString(iEvent))
    End Sub

    Private Sub m_oMFReader_OnMessages(ByVal iMsgType As GIGATMS.NCF.MAD.MessageType, ByVal szMessage As String, ByVal iMessage As Integer) Handles m_oMFReader.OnMessages
        If iMsgType = GIGATMS.NCF.MAD.MessageType.MsgProgress Then
            Select Case szMessage
                Case "Format"
                    progBar.Value = iMessage
                Case "AssignAID"
                    progBar.Value = iMessage
                Case "SetData"
                    progBar.Value = iMessage
            End Select
        End If
    End Sub

    Private Sub cmdCardIssue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCardIssue.Click
        If m_oMFReader.MFReader.CommPort.PortOpen Then
            m_oMFReader.MFReader.mfSelectCardEx()
            If m_oMFReader.CurrentCard.CardClass <> GIGATMS.NCF.MifareCard.CardTypeConstants.MIFARE_None Then
                m_oFPEnrollResult2 = Nothing
                m_oFPEnrollResult2 = New clsResult

                With m_oMFReader
                    .AppAdminKey = "FFFFFFFFFFF1"
                    .AppUserKey = "FFFFFFFFFFF2"
                    .AppAID = 4703
                End With

                frmTCFinger.m_oParent = Me
                frmTCFinger.ShowFinger(m_oSFReader, m_oFPEnrollResult2)
            Else
                MsgBox("Cannot find Card on Reader!")
            End If
            m_oMFReader.MFReader.mfAutoMode(True)
        Else
            MsgBox("Cannot find RWD!")
        End If
    End Sub

    Private Sub m_oFPEnrollResult2_OnResult() Handles m_oFPEnrollResult2.OnResult
        Dim bResult As Boolean
        Dim lBufCount As Long, bFPBuf As Byte() = Nothing, iMachine As Integer
        Dim mFPData As GIGATMS.NCF.FingerprintData, mAPPData As GIGATMS.NCF.ApplicationData
        Dim mUID As GIGATMS.NCF.InterfaceConverter

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        m_bIsShowFinger = True
        bResult = False
        With m_oFPEnrollResult2
            If .Result Then
                lBufCount = .Value("FingerBufferCount")
                bFPBuf = .Value("FingerBuffers")
                iMachine = .Value("IssueMachine")
                bResult = True
            End If
        End With
        m_oSFReader.AutoMode(True)
        m_oSFReader.PortOpen = False
        frmTCFinger.Visible = False
        If bResult Then
            mFPData = New GIGATMS.NCF.FingerprintData
            With mFPData
                .Type = iMachine
                .Action = GIGATMS.NCF.FingerprintData.FPAction.FPAct_CARD_FINGER    'Issue Card+Finger
                '.Action = GIGATMS.NCF.FingerprintData.FPAction.FPAct_CARDONLY      'Issue Card Only
                '.Action = GIGATMS.NCF.FingerprintData.FPAction.FPAct_ADD_FINGER    'Issue Enroll Card (for Finger Only)
                '.Action = GIGATMS.NCF.FingerprintData.FPAction.FPAct_DELETE_FINGER 'Issue Delete Card (for Finger Only)
                .FingerNO = GIGATMS.NCF.FingerprintData.FPNoNum.LEFT_INDEXFINGER
                .FingerSize = lBufCount
                .FingerDatas = bFPBuf

            End With
            bResult = m_oMFReader.writeFPBlock(mFPData)

        End If
        If bResult Then
            mAPPData = New GIGATMS.NCF.ApplicationData
            mUID = mAPPData.UserDataEx
            'mUID.setAsciiValue("Hello")        'Set ASCII Code
            'mUID.setTk2Value(1234567890)       'Set ABA/TK2 Value
            mUID.setWGSetting(16, 8, 0)         'Set Wiegand Bit
            mUID.setWiegandValue(12345, 100)    'Set Wiegand Value
            mAPPData.UserDataEx = mUID
            'mAPPData.Surname = "SURNAME"
            bResult = m_oMFReader.writeAPPBlock(mAPPData)
        End If
        Windows.Forms.Cursor.Current = Cursors.Default

        MsgBox("Issue " & IIf(bResult, "OK", "NG"))
    End Sub

    Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
        Dim szPort As String, iType As GIGATMS.SFReader.MachineTypeConstants, iReadModal As GIGATMS.SFReader.ReaderModal ', iModalNO As GIGATMS.SFReader.ModalNo
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        szPort = cboCommport.Text
        m_szSetPort = ""
        If Microsoft.VisualBasic.Left(szPort, 3) = "COM" Or Microsoft.VisualBasic.Left(szPort, 3) = "TCP" Then
            iType = GIGATMS.SFReader.MachineTypeConstants.Any
            iReadModal = GIGATMS.SFReader.ReaderModal.Any
            If m_oSFReader.AutoScan(iType, iReadModal, szPort, True) Then

                showResult("SmaFinger Connect OK")
                showResult("Reader Type :" & IIf(iType = GIGATMS.SFReader.MachineTypeConstants.Programer, "Programmer", "Reader"))
                showResult("Reader Modal :" & m_oSFReader.MachineModalStr())
                m_szSetPort = szPort
                m_oSFReader.AutoScan(iType, iReadModal, szPort)
                m_iNewRID = 1
            Else
                showResult("SmaFinger Connect NG")
            End If
        Else
            showResult("Please Select Commport")
        End If
        Windows.Forms.Cursor.Current = Cursors.Default

    End Sub


    Private Sub cmdReadBlock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadBlock.Click
        With m_oMFReader
            Windows.Forms.Cursor.Current = Cursors.WaitCursor
            .MadAdminKey = "FFFFFFFFFFF0"
            .AppAdminKey = "FFFFFFFFFFF1"
            .AppUserKey = "FFFFFFFFFFF2"
            .AppAID = 4703

            Dim bTemp() As Byte
            bTemp = .readFPBlock()
            If Not bTemp Is Nothing AndAlso bTemp.Length > 0 Then
                MsgBox("Read APP OK")
            Else
                MsgBox("Read APP NG")
            End If

            If .MFReader.mfReadEx(2, GIGATMS.NCF.MifareCard.KeyTypeConstants.KEY_A, "A0A1A2A3A4A5", 0, bTemp) Then
                MsgBox("Read Block OK")
            Else
                MsgBox("Read Block NG")
            End If
            .MFReader.mfAutoMode(True)

            Windows.Forms.Cursor.Current = Cursors.Default
        End With
    End Sub

    Private Sub cmdWriteBlock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWriteBlock.Click
        With m_oMFReader
            Windows.Forms.Cursor.Current = Cursors.WaitCursor
            .MadAdminKey = "FFFFFFFFFFF0"
            .AppAdminKey = "FFFFFFFFFFF1"
            .AppUserKey = "FFFFFFFFFFF2"
            .AppAID = 4703

            'Demo Format and assignAID
            If .MFReader.mfRequestEx(0) <> 0 Then
                .madInitial()
                .MFReader.mfAddTryKey("FFFFFFFFFFF0")
                .MFReader.mfAddTryKey("FFFFFFFFFFF1")
                If .madFormat() Then
                    .AssignAID(GIGATMS.NCF.SFMAD.AssignCode.APP_AID)
                End If

            End If

            'Demo Write App Block
            Dim bTemp(4) As Byte
            bTemp(0) = &H12
            bTemp(1) = &H34
            bTemp(2) = &H56
            bTemp(3) = &H78
            bTemp(4) = &H90
            If .writeAPPBlock(bTemp) Then
                MsgBox("Write APP OK")
            Else
                MsgBox("Write APP NG")
            End If

            'Demo Write Special Sector
            If .MFReader.mfWriteEx(2, GIGATMS.NCF.MifareCard.KeyTypeConstants.KEY_B, "FFFFFFFFFFF0", 0, bTemp) Then
                MsgBox("Write Block OK")
            Else
                MsgBox("Write Block NG")
            End If


            Windows.Forms.Cursor.Current = Cursors.Default
        End With
    End Sub

    Private Sub cmdChangeLED_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdChangeLED.Click
        Dim bTemp(3) As Byte

        If MsgBox("Before test LED, please use 'Mifare Reader Utility' to setup 'Enable RS232 Command Set Control' setting in 'LED/Buzzer' tab. " & vbCrLf & "Are you ready?", MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Before Test") = MsgBoxResult.Yes Then

            With m_oSFReader
                If .PortOpen Then
                    .Settings = "38400"
                    .AutoMode(False)

                    bTemp(0) = &H2      'STX
                    bTemp(1) = &H4A     'Function Code = J
                    bTemp(2) = &H42     'Bule LED Off
                    bTemp(3) = &HD      'CR

                    .Output = bTemp

                    bTemp(2) = &H38   '30~39
                    .Output = bTemp
                    MsgBox("Red LED ON with Beep 3 Time")

                    bTemp(2) = &H37   '30~39
                    .Output = bTemp
                    MsgBox("Green LED ON with Beep 1 Time")

                    bTemp(2) = &H30   'Bule LED ON
                    .Output = bTemp
                    bTemp(2) = &H41   'Bule LED ON
                    .Output = bTemp
                Else
                    MsgBox("Please connect SmaFinger Reader first!")
                End If
            End With
        End If
    End Sub

    Private Sub m_oSFReader_OnComm(ByRef sender As GIGATMS.IO.ISerialPort, ByVal iCommEvent As GIGATMS.IO.ISerialPort.CommEventConstants) Handles m_oSFReader.OnComm
        Dim bytValue() As Byte
        showResult("SmaFinger OnComm")
        bytValue = m_oSFReader.Input 'RxBuffer
        If Not bytValue Is Nothing AndAlso bytValue.Length > 0 Then
            showResult(System.BitConverter.ToString(bytValue))
        End If
    End Sub

    Private Sub cmdIsFormated_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdIsFormated.Click
        With m_oMFReader
            .MadAdminKey = "FFFFFFFFFFF0"

            If .MFReader.mfRequestEx(0) <> 0 Then
                .madInitial()
                showResult("MAD Format : " & .madIsMAD)
                showResult("AID List : " & Join(.madEnumAID(), ","))
                showResult("size of FP AID : " & .madGetAIDSize("4839"))

            End If
        End With
    End Sub

    Private Sub cmdMultiReaderTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMultiReaderTest.Click
        splitTestTools.Panel1Collapsed = True
    End Sub

    Private Sub cmdNormalTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNormalTest.Click
        splitTestTools.Panel2Collapsed = True
    End Sub

    Private Sub cmdAddReader_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddReader.Click
        If txtXIDNo.Text <> "" AndAlso IsNumeric(txtXIDNo.Text) Then
            addXID(txtXIDNo.Text)
        End If
    End Sub

    Private Sub addXID(ByVal szXIDNo As String)
        Dim lXID As Integer, bValue(3) As Byte
        Dim oReaderContent As ReaderContent
        If m_oSFReader.PortOpen = False Then
            m_oSFReader.PortOpen = True
            m_oSFReader.Settings = "38400"
            If m_iNewRID < 1 Then
                m_iNewRID = 1
            End If
        End If
        If m_oSFReader.PortOpen Then
            With m_oSFReader
                lXID = Val(szXIDNo)
                oReaderContent = New ReaderContent(lXID)
                bValue = oReaderContent.XID

                If isExistReader(oReaderContent) = False Then

                    If .SetSlaveAddr(m_iNewRID, bValue) Then
                        oReaderContent.RID = m_iNewRID
                        lstReaders.Items.Add(oReaderContent)
                        m_iNewRID += 1
                    End If
                End If

            End With
        End If
    End Sub

    Private Function isExistReader(ByVal oReader As ReaderContent) As Boolean
        Dim oFind As ReaderContent, bResult As Boolean
        bResult = False
        For Each oFind In lstReaders.Items
            If oFind.XIDStr = oReader.XIDStr Then
                bResult = True
                Exit For
            End If
        Next
        Return bResult
    End Function


    Private Sub timerPolling_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerPolling.Tick
        If m_bContinuePolling AndAlso m_bPolling = False Then
            m_bPolling = True
            If Polling() Then
                getReadersData()
            End If
            m_bPolling = False
        End If
    End Sub

    Private Function Polling() As Boolean
        Dim I As Integer, bData() As Byte = Nothing, bNoChange As Boolean, iCount As Integer, iLoop As Integer
        Dim iListIndex As Integer
        Dim bResult As Boolean
        Dim oPollingReply As New GIGATMS.SFReader.PollingReply
        With m_oSFReader
            If .PortOpen Then
                If chkPollingLog.Checked Then
                    showResult("Polling...")
                End If
                .GNetPlusTimeout = 5000
                .ActiveAddress = 0
                If .Polling(oPollingReply) Then
                    If chkPollingLog.Checked Then showResult("ok:", False)
                    bNoChange = False
                    iCount = .GetReplyValuesCount()
                    iLoop = 0
                    Do Until bNoChange
                        System.Threading.Thread.Sleep(100)
                        System.Windows.Forms.Application.DoEvents()
                        bNoChange = (iCount = .GetReplyValuesCount) Or (iLoop > 50)
                        iCount = .GetReplyValuesCount()
                        iLoop += 1
                    Loop
                    For I = 0 To .GetReplyValuesCount() - 1
                        If .GetReplyValues(I, bData) AndAlso Not bData Is Nothing AndAlso bData.Length >= 3 Then
                            oPollingReply.ReplyData = bData
                            If chkPollingLog.Checked Then
                                showResult("Reader-" & .GetReplyAddress(I) & "(" & oPollingReply.BufferCount & ")", False)
                            End If
                            iListIndex = lstReaders.FindString(.GetReplyAddress(I) & ",")
                            If iListIndex >= 0 Then
                                refreshReaderLst(iListIndex, oPollingReply.BufferCount, True)
                            End If
                        End If
                    Next I
                    If chkPollingLog.Checked Then showResult("")
                    bResult = True
                Else
                    showResult("ng:", False)
                    showResult(.GetReplyValuesCount())
                    bResult = False
                End If
            End If
        End With
        Return bResult
    End Function
    Private Sub getReadersData()
        Dim oReader As ReaderContent, bData() As Byte, I As Integer
        For I = 0 To lstReaders.Items.Count - 1
            oReader = lstReaders.Items(I)
            If oReader.BufferCount > 0 Then
                bData = getReaderData(oReader)
                If Not bData Is Nothing Then
                    showResult("Reader" & oReader.RID & " Data : " & System.BitConverter.ToString(bData))
                End If
            End If
            refreshReaderLst(I, oReader.BufferCount)
        Next

    End Sub
    Private Function getReaderData(ByRef oReader As ReaderContent) As Byte()
        Dim bResult() As Byte = Nothing
        With m_oSFReader
            .ActiveAddress = oReader.RID
            If .GetBufferData(bResult) Then

                oReader.BufferCount -= 1
            Else

            End If
            oReader.LastBuffer = bResult

        End With
        Return bResult
    End Function

    Private Sub cmdPolling_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPolling.Click
        Polling()
    End Sub

    Private Sub cmdGetData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetData.Click
        getReadersData()
    End Sub

    Private Sub chkContinuePolling_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkContinuePolling.CheckedChanged
        timerPolling.Interval = Val(txtInterval.Text) * 1000
        m_bContinuePolling = chkContinuePolling.Checked
    End Sub

    Private Sub refreshReaderLst(ByVal iListIndex As Integer, ByVal iBufferCount As Integer, Optional ByVal bPolling As Boolean = False)
        Dim oReader As ReaderContent
        oReader = lstReaders.Items(iListIndex)
        oReader.Polling = bPolling
        oReader.BufferCount = iBufferCount
        lstReaders.Items(iListIndex) = oReader
    End Sub

    Private Sub cmdReadFinger_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFinger.Click
        Dim bResult As Boolean
        Dim bFingerBuffer() As Byte = Nothing

        If m_oSFReader.PortOpen OrElse m_oSFReader.AutoScan(, , m_szSetPort) Then
            'iFID = m_oSFReader.FindFID(FINGER_NO_FOR_TEST, m_bUserData)  'if you don't have FID, you can get it from this method
            bResult = m_oSFReader.GetFingerTmp(m_iFingerID, bFingerBuffer)
            If bResult Then

                bResult = (System.BitConverter.ToString(m_bFingerBuffers) = System.BitConverter.ToString(bFingerBuffer))
                showResult("Reader Fingerprint Success!" & vbCrLf & "Finger Buffer Size =" & bFingerBuffer.Length & " bytes")
            Else
                showResult("Reader Fingerprint Fail!")
            End If
        Else
            showResult("Do not find SmaFinger Reader!")
        End If
        showResult("Reader Fingerprint : " & m_iFingerID & " " & IIf(bResult, "OK", "NG"))
        If bResult Then
            cmdDeleteFP.Enabled = True
            If m_bAuto Then
                m_szAutoStep = "DeleteFP"
            End If
        End If
    End Sub


    Private Sub m_oSFReader_OnMonitor(ByRef oSender As GIGATMS.IO.ISerialPort, ByVal iEvent As GIGATMS.IO.ISerialPort.CommMonitorEventConstants, ByRef bBuffer() As Byte) Handles m_oSFReader.OnMonitor
        If chkMonitor.Checked Then
            Select Case iEvent
                Case GIGATMS.IO.ISerialPort.CommMonitorEventConstants.comEvInput
                    showResult("SFReader Monitor: " & "(Answer)" & System.BitConverter.ToString(bBuffer))
                Case GIGATMS.IO.ISerialPort.CommMonitorEventConstants.comEvOutput
                    showResult("SFReader Monitor: " & "(Request)" & System.BitConverter.ToString(bBuffer))
                Case GIGATMS.IO.ISerialPort.CommMonitorEventConstants.comEvPortOpen
                    showResult("SFReader Monitor: Port Open " & IIf(bBuffer(0) = 1, "OK", "NG"))
                Case GIGATMS.IO.ISerialPort.CommMonitorEventConstants.comEvPortBeforeClose
                    showResult("SFReader Monitor: Port Closing ... ")
                Case GIGATMS.IO.ISerialPort.CommMonitorEventConstants.comEvPortClose
                    showResult("SFReader Monitor: Port Close " & IIf(bBuffer(0) = 1, "OK", "NG"))
            End Select
        End If
    End Sub

    Private Sub cmdQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdQuery.Click
        Dim bContinue As Boolean
        If m_oSFReader.PortOpen = False Then
            m_oSFReader.AutoScan()

        End If
        If m_oSFReader.PortOpen Then
            m_oSFReader.IsMonitorIO = True
            Do
                bContinue = QueryEx(txtFunc.Text & "," & txtParams.Text)
                If chkContinue.Checked = False Then
                    bContinue = False
                End If
            Loop While bContinue

        End If
    End Sub

    Private Function QueryEx(ByVal szCMD As String) As Boolean
        Dim bResult As Boolean, szCmds() As String
        Dim bFunc As Byte, bParam() As Byte, I As Integer, szTemp As String
        szCmds = Split(szCMD, ",")
        bFunc = Val("&H" & szCmds(0)) And &HFF
        ReDim bParam(-1)
        For I = 1 To Len(szCmds(1)) Step 2
            szTemp = Mid(szCmds(1) & "0", I, 2)
            ReDim Preserve bParam(bParam.Length)
            bParam(bParam.Length - 1) = Val("&H" & szTemp)
        Next
        With m_oSFReader
            bResult = .Query(bFunc, bParam)
        End With
        Return bResult
    End Function

    Private Sub cmdDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDisconnect.Click
        m_oSFReader.PortOpen = False
    End Sub

    Private Sub cmdQuery2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdQuery2.Click
        Dim bContinue As Boolean, iTemp As Integer
        If m_oSFReader.PortOpen = False Then
            m_oSFReader.AutoScan()

        End If
        If m_oSFReader.PortOpen Then
            m_oSFReader.IsMonitorIO = True
            iTemp = 0
            Do
                bContinue = QueryEx(txtCMDs.Lines(iTemp))
                If chkContinue.Checked = False Then
                    bContinue = False
                End If
                iTemp += 1
                If iTemp >= txtCMDs.Lines.Length Then iTemp = 0
                My.Application.DoEvents()
            Loop While bContinue

        End If
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        With cboCommport.Items
            .Clear()
            .AddRange(m_oSFReader.EnumCommPortEx)
        End With

    End Sub
End Class