﻿Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1
    Public Shared Id As Short

    Dim SamplingData(DATA_NUM - 1, CHANNEL_NUM - 1) As UInt32 ' Buffer for sampling
    Dim NumberOfData As Integer
    Dim ReadIndex As Integer          'Read pointer
    Dim WriteIndex As Integer         'Write pointer
    Dim PreCount As Integer           'Previous transfer count
    Dim PreCarry As Integer           'Previous carry count
    Dim FileName As String = "Infinite.csv"

    Dim gMode As New frmMode()
    Dim gCondition As New frmCondition()

    Dim gCh As GCHandle
    Dim pSamplingData As IntPtr

    '===================================================
    ' Dialog initialization
    '===================================================
    Private Sub frmInfinite_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '-----------------------------------
        ' Initialize dialog display
        '-----------------------------------
        txtDeviceName.Text = "CNT000"
        '-----------------------------------
        ' Specify Pinned handle to SamplingData
        '-----------------------------------
        If gCh.IsAllocated = False Then
            gCh = GCHandle.Alloc(SamplingData, GCHandleType.Pinned)
        End If
    End Sub

    '===================================================
    ' CntInit()
    '===================================================
    Private Sub btnCntInit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntInit.Click
        Dim str As String
        Dim buf As New String("", 100)
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer

        '-----------------------------------
        ' Get device name
        '-----------------------------------
        buf = txtDeviceName.Text
        '-----------------------------------
        ' Initialization
        '-----------------------------------
        ret = CntInit(buf, Id)
        CntGetErrorString(ret, error_string)
        str = String.Format("CntInit ret = {0:d}: {1}", ret, error_string)
        txtReturn.Text = str
    End Sub

    '---------------------------------------------
    ' Display Counter Mode Setting dialog
    '---------------------------------------------
    Private Sub btnMode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMode.Click
        gMode.Show()
    End Sub

    '===================================================
    ' Condition Setting
    '===================================================
    Private Sub btnCondition_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCondition.Click
        gCondition.Show()
    End Sub

    '===================================================
    ' Start transfer
    '===================================================
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Dim ChNo(CHANNEL_NUM - 1) As Short
        Dim i As Short
        Dim error_string As New StringBuilder("", 256)
        Dim str As String
        Dim ret As Integer

        '-----------------------------------
        ' Set message notification
        '-----------------------------------
        ret = CntNotifySamplingStop(Id, Me.Handle)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntNotifySamplingStop ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        ret = CntNotifySamplingCount(Id, frmCondition.NumberOfData, Me.Handle)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntNotifySamplingCount ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        '-----------------------------------
        ' Reset FIFO (Input)
        '-----------------------------------
        ret = CntSamplingFifoReset(Id)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntSamplingFifoReset ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        '-----------------------------------
        ' Set data buffer
        '-----------------------------------
        Array.Clear(SamplingData, 0, SamplingData.Length)

        pSamplingData = gCh.AddrOfPinnedObject()
        ret = CntSamplingSetBuffer(Id, pSamplingData, CHANNEL_NUM, DATA_NUM, CNTS_WRITE_RING)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntSamplingSetBuffer ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        '------------------------------
        ' Set parameter
        '------------------------------
        For i = 0 To CHANNEL_NUM - 1
            ChNo(i) = i
        Next i
        '------------------------------
        ' Start count
        '------------------------------
        ret = CntStartCount(Id, ChNo, CHANNEL_NUM)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntStartCount ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        '-----------------------------------
        ' Initialize count
        '-----------------------------------
        ReadIndex = 0   ' Read pointer
        WriteIndex = 0  ' Write pointer
        PreCount = 0    ' Previous transfer count
        PreCarry = 0    ' Previous carry count
        '-----------------------------------
        ' Delete data file
        '-----------------------------------
        FileOpen(1, FileName, OpenMode.Append)
        FileClose(1)
        Kill(FileName)
        '-----------------------------------
        ' Start transfer
        '-----------------------------------
        ret = CntSamplingStart(Id)
        If ret <> CNT_ERR_SUCCESS Then
            CntGetErrorString(ret, error_string)
            str = String.Format("CntSamplingStart ret = {0:d}: {1}", ret, error_string)
            txtReturn.Text = str
            Exit Sub
        End If
        txtTransCount.Text = ""
        txtStatus.Text = ""
        txtError.Text = ""
    End Sub

    '===================================================
    ' Stop transfer
    '===================================================
    Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
        Dim error_string As New StringBuilder("", 256)
        Dim str As String
        Dim ret As Integer

        '-----------------------------------
        ' Stop transfer
        '-----------------------------------
        ret = CntSamplingStop(Id)
        CntGetErrorString(ret, error_string)
        str = String.Format("CntSamplingStop ret = {0:d}: {1}", ret, error_string)
        txtReturn.Text = str

    End Sub

    '===================================================
    ' Display data file
    '===================================================
    Private Sub btnData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnData.Click
        '-----------------------------------
        ' notepad
        '-----------------------------------
        Process.Start("notepad.exe", FileName)
    End Sub

    '===================================================
    ' Transfer count
    '===================================================
    Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCount.Click
        Dim count, carry As Integer
        Dim error_string As New StringBuilder("", 256)
        Dim str As String
        Dim ret As Integer

        count = 0
        carry = 0
        '-----------------------------------
        ' Get transfer count
        '-----------------------------------
        ret = CntGetSamplingCount(Id, count, carry)
        CntGetErrorString(ret, error_string)
        str = String.Format("CntGetSamplingCount ret = {0:d}: {1}", ret, error_string)
        txtReturn.Text = str
        If ret = CNT_ERR_SUCCESS Then
            ' In order to display the count value to unsigned, convert it once through hexadecimal characters
            txtTransCount.Text = String.Format("{0:d}", Convert.ToUInt32(Hex(count), 16))
        End If
    End Sub

    '===================================================
    ' Transfer status
    '===================================================
    Private Sub btnStatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStatus.Click
        Dim status, err As Integer
        Dim error_string As New StringBuilder("", 256)
        Dim str As String
        Dim ret As Integer

        '-----------------------------------
        ' Get transfer status
        '-----------------------------------
        ret = CntGetSamplingStatus(Id, status, err)
        CntGetErrorString(ret, error_string)
        str = String.Format("CntGetSamplingStatus ret = {0:d}: {1}", ret, error_string)
        txtReturn.Text = str
        If ret <> CNT_ERR_SUCCESS Then
            Return
        End If

        ' Status
        str = ""
        If (status And CNTS_STATUS_BMSTOP) Then
            str = str & "BmStop,"
        End If
        If (status And CNTS_STATUS_CNTSTART) Then
            str = str & "CntStart,"
        End If
        If (status And CNTS_STATUS_CNTSTOP) Then
            str = str & "CntStop,"
        End If
        If (status And CNTS_STATUS_TRGIN) Then
            str = str & "TrgIn,"
        End If
        If (status And CNTS_STATUS_OVERRUN) Then
            str = str & "Overrun"
        End If
        txtStatus.Text = str
        ' Error
        str = ""
        If (err And CNTS_STATUS_FIFOFULL) Then
            str = str & "FifoFull,"
        End If
        If (err And CNTS_STATUS_SGOVERIN) Then
            str = str & "S/GOverIn,"
        End If
        If (err And CNTS_STATUS_TRGERR) Then
            str = str & "TrgErr,"
        End If
        If (err And CNTS_STATUS_CLKERR) Then
            str = str & "ClkErr,"
        End If
        If (err And CNTS_STATUS_SLAVEHALT) Then
            str = str & "SlaveHalt,"
        End If
        If (err And CNTS_STATUS_MASTERHALT) Then
            str = str & "MasterHalt"
        End If

        txtError.Text = str
    End Sub

    '===================================================
    ' CntExit
    '===================================================
    Private Sub btnCntExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntExit.Click
        Dim error_string As New StringBuilder("", 256)
        Dim str As String
        Dim ret As Integer

        '-----------------------------------
        ' CntExit
        '-----------------------------------
        ret = CntExit(Id)
        CntGetErrorString(ret, error_string)
        str = String.Format("CntExit ret = {0:d}: {1}", ret, error_string)
        txtReturn.Text = str
    End Sub

    '===================================================
    ' Exit
    '===================================================
    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        '-----------------------------------
        ' Free GCHandle
        '-----------------------------------
        If gCh.IsAllocated = True Then
            gCh.Free()
        End If
        End
    End Sub

    '---------------------------------------------
    ' Counter Event notification processing
    '---------------------------------------------
    Protected Overrides Sub WndProc(ByRef m As Message)

        Dim ret As Integer
        Dim count, carry As Integer
        Dim data_count, ch_no As Integer
        Dim Cnt As UInteger
        Dim buf As New String("", 100)
        Dim str As String

        Select Case m.Msg
            Case CNTM_SAMPLING_COUNT ' Specified number transfer completion
                '-----------------------------------
                ' Retrieve transfer position on data buffer
                '-----------------------------------
                ret = CntGetSamplingWritePointer(Id, WriteIndex, count, carry)
                '-----------------------------------
                ' Check overflow error
                '-----------------------------------
                If carry = PreCarry Then
                    If count > (PreCount + DATA_NUM) Then
                        ' In order to display the count value to unsigned, convert it once through hexadecimal characters
                        str = String.Format("Overrun Error!(count = {0:d})", Convert.ToUInt32(Hex(count), 16))
                        txtError.Text = str
                        Exit Sub
                    End If
                End If
                '-----------------------------------
                ' If count value is same as previous, exit current operation
                ' (When it was called from the transfer completion message)
                '-----------------------------------
                If (count = PreCount) And (carry = PreCarry) Then
                    Exit Sub
                End If
                '-----------------------------------
                ' Write transferred data to file
                '-----------------------------------
                '-----------------------------------
                ' Open file
                '-----------------------------------
                Try
                    FileOpen(1, FileName, OpenMode.Append)
                Catch ex As Exception
                    txtReturn.Text = "fopen : file open error."
                    Exit Sub
                End Try
                '-----------------------------------
                ' Write data
                '-----------------------------------
                If WriteIndex > ReadIndex Then
                    ' In order to set the transferred count to signed, convert it once through hexadecimal characters
                    If Convert.ToUInt32(Hex(count), 16) > (WriteIndex - ReadIndex) Then
                        Cnt = Convert.ToUInt32(Hex(Convert.ToUInt32(Hex(count), 16) - (WriteIndex - ReadIndex)), 16)
                    Else
                        Cnt = Convert.ToUInt32(Hex(count - (WriteIndex - ReadIndex)), 16)
                    End If
                    For data_count = ReadIndex To WriteIndex - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                Else
                    ' In order to set the transferred count to signed, convert it once through hexadecimal characters
                    If Convert.ToUInt32(Hex(count), 16) > (DATA_NUM - ReadIndex + WriteIndex) Then
                        Cnt = Convert.ToUInt32(Hex(Convert.ToUInt32(Hex(count), 16) - (DATA_NUM - ReadIndex + WriteIndex)), 16)
                    Else
                        Cnt = Convert.ToUInt32(Hex(count - (DATA_NUM - ReadIndex + WriteIndex)), 16)
                    End If
                    For data_count = ReadIndex To DATA_NUM - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                    For data_count = 0 To WriteIndex - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                End If
                '-----------------------------------
                ' Close file
                '-----------------------------------
                FileClose(1)
                '-----------------------------------
                ' Set read pointer
                '-----------------------------------
                ReadIndex = WriteIndex
                PreCount = count
                PreCarry = carry
                '-----------------------------------
                ' Display transfer count value
                '-----------------------------------
                ' In order to display the count value to unsigned, convert it once through hexadecimal characters
                txtTransCount.Text = String.Format("{0:d}", Convert.ToUInt32(Hex(count), 16))

            Case CNTM_SAMPLING_STOP ' Transfer completion
                txtStatus.Text = "Stopped!"
                '-----------------------------------
                ' Retrieve transfer position on data buffer
                '-----------------------------------
                ret = CntGetSamplingWritePointer(Id, WriteIndex, count, carry)
                '-----------------------------------
                ' Check overflow error
                '-----------------------------------
                If carry = PreCarry Then
                    If count > (PreCount + DATA_NUM) Then
                        ' In order to display the count value to unsigned, convert it once through hexadecimal characters
                        str = String.Format("Overrun Error!(count = {0:d})", Convert.ToUInt32(Hex(count), 16))
                        txtError.Text = str
                        Exit Sub
                    End If
                End If
                '-----------------------------------
                ' If count value is same as previous, exit current operation
                ' (In case of called from transfer completion message)
                '-----------------------------------
                If (count = PreCount) And (carry = PreCarry) Then
                    Exit Sub
                End If
                '-----------------------------------
                ' Write transferred data to file
                '-----------------------------------
                '-----------------------------------
                ' Open file
                '-----------------------------------
                Try
                    FileOpen(1, FileName, OpenMode.Append)
                Catch ex As Exception
                    txtReturn.Text = "fopen : file open error."
                    Exit Sub
                End Try
                '-----------------------------------
                ' Write data
                '-----------------------------------
                If WriteIndex > ReadIndex Then
                    ' In order to set the transferred count to signed, convert it once through hexadecimal characters
                    If Convert.ToUInt32(Hex(count), 16) > (WriteIndex - ReadIndex) Then
                        Cnt = Convert.ToUInt32(Hex(Convert.ToUInt32(Hex(count), 16) - (WriteIndex - ReadIndex)), 16)
                    Else
                        Cnt = Convert.ToUInt32(Hex(count - (WriteIndex - ReadIndex)), 16)
                    End If
                    For data_count = ReadIndex To WriteIndex - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                Else
                    ' In order to set the transferred count to signed, convert it once through hexadecimal characters
                    If Convert.ToUInt32(Hex(count), 16) > (DATA_NUM - ReadIndex + WriteIndex) Then
                        Cnt = Convert.ToUInt32(Hex(Convert.ToUInt32(Hex(count), 16) - (DATA_NUM - ReadIndex + WriteIndex)), 16)
                    Else
                        Cnt = Convert.ToUInt32(Hex(count - (DATA_NUM - ReadIndex + WriteIndex)), 16)
                    End If
                    For data_count = ReadIndex To DATA_NUM - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                    For data_count = 0 To WriteIndex - 1
                        buf = String.Format("{0:d8}: ", Cnt)
                        For ch_no = 0 To CHANNEL_NUM - 2
                            buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        Next ch_no
                        buf = String.Format("{0}{1:X8}, ", buf, SamplingData(data_count, ch_no))
                        PrintLine(1, buf)

                        If Cnt = UInteger.MaxValue Then
                            Cnt = 0
                        Else
                            Cnt = Cnt + 1
                        End If
                    Next data_count
                End If
                '-----------------------------------
                ' Close file
                '-----------------------------------
                FileClose(1)
                '-----------------------------------
                ' Set read pointer
                '-----------------------------------
                ReadIndex = WriteIndex
                PreCount = count
                PreCarry = carry
                '-----------------------------------
                ' Display transf counter value
                '-----------------------------------
                ' In order to display the count value to unsigned, convert it once through hexadecimal characters
                txtTransCount.Text = String.Format("{0:d}", Convert.ToUInt32(Hex(count), 16))
        End Select
        MyBase.WndProc(m)

    End Sub
End Class
