Attribute VB_Name = "System"
Option Explicit

' Global variable to keep track of application tick counts
' Could have used GetTickCount but like this solution better
Public AppTickCount As Long
' AppTickPeriod in milliseconds
Public Const AppTickPeriod As Integer = 100

' Globs for various tests
Public CycleTestRunning As Boolean
Public PowerCutTestRunning As Boolean

'Delay variables
Private SampleTimePeriod As Long
Private PowerOffPeriod As Long

Dim StatusTextBox As TextBox

' Declarations of Windows API functions
Declare Function GetPrivateProfileInt Lib "kernel32" Alias _
"GetPrivateProfileIntA" (ByVal lpApplicationName As String, _
                         ByVal lpKeyName As String, _
                         ByVal nDefault As Long, _
                         ByVal lpFileName As String) As Long

Declare Function GetPrivateProfileString Lib "kernel32" Alias _
"GetPrivateProfileStringA" (ByVal lpApplicationName As String, _
                            ByVal lpKeyName As String, _
                            ByVal lpDefault As String, _
                            ByVal lpReturnedString As String, _
                            ByVal nSize As Long, _
                            ByVal lpFileName As String) As Long

Declare Function WritePrivateProfileString Lib "kernel32" Alias _
"WritePrivateProfileStringA" (ByVal lpApplicationName As String, _
                              ByVal lpKeyName As String, _
                              ByVal lpString As String, _
                              ByVal lpFileName As String) As Long

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Public Sub SetStatusText(Status As TextBox)
    Set StatusTextBox = Status
End Sub

Public Function ConfigureSystem(ErrStr As String)
    Dim Port As Integer
    
    ' clear test running flags
    CycleTestRunning = False
    PowerCutTestRunning = False
    
    'Get delay variables
    SampleTimePeriod = GetPrivateProfileInt("TestPeriods", _
                                            "SampleTimePeriod", _
                                            2, ".\\shuttertest.ini")
    
    
    'convert SampleTimePeriod to AppTicks
    SampleTimePeriod = SampleTimePeriod * (1000 / AppTickPeriod)
    
    PowerOffPeriod = GetPrivateProfileInt("TestPeriods", _
                                          "PowerOffPeriod", _
                                          2, ".\\shuttertest.ini")
    
    'convert PowerOffPeriod to AppTicks
    PowerOffPeriod = PowerOffPeriod * (1000 / AppTickPeriod)
    
    
    
    'Setup PowerSupply
    Port = GetPrivateProfileInt("Communications", _
                                "PowerSupplyPort", _
                                -1, _
                                ".\\shuttertest.ini")
    
    If Not ConfigurePowerSupply(Port, ErrStr) Then
        ConfigureSystem = False
        Exit Function
    End If
     
    'Setup Shutter
    Port = GetPrivateProfileInt("Communications", _
                                "ShutterPort", _
                                -1, _
                                ".\\shuttertest.ini")
    
    If Not ConfigureShutter(Port, ErrStr) Then
        ConfigureSystem = False
        Exit Function
    End If
    
    ErrStr = ""
    ConfigureSystem = True

End Function

Public Function CycleTest()
    'file vars
    Dim LogFile As String
    Dim FileNumber As Integer
    Dim MaxFileNumber As Integer
    'test vars
    Dim Count As Integer
    Dim ErrorString As String
        
    'initialize the counter var
    Count = 1
    
    'look for the next available logfile number
    LogFile = Dir(".\\cycle_log*.txt")

    While Len(LogFile) > 1
        FileNumber = Val(Mid(LogFile, 10))
        If FileNumber > MaxFileNumber Then
            MaxFileNumber = FileNumber
        End If
        LogFile = Dir
    Wend

    'create the log file name with the next available number
    LogFile = ".\\cycle_log" + Trim(Str(MaxFileNumber + 1)) + ".txt"

    'create new log file that is MaxFileNumber + 1
    Open LogFile For Output As #1
    
    'write the file header
    Print #1, "Shutter Cycle Test"
    Print #1, "Started on " & Date & " at " & Time
    Print #1, ""
    Print #1, "Count" & vbTab & "Status" & vbTab & "Time" & vbTab & "Error"
    
    ' make sure the shutter is homed for the test
    If Not PowerOn(ErrorString) Then
        ErrorString = "PowerOn Error: " & ErrorString
        StatusTextBox.Text = ErrorString
        GoTo ErrorExit
    End If
    
    ' make sure power supply is stable
    TickDelay 5
        
    If Not CloseShutter(ErrorString) Then
        ErrorString = "CloseShutter Error: " & ErrorString
        StatusTextBox.Text = ErrorString
        GoTo ErrorExit
    End If
       
    If Not PowerOff(ErrorString) Then
        ErrorString = "PowerOff Error: " & ErrorString
        StatusTextBox.Text = ErrorString
        GoTo ErrorExit
    End If
    
    'start the test
    Do While CycleTestRunning
        
        'power off delay
        If Not TickDelayTest(PowerOffPeriod, CycleTestRunning) Then
            StatusTextBox.Text = "Test stopped by user"
            GoTo StopExit
        End If
        
        'power on the shutter
        If Not PowerOn(ErrorString) Then
            ErrorString = "PowerOn Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        ' make sure power supply is stable
        TickDelay 5
        
        'open the shutter
        If Not OpenShutter(ErrorString) Then
            ErrorString = "OpenShutter Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        'wait for sample time while the shutter is open
        If Not TickDelayTest(SampleTimePeriod, CycleTestRunning) Then
            StatusTextBox.Text = "Test stopped by user"
            GoTo StopExit
        End If
        
        'close the shutter
        If Not CloseShutter(ErrorString) Then
            ErrorString = "CloseShutter Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        'power of the shutter
        If Not PowerOff(ErrorString) Then
            ErrorString = "PowerOff Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        'log results of test
        Print #1, Count & vbTab & "SUCCESS" & vbTab & Time & vbTab & "NONE"
        StatusTextBox.Text = "Cycle Test: " & Str(Count)
        'increment the counter
        Count = Count + 1
    Loop
    
    StatusTextBox.Text = "Test stopped by user"
    
