VERSION 5.00
Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
Object = "{5E9E78A0-531B-11CF-91F6-C2863C385E30}#1.0#0"; "MSFLXGRD.OCX"
Begin VB.Form frmCSDJ 
   Caption         =   "CSDJ Comm Control "
   ClientHeight    =   8715
   ClientLeft      =   60
   ClientTop       =   345
   ClientWidth     =   11940
   BeginProperty Font 
      Name            =   "Tahoma"
      Size            =   9
      Charset         =   0
      Weight          =   400
      Underline       =   0   'False
      Italic          =   0   'False
      Strikethrough   =   0   'False
   EndProperty
   Icon            =   "frmCSDJ.frx":0000
   LinkTopic       =   "Form1"
   ScaleHeight     =   8715
   ScaleWidth      =   11940
   StartUpPosition =   2  '화면 가운데
   Begin VB.Frame Frame6 
      Caption         =   "MOR Command - For Monitoring"
      Height          =   1425
      Left            =   30
      TabIndex        =   49
      Top             =   7170
      Width           =   7875
      Begin VB.TextBox txtMORValue 
         Height          =   345
         Index           =   2
         Left            =   2700
         TabIndex        =   58
         Top             =   930
         Width           =   1095
      End
      Begin VB.CommandButton cmdSendMOR 
         Caption         =   "Send MOR Cmd."
         Height          =   825
         Left            =   3900
         TabIndex        =   57
         Top             =   480
         Width           =   1485
      End
      Begin VB.TextBox txtMORValue 
         Height          =   345
         Index           =   1
         Left            =   1800
         TabIndex        =   56
         Top             =   930
         Width           =   825
      End
      Begin VB.TextBox txtMORValue 
         Height          =   345
         Index           =   0
         Left            =   900
         TabIndex        =   55
         Top             =   930
         Width           =   825
      End
      Begin VB.ComboBox cbVarMORNumber 
         Height          =   330
         Index           =   1
         Left            =   1800
         TabIndex        =   52
         Top             =   480
         Width           =   825
      End
      Begin VB.ComboBox cbVarMORNumber 
         Height          =   330
         Index           =   0
         Left            =   900
         TabIndex        =   51
         Top             =   480
         Width           =   825
      End
      Begin VB.Label Label3 
         Caption         =   "Value"
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   1
         Left            =   180
         TabIndex        =   54
         Top             =   990
         Width           =   525
      End
      Begin VB.Label Label5 
         Caption         =   "NO1         NO2            I/O"
         Height          =   255
         Index           =   1
         Left            =   1080
         TabIndex        =   53
         Top             =   210
         Width           =   2775
      End
      Begin VB.Label Label4 
         Caption         =   "Variable Number"
         ForeColor       =   &H00FF0000&
         Height          =   405
         Index           =   1
         Left            =   120
         TabIndex        =   50
         Top             =   450
         Width           =   675
      End
   End
   Begin VB.Frame Frame5 
      Caption         =   "MDM Commnsd - For Monitoring"
      Height          =   1455
      Left            =   30
      TabIndex        =   34
      Top             =   5610
      Width           =   7845
      Begin VB.TextBox txtMDMValue 
         Height          =   345
         Index           =   4
         Left            =   4290
         Locked          =   -1  'True
         TabIndex        =   48
         Top             =   960
         Width           =   765
      End
      Begin VB.CommandButton cmdClearMDM 
         Caption         =   "Clear Value"
         Height          =   495
         Left            =   5370
         TabIndex        =   47
         Top             =   840
         Width           =   2295
      End
      Begin VB.TextBox txtMDMValue 
         Height          =   345
         Index           =   3
         Left            =   3450
         Locked          =   -1  'True
         TabIndex        =   46
         Top             =   960
         Width           =   765
      End
      Begin VB.TextBox txtMDMValue 
         Height          =   345
         Index           =   2
         Left            =   2610
         Locked          =   -1  'True
         TabIndex        =   45
         Top             =   960
         Width           =   765
      End
      Begin VB.TextBox txtMDMValue 
         Height          =   345
         Index           =   1
         Left            =   1740
         Locked          =   -1  'True
         TabIndex        =   44
         Top             =   960
         Width           =   765
      End
      Begin VB.CommandButton SendMDM 
         Caption         =   "Send MDM Cmd."
         Height          =   495
         Left            =   5370
         TabIndex        =   43
         Top             =   270
         Width           =   2295
      End
      Begin VB.ComboBox cbVariableNumber 
         Enabled         =   0   'False
         Height          =   330
         Index           =   3
         Left            =   3450
         TabIndex        =   41
         Top             =   570
         Width           =   765
      End
      Begin VB.ComboBox cbVariableNumber 
         Enabled         =   0   'False
         Height          =   330
         Index           =   2
         Left            =   2610
         TabIndex        =   40
         Top             =   570
         Width           =   765
      End
      Begin VB.ComboBox cbVariableNumber 
         Enabled         =   0   'False
         Height          =   330
         Index           =   1
         Left            =   1740
         TabIndex        =   39
         Top             =   570
         Width           =   765
      End
      Begin VB.TextBox txtMDMValue 
         Height          =   345
         Index           =   0
         Left            =   870
         Locked          =   -1  'True
         TabIndex        =   36
         Top             =   960
         Width           =   765
      End
      Begin VB.ComboBox cbVariableNumber 
         Height          =   330
         Index           =   0
         Left            =   870
         TabIndex        =   35
         Top             =   570
         Width           =   765
      End
      Begin VB.Label Label5 
         Caption         =   "NO1         NO2        NO3        NO4        I/O"
         Height          =   255
         Index           =   0
         Left            =   1050
         TabIndex        =   42
         Top             =   300
         Width           =   3915
      End
      Begin VB.Label Label4 
         Caption         =   "Variable Number"
         ForeColor       =   &H00FF0000&
         Height          =   405
         Index           =   0
         Left            =   120
         TabIndex        =   38
         Top             =   540
         Width           =   675
      End
      Begin VB.Label Label3 
         Caption         =   "Value"
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   0
         Left            =   180
         TabIndex        =   37
         Top             =   1050
         Width           =   525
      End
   End
   Begin VB.CommandButton cmdPacketStructure 
      Caption         =   "Packet Structure"
      Height          =   495
      Left            =   6435
      TabIndex        =   33
      Top             =   765
      Width           =   1335
   End
   Begin MSComDlg.CommonDialog cdLoad 
      Left            =   10020
      Top             =   8100
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
      InitDir         =   "c:\"
   End
   Begin MSComDlg.CommonDialog cdSave 
      Left            =   9420
      Top             =   8100
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
      InitDir         =   "c:\"
   End
   Begin VB.ListBox lstCommLogHex 
      Height          =   3840
      Left            =   7980
      TabIndex        =   27
      ToolTipText     =   "Display Communication Log with Hex"
      Top             =   4050
      Width           =   3945
   End
   Begin VB.CommandButton cmdClearLog 
      Caption         =   "Clear Log"
      Height          =   435
      Left            =   10290
      TabIndex        =   26
      Top             =   8130
      Width           =   1575
   End
   Begin VB.ListBox lstCommLog 
      Height          =   3840
      Left            =   7980
      TabIndex        =   18
      ToolTipText     =   "Display Communication Log with Text"
      Top             =   90
      Width           =   3855
   End
   Begin VB.Frame Frame4 
      Caption         =   "Request Parameter"
      Height          =   3225
      Left            =   0
      TabIndex        =   16
      Top             =   2340
      Width           =   7875
      Begin MSFlexGridLib.MSFlexGrid gridParameter 
         Height          =   2895
         Left            =   120
         TabIndex        =   32
         Top             =   240
         Width           =   4695
         _ExtentX        =   8281
         _ExtentY        =   5106
         _Version        =   393216
         AllowBigSelection=   0   'False
      End
      Begin VB.CommandButton cmdViewParam 
         Caption         =   "Edit Parameter File"
         Height          =   495
         Left            =   4980
         TabIndex        =   30
         ToolTipText     =   "Edit/View Parameter File"
         Top             =   2640
         Width           =   2715
      End
      Begin VB.CommandButton cmdLoad 
         Caption         =   "Load Param."
         Height          =   495
         Left            =   6420
         TabIndex        =   29
         ToolTipText     =   "Load Parameters from File"
         Top             =   1980
         Width           =   1275
      End
      Begin VB.CommandButton cmdSave 
         Caption         =   "Save Param."
         Height          =   495
         Left            =   4980
         TabIndex        =   28
         ToolTipText     =   "Save Parameters to File"
         Top             =   1980
         Width           =   1335
      End
      Begin VB.ComboBox cbGridNumber 
         Height          =   330
         ItemData        =   "frmCSDJ.frx":0ECA
         Left            =   4980
         List            =   "frmCSDJ.frx":0ECC
         TabIndex        =   25
         Top             =   1380
         Width           =   1155
      End
      Begin VB.CommandButton cmdChangeParameter 
         Caption         =   "Download Parameters"
         Height          =   615
         Left            =   6240
         TabIndex        =   24
         ToolTipText     =   "Download Parameters To CSDJ Servo Drive"
         Top             =   1080
         Width           =   1455
      End
      Begin VB.CommandButton cmdRequestParameter 
         Caption         =   "Upload Parameters"
         Height          =   615
         Left            =   4980
         TabIndex        =   17
         ToolTipText     =   "Upload Parameters from CSDJ Servo Drive"
         Top             =   240
         Width           =   2715
      End
      Begin VB.Label Label2 
         Caption         =   "Number"
         Height          =   255
         Left            =   4980
         TabIndex        =   31
         Top             =   1140
         Width           =   795
      End
   End
   Begin VB.Frame Frame3 
      Caption         =   "Jog Mode"
      Height          =   855
      Left            =   2820
      TabIndex        =   15
      Top             =   1380
      Width           =   5025
      Begin VB.CommandButton cmdJogFinish 
         Caption         =   "Finish"
         Height          =   495
         Left            =   3600
         TabIndex        =   23
         ToolTipText     =   "Finish Jog Mode"
         Top             =   240
         Width           =   1275
      End
      Begin VB.CommandButton cmdMinusDirection 
         Caption         =   "(-)"
         Height          =   495
         Left            =   2580
         TabIndex        =   22
         ToolTipText     =   "Turn (-) Direction"
         Top             =   240
         Width           =   675
      End
      Begin VB.CommandButton cmdPlusDIrection 
         Caption         =   "(+)"
         Height          =   495
         Left            =   1860
         TabIndex        =   21
         ToolTipText     =   "Turn (+) Direction"
         Top             =   240
         Width           =   675
      End
      Begin VB.CommandButton cmdEnterJogMode 
         Caption         =   "Enter Jog Mode"
         Height          =   495
         Left            =   180
         TabIndex        =   20
         ToolTipText     =   "Enter Jog Mode"
         Top             =   240
         Width           =   1275
      End
   End
   Begin VB.Frame Frame2 
      Caption         =   "Auto Tuning"
      Height          =   855
      Left            =   0
      TabIndex        =   14
      Top             =   1380
      Width           =   2655
      Begin VB.CommandButton cmdAutoTuning 
         Caption         =   "Send AutoTuning Command"
         Height          =   495
         Left            =   420
         TabIndex        =   19
         ToolTipText     =   "Auto Tuning Command"
         Top             =   240
         Width           =   1875
      End
   End
   Begin MSCommLib.MSComm commTest 
      Left            =   8100
      Top             =   8100
      _ExtentX        =   1005
      _ExtentY        =   1005
      _Version        =   393216
      DTREnable       =   -1  'True
   End
   Begin VB.CommandButton cmdEnd 
      Caption         =   "End"
      Height          =   495
      Left            =   6435
      TabIndex        =   1
      Top             =   120
      Width           =   1335
   End
   Begin VB.Frame Frame1 
      Height          =   1215
      Left            =   0
      TabIndex        =   0
      Top             =   60
      Width           =   6135
      Begin VB.ComboBox cbParityBit 
         Height          =   330
         Left            =   4920
         TabIndex        =   13
         Text            =   "Combo5"
         Top             =   720
         Width           =   1035
      End
      Begin VB.ComboBox cbBaudRate 
         Height          =   330
         Left            =   5040
         TabIndex        =   12
         Text            =   "Combo4"
         Top             =   240
         Width           =   915
      End
      Begin VB.ComboBox cbStopBit 
         Height          =   330
         Left            =   2880
         TabIndex        =   11
         Text            =   "Combo3"
         Top             =   720
         Width           =   855
      End
      Begin VB.ComboBox cbDataBit 
         Height          =   330
         Left            =   840
         TabIndex        =   10
         Text            =   "Combo2"
         Top             =   720
         Width           =   1035
      End
      Begin VB.CommandButton cmdPortOpen 
         Caption         =   "Open Port"
         Height          =   315
         Left            =   2580
         TabIndex        =   5
         ToolTipText     =   "Open Comm Port"
         Top             =   240
         Width           =   1215
      End
      Begin VB.CommandButton cmdCommTest 
         Caption         =   "Test"
         Height          =   315
         Left            =   1980
         TabIndex        =   4
         ToolTipText     =   "Test Port"
         Top             =   240
         Width           =   555
      End
      Begin VB.ComboBox cbPort 
         Height          =   330
         Left            =   840
         TabIndex        =   3
         Text            =   "Combo1"
         Top             =   240
         Width           =   1095
      End
      Begin VB.Label Label1 
         Caption         =   "ParityBit"
         BeginProperty Font 
            Name            =   "굴림"
            Size            =   9
            Charset         =   129
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   4
         Left            =   4080
         TabIndex        =   9
         Top             =   780
         Width           =   855
      End
      Begin VB.Label Label1 
         Caption         =   "StopBit"
         BeginProperty Font 
            Name            =   "굴림"
            Size            =   9
            Charset         =   129
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   3
         Left            =   2220
         TabIndex        =   8
         Top             =   780
         Width           =   615
      End
      Begin VB.Label Label1 
         Caption         =   "DataBit"
         BeginProperty Font 
            Name            =   "굴림"
            Size            =   9
            Charset         =   129
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   2
         Left            =   120
         TabIndex        =   7
         Top             =   780
         Width           =   615
      End
      Begin VB.Label Label1 
         Caption         =   "BaudRate"
         BeginProperty Font 
            Name            =   "굴림"
            Size            =   9
            Charset         =   129
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   1
         Left            =   4020
         TabIndex        =   6
         Top             =   300
         Width           =   915
      End
      Begin VB.Label Label1 
         Caption         =   "PORT"
         BeginProperty Font 
            Name            =   "굴림"
            Size            =   9
            Charset         =   129
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         ForeColor       =   &H000000FF&
         Height          =   255
         Index           =   0
         Left            =   120
         TabIndex        =   2
         Top             =   300
         Width           =   615
      End
   End
   Begin MSCommLib.MSComm commCSDJ 
      Left            =   8700
      Top             =   8100
      _ExtentX        =   1005
      _ExtentY        =   1005
      _Version        =   393216
      DTREnable       =   -1  'True
      InBufferSize    =   2048
      RThreshold      =   1
      InputMode       =   1
   End
   Begin VB.Timer tmrCSDJ 
      Enabled         =   0   'False
      Interval        =   150
      Left            =   7890
      Top             =   8070
   End
