﻿Option Strict Off
Option Explicit On
Imports System.Text

Public Class Form1
    Dim Id As Short ' Device ID
    Const MAX_SAMPLES As Short = 512 ' Number of the maximam samples
    Dim Data(MAX_SAMPLES) As Integer ' Array of retrieving data
    Dim UpperData(MAX_SAMPLES) As Integer ' Array which the upper bound data for waveform judgment are stored in
    Dim LowerData(MAX_SAMPLES) As Integer ' Array which the lower bound data for waveform judgment are stored in
    Dim Judge(1) As Short   ' Result of judgement
    Dim JudgeDetail(MAX_SAMPLES) As Short ' Details result of judgement
    Dim Records As Integer ' Number of retrieved record
    Dim Resolution As Integer ' The resolution of device
    Dim bmp As Bitmap    ' Bitmap

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        bmp = New Bitmap(Graph.Size.Width, Graph.Size.Height)    ' Create the bitmap which is compatible with the graph
    End Sub

    '==================================
    ' Init handling
    '==================================
    Private Sub CommandInit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandInit.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string

        '----------------------------------
        ' Init handling
        '----------------------------------
        Ret = DigInit(TextDevice.Text, Id)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigInit = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Reset device
        '----------------------------------
        Ret = DigResetDevice(Id)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigResetDevice = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        TextInfo.Text = "Init : Normality completion"
    End Sub

    '==================================
    ' Set device
    '==================================
    Private Sub CommandSetting_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandSetting.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string

        '----------------------------------
        ' Initialize variable
        '----------------------------------
        Records = 0
        Resolution = 1024   ' Fixed setting of DIG-100M1002-PCI

        '----------------------------------
        ' Set the operation mode : Waveform judgment instrument mode
        '----------------------------------
        Ret = DigSetDigitizerMode(Id, DIG_MODE_JUDGE)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetDigitizerMode = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        'Set the emergency halt factor of digitizer : Sampling clock error, Waveform judgment count match,
        '                                             Device memory overflow
        '----------------------------------
        Ret = DigSetHaltCondition(Id, DIG_HALT_CLOCK_ERROR Or DIG_HALT_JUDGE_COUNT Or DIG_HALT_DEVMEM_OVERFLOW)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetHaltCondition = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set sampling clock source : Crystal oscillator of board
        '----------------------------------
        Ret = DigSetClockSource(Id, DIG_ECU_SRC_CLOCK)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetClockSource = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set sampling rate : 1MHz
        '----------------------------------
        Ret = DigSetSampleRate(Id, 1000000)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetSampleRate = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set the length of record : 512
        '----------------------------------
        Ret = DigSetRecordLength(Id, MAX_SAMPLES)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetRecordLength = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set the number of records : Infinite
        '----------------------------------
        Ret = DigSetRecordNumber(Id, 0)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetRecordNumber = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set duty ratio : 50%
        '----------------------------------
        Ret = DigSetDutyCycle(Id, 50)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetDutyCycle = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set channel : Enable channel0 only
        '----------------------------------
        ' Enable channel0
        Ret = DigSetChannel(Id, DIG_CHANNEL0, DIG_ENABLE)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetChannel = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        ' Disable channel1
        Ret = DigSetChannel(Id, DIG_CHANNEL1, DIG_DISABLE)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetChannel = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set range : +/-20V
        '----------------------------------
        Ret = DigSetRange(Id, DIG_CHANNEL0, DIG_RANGE_40VPP)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetRange = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set the type of pre-trigger : Auto
        '----------------------------------
        Ret = DigSetPreTriggerType(Id, DIG_TRIGGERTYPE_AUTO)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetPreTriggerType = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set the type of post-trigger : Analog edge trigger
        '----------------------------------
        Ret = DigSetPostTriggerType(Id, DIG_TRIGGERTYPE_AIEDGE)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetPostTriggerType = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Detailed setting for the post-trigger : TriggerSource : channel0, Trigger level : 0V, Rising edge, 1
        '----------------------------------
        Ret = DigSetPostTriggerAiEdge(Id, DIG_CHANNEL0, 0, DIG_TRIGGER_SLOPE_RISE, 1)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetPostTriggerAiEdge = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Specify the channel to perform waveform judgment : Channel0
        '----------------------------------
        Ret = DigSetJudgeChannel(Id, DIG_CHANNEL0, DIG_ENABLE)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetJudgeChannel = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Set the upper bound value for counting the waveform judgment result : Count the FAIL records, The upper bound value of count times is 1
        '----------------------------------
        Ret = DigSetJudgeCountLimit(Id, DIG_CHANNEL0, DIG_JUDGE_NG, 1)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetJudgeCountLimit = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' Generate the data for waveform judgment automatically : Margin of horizontal axis : -10V to +10V, Margin of vertical axis : -50V to +50V, New
        '----------------------------------
        Ret = DigSetAutoMask(Id, DIG_CHANNEL0, 10, 50, DIG_AUTOMASK_NEW)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigSetAutoMask = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        ' Retrieve the data for waveform judgment which has been set to digitizer
        Ret = DigGetJudgeData32(Id, DIG_CHANNEL0, MAX_SAMPLES, UpperData, LowerData)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigGetJudgeData = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        TextInfo.Text = "Setting : Normality completion"
    End Sub

    '==================================
    ' Start judgement
    '==================================
    Private Sub CommandStart_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandStart.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string

        '----------------------------------
        ' Operation start
        '----------------------------------
        Ret = DigStart(Id)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigStart = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If
        TextInfo.Text = "Start judgement : Normality completion"

        '----------------------------------
        ' Polling until the operation status is changed to be OFF
        '----------------------------------
        Dim Status As Integer
        Dim NgCount As Integer   ' Fail times for the waveform judgment

        Do
            System.Windows.Forms.Application.DoEvents()    ' In order to enable the dialog operation
            '----------------------------------
            ' Get the number of records which are being stored in driver memory
            '----------------------------------
            Ret = DigGetDriverMemoryRecords(Id, Records)
            If Ret <> 0 Then
                Ret2 = DigGetErrorString(Ret, ErrorString)
                TextInfo.Text = "DigGetDriverMemoryRecords = " & Ret & " : " & ErrorString.ToString()
                Exit Sub
            End If

            '----------------------------------
            ' If there are records in driver memory, retrieve the data from the new side
            '----------------------------------
            If Records > 0 Or Records = -1 Then
                Ret = DigReadLatestRecords32(Id, DIG_RECORD_DATA, 1, Data, Judge, JudgeDetail)
                If Ret <> 0 Then
                    Ret2 = DigGetErrorString(Ret, ErrorString)
                    TextInfo.Text = "DigReadLatestRecords = " & Ret & " : " & ErrorString.ToString()
                    Exit Sub
                End If
                '----------------------------------
                ' Draw graph
                '----------------------------------
                DrawGraph()
            End If

            '----------------------------------
            ' Acquire fail times for the waveform judgment
            '----------------------------------
            Ret = DigGetJudgeCount(Id, NgCount)
            If Ret <> 0 Then
                Ret2 = DigGetErrorString(Ret, ErrorString)
                TextInfo.Text = "DigGetJudgeCount = " & Ret & " : " & ErrorString.ToString()
                Exit Sub
            End If
            LabelJudgeCount.Text = NgCount.ToString

            '----------------------------------
            ' Get the operation status
            '----------------------------------
            Ret = DigGetStatus(Id, Status)
            If Ret <> 0 Then
                Ret2 = DigGetErrorString(Ret, ErrorString)
                TextInfo.Text = "DigGetStatus = " & Ret & " : " & ErrorString.ToString()
                Exit Sub
            End If
            LabelStatus.Text = Hex(Status) & "H"
        Loop While (Status And DIG_STATUS_BUSY) = DIG_STATUS_BUSY

        '----------------------------------
        ' Acquire fail times for the waveform judgment
        '----------------------------------
        Ret = DigGetJudgeCount(Id, NgCount)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigGetJudgeCount = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If
        LabelJudgeCount.Text = NgCount.ToString

        '----------------------------------
        ' Acquire the number of records not yet acquired in the driver memory
        '----------------------------------
        Ret = DigGetDriverMemoryRecords(Id, Records)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigGetDriverMemoryRecords = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        '----------------------------------
        ' If there are records in driver memory, retrieve the data from the new side
        '----------------------------------
        If Records > 0 Or Records = -1 Then
            Ret = DigReadLatestRecords32(Id, DIG_RECORD_DATA, 1, Data, Judge, JudgeDetail)
            If Ret <> 0 Then
                Ret2 = DigGetErrorString(Ret, ErrorString)
                TextInfo.Text = "DigReadLatestRecords = " & Ret & " : " & ErrorString.ToString()
                Exit Sub
            End If
            '----------------------------------
            ' Draw graph
            '----------------------------------
            DrawGraph()
        End If

    End Sub

    '==================================
    ' Get status
    '==================================
    Private Sub CommandInfo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandInfo.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string
        Dim Status As Integer    ' Status

        '----------------------------------
        ' Get the operation status
        '----------------------------------
        Ret = DigGetStatus(Id, Status)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigGetStatus = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If
        LabelStatus.Text = Hex(Status) & "H"

        TextInfo.Text = "Get Status : Normality completion"
    End Sub

    '==================================
    ' Stop judgement
    '==================================
    Private Sub CommandStop_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandStop.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string

        Ret = DigStop(Id)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigExit = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        TextInfo.Text = "Stop judgement : Normality completion"
    End Sub


    '==================================
    ' Exit handling
    '==================================
    Private Sub CommandExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CommandExit.Click
        Dim Ret As Integer    ' Return value
        Dim Ret2 As Integer   ' Return value2
        Dim ErrorString As New StringBuilder("", 256)     ' Error string

        Ret = DigExit(Id)
        If Ret <> 0 Then
            Ret2 = DigGetErrorString(Ret, ErrorString)
            TextInfo.Text = "DigExit = " & Ret & " : " & ErrorString.ToString()
            Exit Sub
        End If

        TextInfo.Text = "Exit : Normality completion"
    End Sub

    '==================================
    ' Form unload
    '==================================
    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        Dim Ret As Integer    ' Return value
        Ret = DigExit(Id)
    End Sub

    '==================================
    ' Draw graph
    '==================================
    Private Sub DrawGraph()
        Dim XUnit As Single   ' Drawing unit of X axis
        Dim PosX As Single    ' Drawing coordinate of X axis
        Dim PosY As Single    ' Drawing coordinate of Y axis
        Dim OldX As Single    ' For saving the drawing coordinate of X axis
        Dim OldY As Single    ' For saving the drawing coordinate of Y axis
        Dim i As Integer
        Dim j As Integer

        '-----------------------------------------
        ' Draw the current data in graph
        '-----------------------------------------
        Dim pen As New Pen(System.Drawing.Color.Red, 1)  ' Create red pen
        Graph.Image = bmp
        Dim grp As Graphics = Graphics.FromImage(Graph.Image)  ' Create a new graphics object from the specified image object
        grp.Clear(Graph.BackColor)                             ' Clear the graph

        XUnit = Graph.Size.Width() / CSng(MAX_SAMPLES)  ' Calculate the moving pixel number of X axis for data 1
        For i = 0 To 2
            OldX = 0
            Select Case i
                Case 0
                    ' Set the origin position of upper data
                    OldY = Graph.Height * (Resolution - UpperData(0)) / CSng(Resolution)     ' Calculate the coordinate of Y axis
                Case 1
                    ' Set the origin position of lower data
                    OldY = Graph.Height * (Resolution - LowerData(0)) / CSng(Resolution)     ' Calculate the coordinate of Y axis

                Case 2
                    ' Set the origin position of retrieving data
                    OldY = Graph.Height * (Resolution - Data(0)) / CSng(Resolution)     ' Calculate the coordinate of Y axis
            End Select
            If OldY >= Graph.Height Then
                OldY = Graph.Height - 1      ' If the initial value of Y axis exceeds the drawing rect of graph, modify the drawing position
            End If
            If OldY < 0 Then
                OldY = 0     ' If the coordinate of Y axis is lower than the drawing rect, modify the drawing position
            End If

            '----------------------------------------------------
            ' Repeat the drawing handling only for the times which is equal to the numer of acquisition data
            '----------------------------------------------------
            For j = 1 To MAX_SAMPLES - 1
                PosX = OldX + XUnit      ' Calculate the coordinate of X axis
                Select Case i
                    Case 0
                        ' Set the drawing position of upper data
                        PosY = Graph.Height * (Resolution - UpperData(j)) / CSng(Resolution)        ' Calculate the coordinate of Y axis
                    Case 1
                        ' Set the drawing position of lower data
                        PosY = Graph.Height * (Resolution - LowerData(j)) / CSng(Resolution)        ' Calculate the coordinate of Y axis

                    Case 2
                        ' Set the drawing position of retrieving data
                        PosY = Graph.Height * (Resolution - Data(j)) / CSng(Resolution)        ' Calculate the coordinate of Y axis
                End Select
                If PosY >= Graph.Height() Then
                    ' If the coordinate of Y axis exceeds the drawing rect
                    PosY = Graph.Height() - 1       ' Modify the drawing position

                ElseIf PosY < 0 Then
                    ' If the coordinate of Y axis is lower than the drawing rect
                    PosY = 0       ' Modify the drawing position
                End If
                grp.DrawLine(pen, OldX, OldY, PosX, PosY)     ' Draw

                OldX = PosX      ' Save the drawing coordinate of X axis
                OldY = PosY      ' Save the drawing coordinate of Y axis
            Next j
        Next i
        pen.Dispose()   ' Reales all resoures used by this pen object
        grp.Dispose()   ' Reales all resoures used by this graphics object
    End Sub
End Class
