Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' >>>>> Initialize Combo box <<<<<
        With Combo_ModeSelect                   				'Combo box setting.
            .Items.Clear()                      				'Combo box initialize.
            .Items.Add("C Mode")                				'Register combo box item.
            .Items.Add("E Mode")
            .Items.Add("EA Mode")
            .Items.Add("ED Mode")
            .Items.Add("ES Mode")
            .Text = Combo_ModeSelect.GetItemText(Combo_ModeSelect.Items(0))
        End With

        ' >>>>> Initialize communication line <<<<<
        With SerialPort1                        				'Serial port setting.  
            .PortName = "COM3"                  				'Set port name.  
            .BaudRate = 38400                   				'Set communication speed.
            .Parity = IO.Ports.Parity.None      				'Set parity.  
            .DataBits = 7                       				'Set Data bit.
            .StopBits = IO.Ports.StopBits.Two   				'Set Stop bit.
            .Handshake = IO.Ports.Handshake.RequestToSend   	'Set handshake method (RS-CS control)
            .RtsEnable = True                   				'RS signal = High (receivable).
            .ReadTimeout = 2000                 				'Set Time to read timeout.Unit: msec.
            .WriteTimeout = 2000                				'Set Time to write timeout.Unit: msec.
            Try
                .Open()                         				'Open communication line.
            Catch Cable As Exception
                Call Err_disp(0, "")            				'Connection error.
                Application.Exit()
                Exit Sub
            End Try
        End With

        Output_Text.Text = "Select the transfer mode from the combo box," & Chr(&HD) & "and click on OMR Read."

    End Sub

    Private Sub Button_Read_Click(sender As Object, e As EventArgs) Handles Button_Read.Click

        Dim Response As String = ""
        Dim TMCount As String = ""
        Dim ReciveCnt As String = ""
        Dim Mode As String = ""

		Button_Read.Enabled = False     						'The reading button is disabled during processing.

        ' >>>>> Check device communication <<<<<
        If SerialPort1.IsOpen = True Then
            If SerialPort1.DsrHolding = False Then              'Connection check.
                Call Err_disp(0, "")                            'Connection error.
                Exit Sub

            End If
            If SerialPort1.CtsHolding = False Then              'Check device communication state.
                Call Err_disp(0, "")                            'Connection error.
                Exit Sub
            End If
        Else
            Call Err_disp(0, "")                                'Connection error.
            Exit Sub
        End If

        ' >>>>> Initialize <<<<<
        Try
            SerialPort1.Write(Chr(&H18) & Chr(&HD))             'Send initialize command.
            Response = Chr(SerialPort1.ReadByte)
        Catch CAN As TimeoutException
            Call Err_disp(3, "")                                'Time out.
            Exit Sub
        End Try
        If Response <> Chr(&H6) Then
            Call Err_disp(1, "")                                'Initialization error.
            Exit Sub
        End If

		' >>>>> Scan Setting <<<<<
        Try
            SerialPort1.Write(Chr(&H13) & "12" & Chr(&HD))      'Send read line specify command (12 lines.)

            SerialPort1.Write(Chr(&H10) & "T" & Chr(&HD))       'Send timing format specify command(direct-under type)

            SerialPort1.Write(Chr(&H2) & "2" & Chr(&HD))

        Catch ReadSet As TimeoutException
            Call Err_disp(3, "")                                'Time out.
            Exit Sub
        End Try

        ' >>>>> Read card <<<<<
        Try
            SerialPort1.Write("?" & Chr(&HD))                   'Send card read command.
            ReciveCnt = 1                                       'Set number of bytes received for reading status.
            Response = Chr(SerialPort1.ReadByte)                'Receive read status.
            If Response <> "0" Then                             'Check read status.
                Call Err_disp(2, Response)                      'Read error.
                Exit Sub
            End If

            ' >>>>> Read timing mark count <<<<<
            SerialPort1.Write(Chr(&H5) & "T" & Chr(&HD))        'Send timing mark count read command.
            ReciveCnt = 1                                       'Wait until timing mark count is received.
            Do
                System.Windows.Forms.Application.DoEvents()
                TMCount = TMCount & Chr(SerialPort1.ReadByte.ToString) 'Receive timing mark count.
            Loop Until TMCount.Length = 3                       'Wait until reception of timing mark count.
            Output_Text.Text = "Timing mark count ：" & TMCount & Chr(&HD) & Chr(&HA) 'Display Timing mark count.
        Catch CardTM As TimeoutException
            Call Err_disp(3, "")                                'Time out.
            Exit Sub
        End Try

        ' >>>>> Transfer mode branch <<<<<
        Mode = Combo_ModeSelect.SelectedIndex
        Select Case Mode
            Case 0
                Call C_Mode(TMCount)                            'Read C mode.
            Case 1, 2, 3, 4
                Call E_Series(TMCount, Mode)                    'Read E,EA,ED,ES mode.
            Case Else
                Call Err_disp(99, "")                           'unexpected error.
                Exit Sub
        End Select

		Button_Read.Enabled = True                              'Enable the read button after processing is complete.
    End Sub

    ' >>>>> C mode reading (reading of fixed length data) <<<<<
    Private Sub C_Mode(ByVal TMCount As String)
        Dim CMode As String = ""
        Try
            SerialPort1.Write(Chr(&H10) & "C001" & TMCount & Chr(&HD))          'Send C mode read command.
            Do
                System.Windows.Forms.Application.DoEvents()
                CMode = CMode & Chr(SerialPort1.ReadByte.ToString)              'Receive C mode data.
            Loop Until CMode.Length = (3 * Val(TMCount))
            'Keep looping until "3*timing mark count" is received
            'since one column corresponds to 3 bytes.                                   
            Output_Text.Text = Output_Text.Text & "C Mode：" & CMode & Chr(&HD) & Chr(&HA) 'Display C mode data.

        Catch CRead As TimeoutException
            Call Err_disp(3, "")                                                'Time out.
            Exit Sub
        End Try
    End Sub

    ' >>>>> E mode series reading <<<<<
    Private Sub E_Series(ByVal TMCount As String, ByVal Mode As String)
        Dim Response As String = ""
        Dim ReciveCnt As Integer = 0
        Try
            Select Case Val(Mode)                                          'Branch to the transfer mode selected by the combo box.
                Case 1
                    Output_Text.Text = Output_Text.Text & "E Mode：" & Chr(&HD) & Chr(&HA)
                    SerialPort1.Write(Chr(&H10) & "E001" & TMCount & Chr(&HD))
                                                                            'Send E mode read command.
                Case 2
                    Output_Text.Text = Output_Text.Text & "EA Mode：" & Chr(&HD) & Chr(&HA)
                    SerialPort1.Write(Chr(&H10) & "EA001" & TMCount & Chr(&HD))
                                                                            'Send EA mode read command.
                Case 3
                    Output_Text.Text = Output_Text.Text & "ED Mode：" & Chr(&HD) & Chr(&HA)
                    SerialPort1.Write(Chr(&H10) & "ED001" & TMCount & Chr(&HD))
                                                                            'Send ED mode read command.
                Case 4
                    Output_Text.Text = Output_Text.Text & "ES Mode：" & Chr(&HD) & Chr(&HA)
                    SerialPort1.Write(Chr(&H10) & "ES001" & TMCount & Chr(&HD))
                    														'Send ES mode read command.
                Case Else
                    Call Err_disp(99, "")           'unexpected error.
                    Exit Sub
            End Select

            Select Case Val(Mode)