End
Attribute VB_Name = "frmCSDJ"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'==========================================================================
'Sample Name  : CSDJ Servo Drive Communication Control Software
'Purpose      : 1. Control CSDJ Servo by User Application
'               2. Coding with 3-Types Sample
'                 (1) Used By MSComm Control in Visual Basic 6
'                 (2) Used By Communication Class in Visual Basic.Net 2003 ==> Not Released
'                 (3) Used By Serial Port Control in Visual Basic 2005 ==> Another Sample
'Environment  : WIndows XP Pro-SP2, Visual Basic 6.0
'Date         : 1st : 2006/08/21 ~ 22
'             : 2nd : Modified 2006/08/24
'Coding       : Kijoon Kim ( kjkim@ra.rockwell.com )
'Depart       : Rockwell Automation Korea, Samsung / OEMax Business
'               Strategic Marketing
'==========================================================================
'2006/08/29   : Add Load/Save Parameter Function
'==========================================================================
Option Explicit

'--------------------------------------------
'Define Global Variable
'--------------------------------------------
Dim CommSettingString As String

Dim SB() As Byte    'Buffer for Send
Dim SBB() As Byte   'Buffer for Re-Send
Dim RB(1024) As Byte    'Buffer for Receive
Dim RB_0(1024) As Byte    'Buffer for Receive
Dim ANS_BUFFER(255) As Byte
Dim m_OFFSET As Integer
Dim RETRY_COUNT As Integer
Dim SCOMM_STATUS As Integer
Dim RCOMM_STATUS As Integer
Dim ReceivedFlag As Boolean
Dim ANS_FLAG As Integer
Dim MDMASC() As Byte
Dim MORASC() As Byte