StopExit:
    'close the file and return
    Close #1
    Exit Function
    
ErrorExit:
    'log the error
    Print #1, Count & vbTab & "FAILURE" & vbTab & Time & vbTab & ErrorString
    
    'close the file and return
    Close #1
End Function

Public Function PowerCutTest()
    'file vars
    Dim LogFile As String
    Dim FileNumber As Integer
    Dim MaxFileNumber As Integer
    'test vars
    Dim Count As Integer
    Dim ErrorString As String
        
    'initialize the counter var
    Count = 1
    
    'look for the next available logfile number
    LogFile = Dir(".\\powercut_log*.txt")

    While Len(LogFile) > 1
        FileNumber = Val(Mid(LogFile, 13))
        If FileNumber > MaxFileNumber Then
            MaxFileNumber = FileNumber
        End If
        LogFile = Dir
    Wend

    'create the log file name with the next available number
    LogFile = ".\\powercut_log" + Trim(Str(MaxFileNumber + 1)) + ".txt"

    'create new log file that is MaxFileNumber + 1
    Open LogFile For Output As #2
    
    'write the file header
    Print #2, "Shutter Power Cut Test"
    Print #2, "Started on " & Date & " at " & Time
    Print #2, ""
    Print #2, "Count" & vbTab & "Status" & vbTab & "Time" & vbTab & "Error"
    
    ' power on the shutter to start the test
    If Not PowerOn(ErrorString) Then
        ErrorString = "PowerOn Error: " & ErrorString
        StatusTextBox.Text = ErrorString
        GoTo ErrorExit
    End If
    
    ' make sure power supply is stable
    TickDelay 10
        
    'start the test
    Do While PowerCutTestRunning
        'close the shutter
        If Not CloseShutter(ErrorString) Then
            ErrorString = "CloseShutter Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        'power off the shutter
        If Not PowerOff(ErrorString) Then
            ErrorString = "PowerOff Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
    
        'power off delay
        If Not TickDelayTest(PowerOffPeriod, PowerCutTestRunning) Then
            StatusTextBox.Text = "Test stopped by user"
            GoTo StopExit
        End If
        
        'power on the shutter
        If Not PowerOn(ErrorString) Then
            ErrorString = "PowerOn Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        ' make sure power supply is stable
        TickDelay 5
        
        ' write the open command to the shutter
        WriteShutter "OPEN"
        
        ' wait a second and cut power
        If Not TickDelayTest(10, PowerCutTestRunning) Then
            StatusTextBox.Text = "Test stopped by user"
            GoTo StopExit
        End If
        
        'power off the shutter
        If Not PowerOff(ErrorString) Then
            ErrorString = "PowerSupply Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        ' leave the power off for a couple of seconds
        If Not TickDelayTest(20, PowerCutTestRunning) Then
            StatusTextBox.Text = "Test stopped by user"
            GoTo StopExit
        End If
        
        'power on the shutter
        If Not PowerOn(ErrorString) Then
            ErrorString = "PowerOn Error: " & ErrorString
            StatusTextBox.Text = ErrorString
            GoTo ErrorExit
        End If
        
        ' make sure power supply is stable
        TickDelay 5
        
        'try to open the shutter
        If Not OpenShutter(ErrorString) Then
            ErrorString = "OpenShutter Error: " & ErrorString
            StatusTextBox.Text = ErrorString
        End If
        
        'log results of test
        Print #2, Count & vbTab & "SUCCESS" & vbTab & Time & vbTab & ErrorString
        StatusTextBox.Text = "Power Cut Test: " & Str(Count)
        'increment the counter
        Count = Count + 1
Loop
    
    StatusTextBox.Text = "Test stopped by user"
    
StopExit:
    'close the file and return
    Close #2
    Exit Function
    
ErrorExit:
    'log the error
    Print #2, Count & vbTab & "FAILURE" & vbTab & Time & vbTab & ErrorString
    'close the file and return
    Close #2
End Function

Public Sub TickDelay(Ticks As Long)
    Dim TimeOut As Long
    TimeOut = AppTickCount + Ticks
    
    Do While TimeOut > AppTickCount
        DoEvents
    Loop
End Sub
 
Public Function TickDelayTest(Ticks As Long, TestFlag As Boolean)
    Dim TimeOut As Long
    TimeOut = AppTickCount + Ticks
    
    Do While ((TimeOut > AppTickCount) And (TestFlag = True))
        DoEvents
    Loop
    
    TickDelayTest = TestFlag
End Function
 