' >>>>> E · EA · ED mode reading <<<<<
                Case 1, 2, 3
                    Dim EMode(Val(TMCount)) As String                                   'Secure area
                    Dim DataLength As Integer = 0
                    Do                                                                  'Wait until E, EA, ED mode data is received.
                        System.Windows.Forms.Application.DoEvents()
                        Response = Response & Chr(SerialPort1.ReadByte.ToString)        'Receive E, EA, ED mode data.
                        DataLength = InStr(Response, Chr(&HD))                          'Extract received data for each column.
                        If DataLength <> 0 Then
                            EMode(ReciveCnt) = Strings.Left(Response, DataLength)
                            Output_Text.Text = Output_Text.Text & Format(ReciveCnt + 1, "000") &
                                "-Column：" & EMode(ReciveCnt) & Chr(&HA)
                            Response = Mid(Response, DataLength + 1)
                            ReciveCnt = ReciveCnt + 1
                        End If
                    Loop Until ReciveCnt = Val(TMCount)

' >>>>> ES mode reading <<<<<
                Case 4

                    Dim ESMode(1, Val(TMCount)) As String                               'Secure area
                    Dim DataLength_MC As Integer = 0
                    Dim MCFlag As Integer                                               'Flag for selection of extraction data.

                    MCFlag = 0

                    Do                                                                  'Wait until ES mode data is recieved.
                        System.Windows.Forms.Application.DoEvents()
                        Response = Response & Chr(SerialPort1.ReadByte.ToString)        'Receive ES mode data.
                        If MCFlag = 0 Then
                            DataLength_MC = InStr(Response, Chr(&HD))                   'Extract mark data for each column.
                            If DataLength_MC <> 0 Then
                                ESMode(MCFlag, ReciveCnt) = Strings.Left(Response, DataLength_MC)
                                Response = Mid(Response, DataLength_MC + 1)
                                MCFlag = 1                                              'Switch data to be extracted
                            End If
                        ElseIf MCFlag = 1 Then
                            DataLength_MC = InStr(Response, Chr(&HD))                   'Extract the density data for each column.
                            If DataLength_MC <> 0 Then
                                ESMode(MCFlag, ReciveCnt) = Strings.Left(Response, DataLength_MC)
                                Response = Mid(Response, DataLength_MC + 1)
                                Output_Text.Text = Output_Text.Text & Format(ReciveCnt + 1, "000") &
                                    "-Column：" & ESMode(0, ReciveCnt) & ESMode(1, ReciveCnt) & Chr(&HA)
                                MCFlag = 0                                              'Switch data to be extracted.
                                ReciveCnt = ReciveCnt + 1                               'Increment the loop count every time a mark and density are extracted.
                            End If
                        Else
                            Call Err_disp(99, "")                                       'unexpected error.
                            Exit Sub
                        End If
                    Loop Until ReciveCnt = Val(TMCount)
                Case Else
                    Call Err_disp(99, "")                                               'unexpected error.
                    Exit Sub
            End Select
        Catch ESeriesRead As TimeoutException
            Call Err_disp(3, "")                                                        'Time out.
            Exit Sub
        End Try
    End Sub

    ' >>>>> Error display processing <<<<<
    Private Sub Err_disp(ByVal errcode As Integer, ByVal Response As String)
        Select Case errcode
            Case 0      'Connection error.
                MessageBox.Show("OMR power is not turned on," & Chr(&HD) &
                    "communication cable is not connected !!",
                    "SR-450 Sample Program-1",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error)

            Case 1      'Initialization error.
                MessageBox.Show("Initialization failure!!",
                    "SR-450 Sample Program-1",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error)

            Case 2      'Read error.
                MessageBox.Show("An error occurred !!" & Chr(&HD) &
                    "Read status＝" & Response,
                    "SR-450 Sample Program-1",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error)

            Case 3      'Time out.
                Output_Text.Text = "Time out"

            Case Else   'unexpected error.
                MessageBox.Show("unexpected error",
                    "SR-450 Sample Program-1",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error)
        End Select

        Button_Read.Enabled = True          'Enable the read button.

    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        SerialPort1.Close()                                                     'Close communication line.
    End Sub                                                                     'Finish program.
End Class