'--------------------------------------------
'
'--------------------------------------------
Dim MousePos As POINTAPI


'--------------------------------------------
'
'--------------------------------------------
Private Sub cmdClearLog_Click()
    lstCommLog.Clear
    lstCommLogHex.Clear
End Sub


'--------------------------------------------
'Test COM Port whether it is available or not
'--------------------------------------------
Private Sub cmdCommTest_Click()
    On Error GoTo PortOpenError
    
    If cbPort.Text = "" Then Exit Sub
    commTest.CommPort = CInt(Mid(cbPort.Text, 4))
    commTest.PortOpen = True
    If commTest.PortOpen = True Then
'        MsgBox "OK. You can use this Port.", vbOKOnly, "Comm. Port"
        commTest.PortOpen = False
        
        'Open Comm. Port
        commCSDJ.CommPort = CInt(Mid(cbPort.Text, 4))
'        commCSDJ.PortOpen = True
        
        cmdPortOpen.Enabled = True
    
    End If
    Exit Sub
PortOpenError:
    MsgBox "Error !!", vbOKOnly, "Comm. Port"
    Select Case Err.Number
        Case 8005
            MsgBox "Already Using Port !! Please Select Another Port", vbOKOnly, "Error"
            Exit Sub
        Case Else
            MsgBox CStr(Err.Number) + " " + Err.Description, vbOKOnly, "Error"
    End Select
    cmdPortOpen.Enabled = False

End Sub

'--------------------------------------------
'Enter Jog Mode Command
'--------------------------------------------
Private Sub cmdEnterJogMode_Click()
        Dim JogMode
        Dim SVRON
        Dim i As Integer
        
        If commCSDJ.PortOpen = False Then
            MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
            Exit Sub
        End If
        
        JogMode = Array(&H2, &H30, &H23, &H4A, &H4F, &H47, &H30, &H33, &H3) '[STX]0#JOG03[ETX]
        SVRON = Array(&H2, &H30, &H23, &H53, &H56, &H52, &H4F, &H4E, &H42, &H3) '[STX]0#SVRONB[ETX]

        'Send Enter Jog Model Command
        If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
            SCOMM_STATUS = ST_JOG
            ReDim SB(0 To UBound(JogMode, 1))
            For i = 0 To UBound(JogMode, 1)
                SB(i) = JogMode(i)
            Next i
            SB_Backup SB
            commCSDJ.Output = SB
            RCOMM_STATUS = ST_WAIT
            AddCommLog "Send [STX]0#JOG03[ETX]"
        End If

        'Wating for ACK
        Do
            DoEvents
        Loop While (RCOMM_STATUS = ST_WAIT)

        'Send SVRON Command
        If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
            SCOMM_STATUS = ST_SVR1
            ReDim SB(0 To UBound(SVRON, 1))
            For i = 0 To UBound(SVRON, 1)
                SB(i) = SVRON(i)
            Next i
            SB_Backup SB
            commCSDJ.Output = SB
            RCOMM_STATUS = ST_WAIT
            AddCommLog "Send [STX]0#SVRONB[ETX]"
        End If
        tmrCSDJ.Enabled = True
End Sub

'--------------------------------------------
'Finish Jog Mode
'--------------------------------------------
Private Sub cmdJogFinish_Click()
    Dim SVROFF
    Dim i As Integer
        
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
        
    SVROFF = Array(&H2, &H30, &H23, &H53, &H56, &H52, &H4F, &H46, &H46, &H39, &H3) '[STX]0#SVROFF9[ETX]
    If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
        SCOMM_STATUS = ST_SVR2
        ReDim SB(0 To UBound(SVROFF, 1))
        For i = 0 To UBound(SVROFF, 1)
            SB(i) = SVROFF(i)
        Next i
        SB_Backup SB
        commCSDJ.Output = SB
        RCOMM_STATUS = ST_WAIT
        AddCommLog "Send [STX]0#SVROFF9[ETX]"
    End If
    tmrCSDJ.Enabled = False
End Sub

'--------------------------------------------
'Jog to Minus Direction
'--------------------------------------------
Private Sub cmdMinusDirection_Click()
    Dim JogMin
    Dim i As Integer
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    JogMin = Array(&H2, &H30, &H23, &H4A, &H4F, &H47, &H2D, &H30, &H3)  '[STX]0#JOG-0[ETX]
    
    If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
        SCOMM_STATUS = ST_JOG
        ReDim SB(0 To UBound(JogMin, 1))
        For i = 0 To UBound(JogMin, 1)
            SB(i) = JogMin(i)
        Next i
        SB_Backup SB
        commCSDJ.Output = SB
        RCOMM_STATUS = ST_WAIT
        AddCommLog "Send [STX]0#JOG-0[ETX]"
    End If
        
End Sub

Private Sub cmdPacketStructure_Click()
    frmPacketStructure.Show
End Sub

'--------------------------------------------
'Jog to Plus Direction
'--------------------------------------------
Private Sub cmdPlusDIrection_Click()
    Dim JogPlus
    Dim i As Integer
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    JogPlus = Array(&H2, &H30, &H23, &H4A, &H4F, &H47, &H2B, &H45, &H3)  '[STX]0#JOG+E[ETX]
    
    If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
        SCOMM_STATUS = ST_JOG
        ReDim SB(0 To UBound(JogPlus, 1))
        For i = 0 To UBound(JogPlus, 1)
            SB(i) = JogPlus(i)
        Next i
        SB_Backup SB
        commCSDJ.Output = SB
        RCOMM_STATUS = ST_WAIT
        AddCommLog "Send [STX]0#JOG+E[ETX]"
    End If
End Sub

'--------------------------------------------
'Initializing Each control after opening port
'--------------------------------------------
Private Sub cmdPortOpen_Click()
    Select Case cmdPortOpen.Caption
        Case "Open Port"
            cmdPortOpen.Caption = "Close Port"
            'Comm Port Open
            commCSDJ.InputMode = comInputModeBinary
            commCSDJ.Settings = CommSetting
            commCSDJ.PortOpen = True
            cmdCommTest.Enabled = False
            
            cbPort.Enabled = False
            cbBaudRate.Enabled = False
            cbDataBit.Enabled = False
            cbStopBit.Enabled = False
            cbParityBit.Enabled = False
            
        Case "Close Port"
            cmdPortOpen.Caption = "Open Port"
            commCSDJ.PortOpen = False
            cmdCommTest.Enabled = True
            cbPort.Enabled = True
            cbBaudRate.Enabled = True
            cbDataBit.Enabled = True
            cbStopBit.Enabled = True
            cbParityBit.Enabled = True
            
            'Timer Disable
            tmrCSDJ.Enabled = False
    End Select
End Sub

'--------------------------------------------
'Communication Port Setting
'--------------------------------------------
Private Function CommSetting() As String
    Dim T As String
    
    CommSettingString = ""
    
    'Get Baudrate Data
    If cbBaudRate.Text = "" Then cbBaudRate.Text = "9600"
    CommSettingString = CommSettingString + cbBaudRate.Text + ","
    
    'Get ParityBit Data
    If cbParityBit.Text = "" Then cbParityBit.Text = "NONE"
    Select Case cbParityBit.Text
        Case "NONE"
            CommSettingString = CommSettingString + "n,"
        Case "EVEN"
            CommSettingString = CommSettingString + "e,"
        Case "ODD"
            CommSettingString = CommSettingString + "o,"
    End Select
    
    'Get Databit
    If cbDataBit.Text = "" Then cbDataBit.Text = "8"
    CommSettingString = CommSettingString + cbDataBit.Text + ","
    
    If cbStopBit.Text = "" Then cbStopBit.Text = "1"
    CommSettingString = CommSettingString + cbStopBit.Text
    
    CommSetting = CommSettingString
End Function




'--------------------------------------------
'Event when Main form load
'--------------------------------------------
Private Sub Form_Load()
    Dim i As Integer
    Dim j As Integer
    Dim S As String
    
    'Port Setup
    Dim Port
    Port = Array("COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10")
    'Baudrate Setup
    Dim Baud
    Baud = Array("38400", "19200", "9600", "4800", "2400")
    'Databit Setup
    Dim DBit
    DBit = Array("8", "7", "6")
    'Stopbit
    Dim SBit
    SBit = Array("1", "2")
    'ParityBit
    Dim PBit
    PBit = Array("NONE", "EVEN", "ODD")
    
'   Dim MDM
'   MDM = Array("Velocity Feedback", "Velocity Command")
    '------------------------------
    'Fill Combobox
    '------------------------------
    
    'Clear Combo Box
    ClearAllComboBox
    
    cmdPortOpen.Enabled = False
    
    'Fill Data to Each ComboBox
    For i = 1 To 10
        cbPort.AddItem (Port(i - 1))
    Next i
    cbPort.Text = "COM1"
    
    For i = 1 To 5
        cbBaudRate.AddItem (Baud(i - 1))
    Next i
    cbBaudRate.Text = "9600"
    
    For i = 1 To 3
        cbDataBit.AddItem (DBit(i - 1))
    Next i
    cbDataBit.Text = "8"
    
    For i = 1 To 2
        cbStopBit.AddItem (SBit(i - 1))
    Next i
    cbStopBit.Text = "1"
    
    For i = 1 To 3
        cbParityBit.AddItem (PBit(i - 1))
    Next i
    cbParityBit.Text = "NONE"
    
    cbGridNumber.AddItem "All"
    For i = 1 To 99
        cbGridNumber.AddItem CStr(i)
    Next i
    
    'Fill MDM Command - ComboBox
    For i = 0 To 3
        cbVariableNumber(i).AddItem ""
        For j = 1 To 13
            S = Right("00" + CStr(j), 2)
            cbVariableNumber(i).AddItem S
        Next j
    Next i
        
'    Dim MDM
'    MDM = Array(&H2, &H30, &H23, &H4D, &H44, &H4D, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H3)      '[STX]0#01020304[CRC][ETX]
'    For i = 0 To 15
'        MDMASC(i) = MDM(i)
'    Next i
'
    For i = 1 To 3
        cbVariableNumber(i).Enabled = False
    Next i

    'Fill MOR Command - ComboBox
    For i = 0 To 1
        cbVarMORNumber(i).AddItem ""
        For j = 1 To 7
            S = Right("00" + CStr(j), 2)
            cbVarMORNumber(i).AddItem S
        Next j
    Next i

End Sub

'--------------------------------------------
'--------------------------------------------
Private Sub cmdClearMDM_Click()
    Dim i As Integer
    For i = 0 To 4
        txtMDMValue(i).Text = ""
    Next i
End Sub

'--------------------------------------------
'Clear All Combo Box
'--------------------------------------------
Private Sub ClearAllComboBox()
    cbPort.Clear
    cbBaudRate.Clear
    cbDataBit.Clear
    cbStopBit.Clear
    cbParityBit.Clear
End Sub

'--------------------------------------------
'When Form_Unload, Close Port
'--------------------------------------------
Private Sub Form_Unload(Cancel As Integer)
    If commCSDJ.PortOpen = True Then
        commCSDJ.PortOpen = False
        Unload frmMonitoringData
        Unload frmPacketStructure
        Unload frmWriteWord
    Else
    
    End If
End Sub

'--------------------------------------------
'End of program
'--------------------------------------------
Private Sub cmdEnd_Click()
    If commCSDJ.PortOpen = True Then
        commCSDJ.PortOpen = False
    End If
    tmrCSDJ.Enabled = False
    End
End Sub


'--------------------------------------------
'Transmit Auto Tuning Command
'--------------------------------------------
Private Sub cmdAutoTuning_Click()
        Dim TAT
        Dim i As Integer
        
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    TAT = Array(&H2, &H30, &H23, &H54, &H41, &H54, &H31, &H44, &H3) '[STX]0#TAT1D[ETX]
    SCOMM_STATUS = ST_TAT
    ReDim SB(0 To UBound(TAT, 1))
    For i = 0 To UBound(TAT, 1)
        SB(i) = TAT(i)
    Next i
    SB_Backup SB
    commCSDJ.Output = SB
    
    AddCommLog "Send [STX]0#TAT1D[ETX]"

End Sub

'--------------------------------------------
'Comminication Control (MSComm) Event
'Alreadt, I set RThreshord value to 1, then
'This event will be call each data.
'--------------------------------------------
Private Sub commCSDJ_OnComm()
    Dim DataLength As Byte
    Dim T1 As Byte
    Dim i As Integer
    Dim AB() As Byte
    Dim L As Integer
    Dim OFS As Integer
    Dim TP(0 To 0) As Byte
    Dim R() As Byte
    Dim S As String
    '----------------------
    Dim T
    Dim j As Integer

    ReceivedFlag = True     'Flag for meaning Receiveing Data

    Select Case commCSDJ.CommEvent
        Case comEvReceive
            OFS = commCSDJ.InBufferCount
            'Wait for finishing data
            Do
                R = commCSDJ.Input
                For i = 0 To OFS - 1
                    RB(m_OFFSET + i) = R(i)
                Next i
                'Add Offset Value
                m_OFFSET = m_OFFSET + OFS
                'GIve a right to OS for
                DoEvents
                OFS = commCSDJ.InBufferCount
            Loop While (OFS > 0)

            'Compare 1 Byte Command(ACK, NAK, RS, US..) or ...
            Select Case m_OFFSET
                Case 1
                    Select Case RB(0)
                        Case asciiACK
                            SCOMM_STATUS = ST_IDLE
                            RCOMM_STATUS = ST_IDLE
                            m_OFFSET = 0
                            RETRY_COUNT = 0
                            ClearRB
                            ANS_FLAG = asciiACK
                            AddCommLog2 "Receive [ACK]", RB(0)
                        Case asciiNAK
                            m_OFFSET = 0
                            RETRY_COUNT = RETRY_COUNT + 1
                            If RETRY_COUNT > 3 Then
                                TP(0) = asciiNAK
                                commCSDJ.Output = TP
                                SCOMM_STATUS = ST_IDLE
                                RCOMM_STATUS = ST_IDLE
                                m_OFFSET = 0
                                RETRY_COUNT = 0
                                ClearRB
                            Else
                                commCSDJ.Output = SBB
                            End If
                            AddCommLog2 "Receive [NAK]", RB(0)
                        Case asciiBEL
                            ANS_FLAG = FLAG_BEL
                            AddCommLog2 "Receive [BEL]: Alarm", RB(0)
                        Case asciiETB
                            ANS_FLAG = FLAG_ETB
                            AddCommLog2 "Receive [ETB]: Multi-Frame", RB(0)
                        Case asciiRS
                            ANS_FLAG = FLAG_RS
                            AddCommLog2 "Receive [RS]: Range Over", RB(0)
                        
                        Case asciiUS
                            ANS_FLAG = FLAG_US
                            SCOMM_STATUS = ST_IDLE
                            RCOMM_STATUS = ST_IDLE
                            m_OFFSET = 0
                            RETRY_COUNT = 0
                            ClearRB
                            AddCommLog2 "Receive [US]: Un-Defined", RB(0)
                     End Select
                Case Is > 1
                    If RB(m_OFFSET - 1) = asciiETX Then
                        If RB(0) = asciiACK Then
                            ReDim AB(0 To m_OFFSET - 2)
                            For i = 0 To m_OFFSET - 2
                                AB(i) = RB(i + 1)
                                RB(i) = 0
                            Next i
                        Else
                            ReDim AB(0 To m_OFFSET - 1)
                            For i = 0 To m_OFFSET - 1
                                AB(i) = RB(i)
                                RB(i) = 0
                            Next i
                        End If
                        RCOMM_STATUS = AnalyzeCommMode(AB)
    
                        If (AB(0) = asciiSTX) And (AB(UBound(AB, 1)) = asciiETX) Then
                            If CheckBCC(AB, UBound(AB, 1) - 2) = False Then
                                ClearFlag
                                TP(0) = asciiNAK
                                commCSDJ.Output = TP
                                AddCommLog1 "Send [NAK]", TP
                            Else
                                Select Case RCOMM_STATUS
                                    Case ST_SET     '= 11
                                        For i = 0 To UBound(AB, 1)
                                            ANS_BUFFER(i) = AB(i)
                                        Next i
    
                                        TP(0) = asciiACK
                                        commCSDJ.Output = TP
                                        AddCommLog1 "Send [ACK]", TP
                                        SCOMM_STATUS = ST_IDLE
                                        RCOMM_STATUS = ST_IDLE
    
                                        ANS_FLAG = FLAG_COMMAND
    
                                    Case ST_STR     '= 13
                                    
                                    Case ST_MDM     '= 21
                                        For i = 0 To UBound(AB, 1)
                                            ANS_BUFFER(i) = AB(i)
                                        Next i
                                        
                                        S = ""
                                        j = 0
                                        For i = 6 To UBound(ANS_BUFFER, 1) - 2
                                            Select Case ANS_BUFFER(i)
                                                Case 38
                                                    txtMDMValue(j).Text = S
                                                    S = ""
                                                    j = j + 1
                                                Case 3
                                                    Exit For
                                                    
                                                Case Else
                                                    S = S + Chr(ANS_BUFFER(i))
                                            End Select
                                        Next i
                                        AddCommLog1 "[STX]0[$][MDM]DATA[BSS][ETX]", ANS_BUFFER
                                        TP(0) = asciiACK
                                        commCSDJ.Output = TP
                                        AddCommLog1 "Send [ACK]", TP
                                        SCOMM_STATUS = ST_IDLE
                                        RCOMM_STATUS = ST_IDLE
    
                                        ANS_FLAG = FLAG_COMMAND
                                        
                                    Case ST_MOR     '= 23
                                        For i = 0 To UBound(AB, 1)
                                            ANS_BUFFER(i) = AB(i)
                                        Next i
                                        
                                        S = ""
                                        j = 0
                                        For i = 6 To UBound(ANS_BUFFER, 1) - 2
                                            Select Case ANS_BUFFER(i)
                                                Case 38
                                                    txtMORValue(j).Text = S
                                                    S = ""
                                                    j = j + 1
                                                Case 3
                                                    Exit For
                                                    
                                                Case Else
                                                    S = S + Chr(ANS_BUFFER(i))
                                            End Select
                                        Next i
                                        AddCommLog1 "[STX]0[$][MOR]DATA[BSS][ETX]", ANS_BUFFER
                                        TP(0) = asciiACK
                                        commCSDJ.Output = TP
                                        AddCommLog1 "Send [ACK]", TP
                                        SCOMM_STATUS = ST_IDLE
                                        RCOMM_STATUS = ST_IDLE
    
                                        ANS_FLAG = FLAG_COMMAND
                                    
                                    
                                    Case ST_MOT     '= 25
                                    Case ST_BSY1, ST_BSY2    '= 27, 161
                                        AddCommLog1 "Received [STX]0#BSY2[ETX]", AB
                                        TP(0) = asciiACK
                                        commCSDJ.Output = TP
                                        AddCommLog1 "Send [ACK]", TP
                                    Case ST_TGA     '= 28
                                    Case ST_JOG     '= 31
                                    Case ST_SVR1    '= 32
    
                                    Case ST_TAT     '= 41
                                        Dim TAT() As Byte
                                        Select Case m_OFFSET
                                            Case 9
                                                ReDim TAT(m_OFFSET - 2)
                                                If (AB(0) = asciiACK) And (AB(1) = asciiSTX) Then
                                                    For i = 0 To 7
                                                        TAT(i) = AB(i + 1)
                                                    Next i
                                                    
                                                    Select Case AnalyzeCommMode(TAT)
                                                        Case ST_BSY2
                                                            AddCommLog1 "Received [ACK][STX]0$BSY2[ETX]", TAT
                                                            TP(0) = asciiACK
                                                            commCSDJ.Output = TP
                                                            AddCommLog1 "Send [ACK]", TP
                                                        Case ST_TOK
                                                            AddCommLog1 "Received [ACK][STX]0$TOK2[ETX]", TAT
                                                            TP(0) = asciiACK
                                                            commCSDJ.Output = TP
                                                            AddCommLog1 "Send [ACK]", TP
                                                        Case Else
                                                    
                                                    End Select
                                                End If
    
                                            Case 8
                                                ReDim TAT(m_OFFSET - 1)
    
                                                If (AB(0) = asciiSTX) Then
                                                    For i = 0 To 7
                                                        TAT(i) = AB(i)
                                                    Next i
                                                    
                                                    TP(0) = asciiACK
                                                    Select Case AnalyzeCommMode(TAT)
                                                        Case ST_BSY2
                                                            AddCommLog1 "Received [ACK][STX]0$BSY2[ETX]", TAT
                                                            TP(0) = asciiACK
                                                            commCSDJ.Output = TP
                                                            AddCommLog1 "Send [ACK]", TP
                                                        Case ST_TOK
                                                            AddCommLog1 "Received [ACK][STX]0$TOK2[ETX]", TAT
                                                            TP(0) = asciiACK
                                                            commCSDJ.Output = TP
                                                            AddCommLog1 "Send [ACK]", TP
                                                        Case Else
                                                    
                                                    End Select
                                                End If
    
                                            Case Else
                                                'Debug.Print("m_OFFSET=????")
                                        End Select
                                        SCOMM_STATUS = ST_IDLE
                                        RCOMM_STATUS = ST_IDLE
    
                                    Case ST_TOK     '= 42
                                        Select Case AB(0)
                                            Case asciiSTX
                                                Select Case AnalyzeCommMode(AB)
                                                    Case ST_TOK
                                                        AddCommLog1 "Received [STX]0$TOK2[ETX]", AB
                                                        TP(0) = asciiACK
                                                        commCSDJ.Output = TP
                                                        AddCommLog1 "Send [ACK]", TP
                                                    Case Else
                                                
                                                End Select
                                        End Select
                                        SCOMM_STATUS = ST_IDLE
                                        RCOMM_STATUS = ST_IDLE
    
                                    Case ST_TMN     '= 43
                                    Case ST_SVR2    '= 51
                                    Case ST_STP     '= 61
                                    Case ST_MOV     '= 71
                                    Case ST_MOP     '= 72
                                    Case ST_ORG     '= 81
                                    Case ST_STS     '= 91
                                    Case ST_RST     '= 101
                                    Case ST_POS     '= 111
                                    Case ST_VER     '= 121
                                    Case ST_TST     '= 131
                                    Case ST_DAO     '= 141
                                    Case ST_EHY     '= 151
                                    Case ST_ETC     '= 171
                                    Case ST_ESC     '= 181
                                    Case ST_TYP     '= 191
    
                                End Select
                                m_OFFSET = 0
                                ClearGlobalBuffer
                            End If
                        End If
                    End If
            End Select
    End Select
    ReceivedFlag = False
End Sub

'-------------------------------------
'Clear Buffer to 0
'-------------------------------------
Private Sub ClearGlobalBuffer()
    Dim i As Integer
    For i = 0 To UBound(RB, 1)
        RB(i) = 0
    Next i
    End Sub

'-------------------------------------
'Cleat Flag
'-------------------------------------
Private Sub ClearFlag()
    ANS_FLAG = FLAG_NULL
End Sub

'-------------------------------------
'Anal Command from Servo
'-------------------------------------
Private Function AnalyzeCommMode(ByRef AB() As Byte) As Integer
    Dim WB() As Byte
    Dim i As Integer
    
    ReDim WB(0 To UBound(AB, 1))
    
    If AB(0) = asciiACK Then
        For i = 0 To UBound(AB, 1)
            WB(i) = AB(i + 1)
        Next i
    ElseIf AB(0) = asciiSTX Then
        For i = 0 To UBound(AB, 1)
            WB(i) = AB(i)
        Next i
    End If

    Select Case Chr(WB(3))
        Case "B"
            AnalyzeCommMode = ST_BSY2
            Exit Function
        Case "D"
            AnalyzeCommMode = ST_DAO
            Exit Function
        Case "E"
            Select Case Chr(WB(4))
                Case "H"
                    AnalyzeCommMode = ST_EHY
                Case "T"
                    AnalyzeCommMode = ST_ETC
                Case "S"
                    AnalyzeCommMode = ST_ESC
            End Select
            Exit Function
        Case "J"
            AnalyzeCommMode = ST_JOG
            Exit Function
        Case "M"
            Select Case Chr(WB(4))
                Case "D"
                    AnalyzeCommMode = ST_MDM
                Case "O"
                    If Chr(WB(5)) = "R" Then
                        AnalyzeCommMode = ST_MOR
                    ElseIf Chr(WB(5)) = "T" Then
                        AnalyzeCommMode = ST_MOT
                    ElseIf Chr(WB(5)) = "V" Then
                        AnalyzeCommMode = ST_MOV
                    ElseIf Chr(WB(5)) = "P" Then
                        AnalyzeCommMode = ST_MOP
                    Else
                        AnalyzeCommMode = ST_ETC
                    End If
            End Select
            Exit Function
        Case "O"
            AnalyzeCommMode = ST_ORG
            Exit Function
        Case "P"
            AnalyzeCommMode = ST_POS
            Exit Function
        Case "R"
            AnalyzeCommMode = ST_RST
            Exit Function

        Case "S"
            Select Case Chr(WB(4))
                Case "E"
                    AnalyzeCommMode = ST_SET
                Case "V"
                    AnalyzeCommMode = ST_SVR1
            Exit Function
                Case "T"
                    If Chr(WB(5)) = "R" Then
                        AnalyzeCommMode = ST_STR
                    ElseIf Chr(WB(5)) = "S" Then
                        AnalyzeCommMode = ST_STS
                    ElseIf Chr(WB(5)) = "P" Then
                        AnalyzeCommMode = ST_STP
                    End If
            End Select
            Exit Function

        Case "T"
            Select Case Chr(WB(4))
                Case "G"
                    AnalyzeCommMode = ST_TGA
                Case "A"
                    AnalyzeCommMode = ST_TAT
                Case "O"
                    AnalyzeCommMode = ST_TOK
                Case "M"
                    AnalyzeCommMode = ST_TMN
                Case "S"
                    AnalyzeCommMode = ST_TST
                Case "Y"
                    AnalyzeCommMode = ST_TYP
            End Select
            Exit Function
        Case "V"
            AnalyzeCommMode = ST_VER
            Exit Function
    End Select
End Function

'--------------------------------------------
'
'--------------------------------------------
'Private Sub cbVariableNumber_Change(Index As Integer)
'    cbVariableNumber_Click (Index)
'End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cbVariableNumber_Click(Index As Integer)
    Dim S As String
    
    'MDM = Array(&H2, &H30, &H23, &H4D, &H44, &H4D, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H3)      '[STX]0#01020304[CRC][ETX]
    
    If cbVariableNumber(Index).Text <> "" Then
        Select Case Index
            Case 0
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = False
                cbVariableNumber(2).Text = ""
                cbVariableNumber(3).Enabled = False
                cbVariableNumber(3).Text = ""
            Case 1
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = True
                cbVariableNumber(3).Enabled = False
                cbVariableNumber(3).Text = ""
            Case 2, 3
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = True
                cbVariableNumber(3).Enabled = True
    '       Case 3
    '            cbVariableNumber(1).Enabled = True
    '            cbVariableNumber(2).Enabled = False
    '            cbVariableNumber(3).Enabled = False
        End Select
        
'        S = cbVariableNumber(Index).Text
'        MDMASC(6 + (Index * 2)) = Asc(Mid(S, 1, 1))
'        MDMASC(6 + (Index * 2) + 1) = Asc(Mid(S, 2, 1))
    Else
        Select Case Index
            Case 0
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = False
                cbVariableNumber(1).Text = ""
                cbVariableNumber(2).Enabled = False
                cbVariableNumber(2).Text = ""
                cbVariableNumber(3).Enabled = False
                cbVariableNumber(3).Text = ""
            Case 1
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = False
                cbVariableNumber(2).Text = ""
                cbVariableNumber(3).Enabled = False
                cbVariableNumber(3).Text = ""
            Case 2
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = True
                cbVariableNumber(3).Enabled = False
                cbVariableNumber(3).Text = ""
           Case 3
                cbVariableNumber(0).Enabled = True
                cbVariableNumber(1).Enabled = True
                cbVariableNumber(2).Enabled = True
                cbVariableNumber(3).Enabled = True
        End Select
    End If
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub SendMDM_Click()
    Dim MDM
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If

    Dim i As Integer
    Dim j As Integer
    Dim N As Integer
    Dim S As String
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    MDM = Array(&H2, &H30, &H23, &H4D, &H44, &H4D, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H3)      '[STX]0#01020304[CRC][ETX]
    N = 0
    For i = 0 To 3
        If cbVariableNumber(i).Text <> "" Then
            N = N + 1
        End If
        txtMDMValue(i).Text = ""
    Next i
    ReDim MDMASC(0 To (N * 2) + 8 - 1)
    For i = 0 To 5
        MDMASC(i) = MDM(i)
    Next i
    
    For i = 0 To N - 1
        If cbVariableNumber(i).Enabled = True Then
            If cbVariableNumber(i).Text <> "" Then
                S = cbVariableNumber(i).Text
                MDMASC(6 + (i * 2)) = Asc(Mid(S, 1, 1))
                MDMASC(6 + (i * 2) + 1) = Asc(Mid(S, 2, 1))
            End If
        Else
            Exit For
        End If
    Next i
    
    MDMASC(UBound(MDMASC, 1) - 1) = CalcBCC(MDMASC, UBound(MDMASC, 1))
    MDMASC(UBound(MDMASC, 1)) = &H3
    
    SCOMM_STATUS = ST_MDM
    ReDim SB(0 To UBound(MDMASC, 1))
    For i = 0 To UBound(MDMASC, 1)
        SB(i) = MDMASC(i)
    Next i
    SB_Backup SB
    commCSDJ.Output = SB
    
    AddCommLog "Send [STX]0#MDM[BSS][ETX]"
End Sub

'--------------------------------------------
'Timer Routine when send BSY1 Command to Servo
'--------------------------------------------
Private Sub tmrCSDJ_Timer()
    If (commCSDJ.OutBufferCount <= 0) And (SCOMM_STATUS = ST_IDLE) Then
        Dim BSY
        Dim i As Integer
        
        BSY = Array(&H2, &H30, &H23, &H42, &H53, &H59, &H31, &H3) '[STX]0#BSY1[ETX]
        SCOMM_STATUS = ST_BSY1
        ReDim SB(0 To UBound(BSY, 1))
        For i = 0 To UBound(BSY, 1)
            SB(i) = BSY(i)
        Next i
        SB_Backup SB
        commCSDJ.Output = SB
        RCOMM_STATUS = ST_WAIT
        AddCommLog "Send [STX]0#BSY1[ETX]"
    End If
End Sub

'-------------------------------------
'Calc BCC
'After Taking All data included STX ~ ETX,
'Calculate the BCC and return
'-------------------------------------
Private Function CheckBCC(ByRef RBB() As Byte, ByVal DataLength As Integer) As Boolean
    Dim i As Integer
    Dim BCC As Integer
    Dim S As String
    Dim A As Byte
    For i = 1 To DataLength
        BCC = BCC + RBB(i)
    Next
    S = Right("0000" + CStr(Hex(BCC)), 4)
    A = CByte(Asc(Mid(S, 4, 1)))
    If A = RBB(DataLength + 1) Then
        CheckBCC = True
    Else
        CheckBCC = False
    End If
End Function

'-------------------------------------
'
'-------------------------------------
Private Sub ClearRB()


End Sub

'-------------------------------------
'Back Up Send Data for preparing Re-Send
'-------------------------------------
Private Sub SB_Backup(ByRef Buf() As Byte)
Dim i As Integer
    ReDim SBB(0 To UBound(Buf, 1))
    For i = 0 To UBound(Buf, 1)
        SBB(i) = Buf(i)
    Next i
    'Buf.CopyTo(SBB, Buf.Length)
End Sub

'--------------------------------------------
'Request Parameter Command
'--------------------------------------------
Private Sub cmdRequestParameter_Click()
    Dim SET_CMD
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim S As String
    Dim R As Integer
    Dim T As String
        
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
        
    SET_CMD = Array(&H2, &H30, &H23, &H53, &H45, &H54, &H30, &H30, &H30, &H0, &H3)  '[STX]0#SET000[BCC][ETX]"
    R = 1
    
    With gridParameter
        .Rows = 1
        .Cols = 2
'        .ColWidth(1) = .ColWidth(1) * 10
        ReDim SB(0 To UBound(SET_CMD, 1))
        
        cmdRequestParameter.Enabled = False
        cmdChangeParameter.Enabled = False
        cbGridNumber.Enabled = False

        For i = 1 To 99
            For j = 0 To 1500
                DoEvents
            Next
            For k = 0 To UBound(SET_CMD, 1)
                SB(k) = SET_CMD(k)
            Next k
            
            S = Right("00" + CStr(i), 2)
            SB(7) = CByte(Asc(Mid(S, 1, 1)))
            SB(8) = CByte(Asc(Mid(S, 2, 1)))
            SB(9) = CalcBCC(SB, UBound(SET_CMD, 1))

            SCOMM_STATUS = ST_SET
            RCOMM_STATUS = ST_IDLE
            
            SB_Backup SB

            commCSDJ.Output = SB
            
            'For Displaying Sending Packet
            T = "Send [STX]0#SET" + Right("000" + CStr(i), 3) + CStr(Chr(SB(9))) + "[ETX]"
            AddCommLog T
            
            ANS_FLAG = 0
            Do
                DoEvents
            Loop While (ANS_FLAG = FLAG_NULL)

            .Rows = .Rows + 1
            .Row = R
            .Col = 0
            .Text = Right("00" + CStr(i), 2)
            .Col = 1
            Select Case ANS_FLAG
                Case FLAG_COMMAND
                    .Text = AnalyzeAnswer()
                    AddCommLog "Received [STX]0$SET" + Right("000" + CStr(i), 3) + .Text + "&" + Chr(ANS_BUFFER(12)) + "[ETX]"
                Case FLAG_US
                    .Text = "NO FUNC"
                Case FLAG_RS
                    .Text = "OVER"
                Case FLAG_BEL
                    .Text = "ALARM"
                Case FLAG_ETB
                    .Text = "MULI BLOCK"
                Case Else
            End Select
            
            
            R = R + 1
            ClearFlag
            For k = 0 To UBound(ANS_BUFFER, 1)
                ANS_BUFFER(k) = 0
            Next k
            
            
        Next i
        cmdRequestParameter.Enabled = True
        cmdChangeParameter.Enabled = True
        cbGridNumber.Enabled = True
    End With
End Sub

'--------------------------------------------
'Change  Parameter Command (STR)
'--------------------------------------------
Private Sub cmdChangeParameter_Click()
    Dim i As Integer
    Dim j As Integer
    Dim S As String
    Dim T As String
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    If gridParameter.Rows <= 2 Then
        MsgBox "First, You must Data from Servo.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    Dim STR_COMMAND
    STR_COMMAND = Array(&H2, &H30, &H23, &H53, &H54, &H52, &H30, &H30, &H30, &H30, &H30, &H30, &H30, &H30, &H26, &H0, &H3)  '[STX}0#STR[Num(3Digit)][Data(5Dight)]&[BCC]ETX

    If cbGridNumber.Text = "" Or cbGridNumber.Text = "NO FUNC" Or cbGridNumber.Text = "OVER" Or _
        cbGridNumber.Text = "ALARM" Or cbGridNumber.Text = "MULTI BLOCK" Then
        Exit Sub
    End If
    
    ReDim SB(0 To UBound(STR_COMMAND))
    Select Case cbGridNumber.Text
        Case "All"
            If MsgBox("Do you want to send all data to CSDJ Servo Drive ?", vbYesNo, "Confirm") = vbYes Then
                For i = 1 To 99
                    gridParameter.Row = i
                    gridParameter.Col = 1
                    T = gridParameter.Text
                    
                    If T <> "NO FUNC" And T <> "OVER" And T <> "ALARM" And T <> "MULTI BLOCK" Then
                        For j = 0 To 16
                            SB(j) = STR_COMMAND(j)
                        Next j
                        
                        S = Right("000" + CStr(i), 3)
                        For j = 6 To 8
                            SB(j) = CByte(Asc(Mid(S, j - 5, 1)))
                        Next j
                        
                        S = Right("00000" + T, 5)
                        For j = 9 To 13
                            SB(j) = CByte(Asc(Mid(S, j - 8, 1)))
                        Next j
                        
                        SB(15) = CalcBCC(SB, UBound(STR_COMMAND, 1))
                   
                        SB_Backup SB
                        
                        AddCommLog "Send [STX]0#STR" + Right("000" + CStr(i), 3) + T + "&" + CStr(Chr(SB(15))) + "[ETX]"
                        commCSDJ.Output = SB
                        ANS_FLAG = 0
                        Do
                            DoEvents
                        Loop While (ANS_FLAG = FLAG_NULL)
                        ANS_FLAG = FLAG_NULL
                   End If
                Next i
            Else
                Exit Sub
            End If
        Case Else
            T = "Do you want to send " + Right("000" + cbGridNumber.Text, 5) + " data to CSDJ Servo Drive ?"
            If MsgBox(T, vbYesNo, "Confirm") = vbYes Then
                ReDim SB(0 To UBound(STR_COMMAND))
                gridParameter.Row = CInt(cbGridNumber.Text)
                gridParameter.Col = 1
                T = gridParameter.Text
                
                If T <> "NO FUNC" And T <> "OVER" And T <> "ALARM" And T <> "MULTI BLOCK" Then
                    For j = 0 To 16
                        SB(j) = STR_COMMAND(j)
                    Next j
                    
                    S = Right("000" + cbGridNumber.Text, 3)
                    For j = 6 To 8
                        SB(j) = CByte(Asc(Mid(S, j - 5, 1)))
                    Next j
                    
                    S = Right("00000" + T, 5)
                    For j = 9 To 13
                        SB(j) = CByte(Asc(Mid(S, j - 8, 1)))
                    Next j
                    
                    SB(15) = CalcBCC(SB, UBound(STR_COMMAND, 1))
               
                    SB_Backup SB
        
                    AddCommLog "Send [STX]0#STR" + Right("000" + cbGridNumber.Text, 3) + Right("00000" + T, 5) + "&" + CStr(Chr(SB(15))) + "[ETX]"
                    commCSDJ.Output = SB
                    ANS_FLAG = 0
                    Do
                        DoEvents
                    Loop While (ANS_FLAG = FLAG_NULL)
                    ANS_FLAG = FLAG_NULL
               End If
            Else
                Exit Sub
            End If
    End Select
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub gridParameter_Click()
    Dim i As Integer
    Dim x As Integer
   
    Call GetCursorPos(MousePos)
    
    frmWriteWord.Top = MousePos.y * Screen.TwipsPerPixelY + 150
    frmWriteWord.Left = MousePos.x * Screen.TwipsPerPixelX
    
    frmWriteWord.Show
End Sub

'=============================================================
'Analyze Answer from CSDJ
'=============================================================
Private Function AnalyzeAnswer() As String
    Dim ANS As String
    Dim i As Integer
    For i = 6 To 10
        ANS = ANS + Chr(CStr(ANS_BUFFER(i)))
    Next
    AnalyzeAnswer = ANS
End Function

'-------------------------------------
'Calc BCC
'After Taking All data included STX ~ ETX,
'Calculate the BCC and return
'-------------------------------------
Private Function CalcBCC(ByRef RBB() As Byte, ByVal DataLength As Integer) As Byte
    Dim i As Integer
    Dim BCC As Integer
    Dim S As String

    For i = 1 To DataLength - 2
        BCC = BCC + RBB(i)
    Next
    S = Right("0000" + CStr(Hex(BCC)), 4)
    CalcBCC = CByte(Asc(Mid(S, 4, 1)))
End Function

'--------------------------------------------
'
'--------------------------------------------
Private Sub AddCommLog(ByVal S As String)
    Dim i As Integer
    Dim T As String
    
    lstCommLog.AddItem S
    For i = 0 To UBound(SB, 1)
        T = T + "[" + Right("00" + CStr(Hex(SB(i))), 2) + "] "
    Next i
    lstCommLogHex.AddItem T
End Sub
'--------------------------------------------
'
'--------------------------------------------
Private Sub AddCommLog1(ByVal S As String, ByRef A() As Byte)
    Dim i As Integer
    Dim T As String
    
    lstCommLog.AddItem S
    For i = 0 To UBound(A, 1)
        T = T + "[" + Right("00" + CStr(Hex(A(i))), 2) + "] "
    Next i
    lstCommLogHex.AddItem T
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub AddCommLog2(ByVal S As String, ByVal A As Byte)
    Dim i As Integer
    Dim T As String
    
    lstCommLog.AddItem S
    T = T + "[" + Right("00" + CStr(Hex(A)), 2) + "] "
    lstCommLogHex.AddItem T
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub lstCommLog_Click()
    With lstCommLog
        If .ListIndex = -1 Then Exit Sub
        If (.ListCount > 0) And (lstCommLogHex.ListCount > 0) Then
            lstCommLogHex.ListIndex = .ListIndex
        Else
        End If
    End With

End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub lstCommLogHex_Click()
    With lstCommLogHex
        If .ListIndex = -1 Then Exit Sub
        If (.ListCount > 0) And (lstCommLog.ListCount > 0) Then
            lstCommLog.ListIndex = .ListIndex
        Else
        End If
    End With
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub lstCommLogHex_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
    With lstCommLogHex
        If .ListIndex = -1 Then
            Exit Sub
        End If
        If (.Selected(.ListIndex) = True) And (.List(.ListIndex) <> "") Then
            Call GetCursorPos(MousePos)
            frmMonitoringData.Top = MousePos.y * Screen.TwipsPerPixelY + 150
            frmMonitoringData.Left = MousePos.x * Screen.TwipsPerPixelX
            frmMonitoringData.Show
            frmMonitoringData.txtMonitoringData.Text = (.List(.ListIndex))
        End If
    End With
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub lstCommLogHex_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
    frmMonitoringData.txtMonitoringData.Text = ""
    Unload frmMonitoringData
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cmdLoad_Click()
    On Error GoTo CLSP

    Dim FN As String
    Dim i As Integer
    Dim S As String
'    Dim T As String * 1024
    Dim T As String * 10
    Dim N As Integer
    Dim M
    Dim NN As String
    Dim R As Integer
    Dim ST As String
    
    cdLoad.DefaultExt = ".ini"
    cdLoad.Filter = "*.ini"
    cdLoad.InitDir = App.Path + "\Data"
    cdLoad.ShowOpen
    
    R = 1
    With gridParameter
        .Rows = 1
        .Cols = 2
'        .ColWidth(1) = .ColWidth(1) * 3
        For i = 1 To 99
            .Rows = .Rows + 1
            .Row = R
            .Col = 0
            .Text = Right("00" + CStr(i), 2)
            
            .Row = R
            .Col = 1
            NN = Right("00" + CStr(i), 2)
            M = GetPrivateProfileString("CSDJ", NN, "NO FUNC", T, Len(T), cdLoad.FileName)
            ST = Mid(T, 1, CInt(M)) + ""
            .Text = ST
            
            R = R + 1
        Next i
    End With
    Exit Sub
CLSP:
    Select Case Err.Number
        Case 13
            Exit Sub
    End Select
    
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cmdSave_Click()
    Dim FN As String
    Dim i As Integer
    Dim S As String
    Dim N As String
    
    cdSave.DefaultExt = ".ini"
    cdSave.Filter = "*.ini"
    cdSave.InitDir = App.Path + "\Data"
    cdSave.ShowSave
    FN = cdSave.FileName
    
    With gridParameter
        .Col = 1
        For i = 1 To 99
            N = Right("00" + CStr(i), 2)
            .Row = i
            WritePrivateProfileString "CSDJ", N, gridParameter.Text, cdSave.FileName
        Next i
    End With
    MsgBox "Save Completed !!", vbOKOnly, "Save Parameter"
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cmdViewParam_Click()
    cdLoad.DefaultExt = ".ini"
    cdLoad.Filter = "*.ini"
    cdLoad.InitDir = App.Path + "\Data"
    cdLoad.ShowOpen
    
    WinExec "NotePad " + cdLoad.FileName, 5
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cbVarMorNumber_Click(Index As Integer)
    Dim S As String
    
    'MOR = Array(&H2, &H30, &H23, &H4D, &H4F, &H52, &H0, &H0, &H0, &H0, &H0, &H3)      '[STX]0#MOR0102[CRC][ETX]
    
    If cbVarMORNumber(Index).Text <> "" Then
        Select Case Index
            Case 0
                txtMORValue(0).Text = ""
                cbVarMORNumber(1).Enabled = True
                cbVarMORNumber(1).Text = ""
                txtMORValue(1).Text = ""
            Case 1
                txtMORValue(1).Text = ""
        End Select
    Else
        Select Case Index
            Case 0
                cbVarMORNumber(0).Enabled = True
                cbVarMORNumber(1).Enabled = False
                cbVarMORNumber(1).Text = ""
            Case 1
                cbVarMORNumber(0).Enabled = True
                cbVarMORNumber(1).Enabled = True
        End Select
    End If
End Sub

'--------------------------------------------
'
'--------------------------------------------
Private Sub cmdSendMOR_Click()
    Dim MOR
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If

    Dim i As Integer
    Dim j As Integer
    Dim N As Integer
    Dim S As String
    
    If commCSDJ.PortOpen = False Then
        MsgBox "Please Open the communication Port.", vbOKOnly, "Warning"
        Exit Sub
    End If
    
    MOR = Array(&H2, &H30, &H23, &H4D, &H4F, &H52, &H0, &H0, &H0, &H0, &H0, &H3)      '[STX]0#MOR0102[CRC][ETX]
    N = 0
    For i = 0 To 1
        If cbVarMORNumber(i).Text <> "" Then
            N = N + 1
        End If
        txtMORValue(i).Text = ""
    Next i
    txtMORValue(2).Text = ""
    
    ReDim MORASC(0 To (N * 2) + 8 - 1)
    For i = 0 To 5
        MORASC(i) = MOR(i)
    Next i
    
    For i = 0 To N - 1
        If cbVarMORNumber(i).Enabled = True Then
            If cbVarMORNumber(i).Text <> "" Then
                S = cbVarMORNumber(i).Text
                MORASC(6 + (i * 2)) = Asc(Mid(S, 1, 1))
                MORASC(6 + (i * 2) + 1) = Asc(Mid(S, 2, 1))
            End If
        Else
            Exit For
        End If
    Next i
    
    MORASC(UBound(MORASC, 1) - 1) = CalcBCC(MORASC, UBound(MORASC, 1))
    MORASC(UBound(MORASC, 1)) = &H3
    
    SCOMM_STATUS = ST_MOR
    ReDim SB(0 To UBound(MORASC, 1))
    For i = 0 To UBound(MORASC, 1)
        SB(i) = MORASC(i)
    Next i
    SB_Backup SB
    commCSDJ.Output = SB
    
    AddCommLog "Send [STX]0#MOR[BSS][ETX]"
End Sub


