/Library/PRIMITIVES/TspInstrument.vb
Visual Basic | 5519 lines | 3131 code | 886 blank | 1502 comment | 22 complexity | 2818617540a2164c5a6c36c94204e5ea MD5 | raw file
- Imports isr.Core.StringExtensions
- ''' <summary>
- ''' Defines the I/O driver for accessing the master node of a TSP Linked system.
- ''' </summary>
- ''' <remarks>
- ''' </remarks>
- ''' <license>
- ''' (c) 2010 Integrated Scientific Resources, Inc.
- ''' Licensed under the Apache License Version 2.0.
- ''' Unless required by applicable law or agreed to in writing, this software is provided
- ''' "AS IS", WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ''' </license>
- ''' <history date="02/21/2009" by="David Hary" revision="3.0.3339.x">
- ''' Created
- ''' </history>
- Public Class TspInstrument
- Inherits isr.Visa.Ieee4882.Instrument
- Implements ITspInstrument
- #Region " CONSTRUCTORS and DESTRUCTORS "
- ''' <summary>Constructs this class.</summary>
- ''' <param name="resourceTitle">Specifies the instrument name.</param>
- Public Sub New(ByVal resourceTitle As String)
- MyBase.New(resourceTitle)
- Me._statusLatency = 1
- Me._statusRepeatCount = 3
- ' Creating TSP status manager..."
- ' My.MyLibrary.TspStatus = New isr.Tsp.TspStatus(Me)
- ' default to 8 nodes at this point
- Me._maximumNodeCount = 8
- Me._usingTspLink = True
- Me._systemInitTimeout = 30000
- Me._nilifyTimeout = 10000
- Me._deleteTimeout = 10000
- Me._saveTimeout = 10000
- MyBase.ErrorAvailableBits = Visa.Ieee4882.ServiceRequests.ErrorAvailable
- MyBase.MessageAvailableBits = Visa.Ieee4882.ServiceRequests.MessageAvailable
- MyBase.IsCheckBufferOnReceive = True
- MyBase.IsCheckBufferOnSend = True
- MyBase.IsCheckOpcAfterSend = False
- MyBase.IsDelegateErrorHandling = False
- Me.NewLegacyScripts()
- Me.NewScripts()
- ' set default commands and query commands.
- MyBase.ErrorQueueQueryCommand = TspSyntax.ErrorQueueQueryCommand(TspSyntax.GlobalNode)
- MyBase.ErrorQueueCountQueryCommand = TspSyntax.ErrorQueueCountQueryCommand(TspSyntax.GlobalNode)
- MyBase.ClearErrorQueueCommand = TspSyntax.ClearErrorQueueCommand(TspSyntax.GlobalNode)
- ' include the error clear command for compatibility with 2400 instruments.
- MyBase.ClearExecutionStateCommand = TspSyntax.ClearExecutionStateCommand(TspSyntax.GlobalNode)
- ' *IDN? *WAI
- MyBase.IdentifyQueryCommand = isr.Visa.Ieee4882.Syntax.IdentifyQueryCommand & " " & isr.Visa.Ieee4882.Syntax.WaitCommand
- ' MyBase.IdentifyQueryCommand = TspSyntax.IdentifyQueryCommand(TspSyntax.LocalNode)
- 'MyBase.OperationCompletedCommand = isr.Visa.Ieee4882.Syntax.OperationCompletedCommand ' "*OPC"
- MyBase.OperationCompletedCommand = TspSyntax.OperationCompletedCommand ' "opc()"
- 'MyBase.OperationCompletedQueryCommand = isr.Visa.Ieee4882.Syntax.OperationCompletedQueryCommand ' "*OPC?"
- MyBase.OperationCompletedQueryCommand = TspSyntax.OperationCompletedQueryCommand ' "waitcomplete() print(1)"
- MyBase.OperationEventEnableCommand = TspSyntax.OperationEventEnableCommand(TspSyntax.GlobalNode)
- MyBase.OperationEventEnableQueryCommand = TspSyntax.OperationEventEnableQueryCommand(TspSyntax.GlobalNode)
- MyBase.OperationEventStatusQueryCommand = TspSyntax.OperationEventStatusQueryCommand(TspSyntax.GlobalNode)
- ' Use reset() to reset all devices on the TSP link.
- MyBase.ResetKnownStateCommand = TspSyntax.ResetKnownStateCommand(TspSyntax.GlobalNode)
- MyBase.ServiceRequestEnableCommand = TspSyntax.ServiceRequestEnableCommand(TspSyntax.GlobalNode)
- MyBase.ServiceRequestEnableQueryCommand = TspSyntax.ServiceRequestEnableQueryCommand(TspSyntax.LocalNode)
- MyBase.ServiceRequestStatusQueryCommand = TspSyntax.ServiceRequestStatusQueryCommand(TspSyntax.LocalNode)
- MyBase.StandardEventEnableCommand = TspSyntax.StandardEventEnableCommand(TspSyntax.GlobalNode)
- MyBase.StandardEventEnableQueryCommand = TspSyntax.StandardEventEnableQueryCommand(TspSyntax.GlobalNode)
- MyBase.StandardEventStatusQueryCommand = TspSyntax.StandardEventStatusQueryCommand(TspSyntax.GlobalNode)
- MyBase.WaitCommand = isr.Visa.Ieee4882.Syntax.WaitCommand ' "*WAI"
- ' TSP instrument Ready to Connect.
- End Sub
- ''' <summary>Cleans up unmanaged or managed and unmanaged resources.</summary>
- ''' <param name="disposing">True if this method releases both managed and unmanaged
- ''' resources; False if this method releases only unmanaged resources.</param>
- ''' <remarks>Executes in two distinct scenarios as determined by
- ''' its disposing parameter. If True, the method has been called directly or
- ''' indirectly by a user's code--managed and unmanaged resources can be disposed.
- ''' If disposing equals False, the method has been called by the
- ''' runtime from inside the finalizer and you should not reference
- ''' other objects--only unmanaged resources can be disposed.</remarks>
- <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2215:Dispose methods should call base class dispose")>
- Protected Overrides Sub Dispose(ByVal disposing As Boolean)
- Try
- If Not MyBase.IsDisposed Then
- If disposing Then
- ' Free managed resources when explicitly called
- Me._legacyScripts.Dispose()
- Me._scripts.Dispose()
- If MyBase.IsConnected Then
- MyBase.Disconnect()
- End If
- End If
- ' Free shared unmanaged resources
- End If
- Finally
- ' invoke the dispose method on the base class.
- MyBase.Dispose(disposing)
- End Try
- End Sub
- #End Region
- #Region " SINGLETON "
- ''' <summary>
- ''' The locking object to enforce thread safety when creating the singleton instance.
- ''' </summary>
- Private Shared ReadOnly syncLocker As New Object
- ''' <summary>
- ''' Disposes of the default instance.
- ''' </summary>
- Public Shared Sub DisposeDefault()
- If TspInstrument.Instantiated Then
- SyncLock TspInstrument.syncLocker
- TspInstrument.instance.Dispose()
- TspInstrument.instance = Nothing
- End SyncLock
- End If
- End Sub
- ''' <summary>
- ''' Creates a new default instance of this class.</summary>
- Public Shared Sub NewDefault(ByVal resourceTitle As String)
- SyncLock TspInstrument.syncLocker
- TspInstrument.instance = New TspInstrument(resourceTitle)
- End SyncLock
- End Sub
- ''' <summary>
- ''' The shared instance.
- ''' </summary>
- Private Shared instance As TspInstrument
- ''' <summary>
- ''' Instantiates the class.
- ''' </summary>
- ''' <returns>
- ''' A new or existing instance of the class.
- ''' </returns>
- ''' <remarks>
- ''' Use this property to instantiate a single instance of this class.
- ''' This class uses lazy instantiation, meaning the instance isn't
- ''' created until the first time it's retrieved.
- ''' </remarks>
- Public Shared Function [Get](ByVal resourceTitle As String) As TspInstrument
- If Not TspInstrument.Instantiated Then
- TspInstrument.NewDefault(resourceTitle)
- End If
- Return TspInstrument.instance
- End Function
- ''' <summary>
- ''' Gets True if the singleton instance was instantiated.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Shared ReadOnly Property Instantiated() As Boolean
- Get
- SyncLock TspInstrument.syncLocker
- Return TspInstrument.instance IsNot Nothing AndAlso Not TspInstrument.instance.IsDisposed
- End SyncLock
- End Get
- End Property
- #End Region
- #Region " ICONNECTABLE "
- ''' <summary>Raises the connecting event.</summary>
- ''' <param name="e">Passes reference to the
- ''' <see cref="System.ComponentModel.CancelEventArgs">cancel event arguments</see>.</param>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Protected Overrides Sub OnConnecting(ByVal e As System.ComponentModel.CancelEventArgs)
- Dim synopsis As String = "On Connecting"
- ' MUST TURN OFF PROMPTS because THE TSB SYSTEM LEAVES PROMPTS ON AND RESET CLEAR DOES NOT TURN THEM OFF.
- Try
- ' allow connection time to materialize
- Threading.Thread.Sleep(100)
- Try
- Me.StoreTimeout(Me.ConnectTimeout)
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Clearing error queue.")
- ' clear the error queue on the controller node only.
- Me.ClearErrorQueue()
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Information, "EXCEPTION OCCURRED CLEARING ERROR QUEUE",
- "Exception occurred clearing error queue. Details: {0}. Ignored.", ex)
- Finally
- Me.RestoreTimeout()
- End Try
- Try
- Me.StoreTimeout(Me.ConnectTimeout)
- ' turn prompts off. This may not be necessary.
- TurnPromptsErrorsOff()
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Information, "EXCEPTION OCCURRED TURNING OFF PROMPTS",
- "Exception occurred turning off prompts. Details: {0}. Ignored.", ex)
- Finally
- Me.RestoreTimeout()
- End Try
- ' flush the input buffer in case the instrument has some left overs.
- DiscardUnreadData()
- DiscardUnsentData()
- ' flush write may cause the instrument to send off a new data.
- DiscardUnreadData()
- ' establish the current node as the controller node.
- Dim modelNumber As String = Me.QueryTrimEnd("print(localnode.model)")
- Dim controllerNodeNumber As Integer = Me.LocalNodeNumber
- Me._controllerNode = New NodeEntity(controllerNodeNumber, modelNumber, controllerNodeNumber)
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Error, "EXCETION OCCURRED TURNING OFF PROMPTS AND ERRORS",
- "Exception occurred turning off prompts and errors. Details: {0}", ex)
- If e IsNot Nothing Then
- e.Cancel = True
- End If
- End Try
- MyBase.OnConnecting(e)
- End Sub
- ''' <summary>Closes the device.
- ''' Performs the necessary termination
- ''' functions, which will cleanup and disconnect the
- ''' interface connection.
- ''' </summary>
- ''' <history>
- ''' </history>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Overrides Function Disconnect() As Boolean
- ' Close the device
- Return MyBase.Disconnect()
- End Function
- ''' <summary>Raises the disconnecting event.</summary>
- ''' <param name="e">Passes reference to the <see cref="System.EventArgs">event arguments</see>.</param>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Protected Overrides Sub OnDisconnecting(ByVal e As System.ComponentModel.CancelEventArgs)
- Dim synopsis As String = "On Disconnecting"
- If Me.IsConnected Then
- Try
- ' send termination command
- If Not Me.WriteLine("localnode.prompts = 0 localnode.showerrors = 0") Then
- MyBase.OnMessageAvailable(TraceEventType.Warning, synopsis, "Failed turning off prompts or error messages.")
- End If
- Me.ReportVisaDeviceOperationOkay(False, synopsis, "turning off prompts or error messages")
- Catch ex As BaseException
- MyBase.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception occurred turning off prompts or error messages. Details: {0}", ex)
- End Try
- End If
- MyBase.OnDisconnecting(e)
- End Sub
- #End Region
- #Region " IRESETTABLE "
- ''' <summary>
- ''' Reset known state of this instance.
- ''' </summary>
- ''' <remarks></remarks>
- Public Sub ResetLocalKnownState() Implements ITspInstrument.ResetLocalKnownState
- Me._firmwareExists = New Boolean?
- Me._supportfirmwareExists = New Boolean?
- Me._serialNumber = New Long?
- Me._isTspLinkOnline = New Boolean?
- Me._lastFetchedSavedRemoteScripts = ""
- End Sub
- #End Region
- #Region " IINITIALIZATABLE "
- Private _systemInitTimeout As Integer
- ''' <summary>
- ''' Gets or sets the time out for initializing the TSP system.
- ''' </summary>
- Public Property SystemInitTimeout() As Integer Implements ITspInstrument.SystemInitTimeout
- Get
- Return Me._systemInitTimeout
- End Get
- Set(ByVal Value As Integer)
- Me._systemInitTimeout = Value
- End Set
- End Property
- Public Function InitializeSystemState() As Boolean Implements Core.IInitializable.InitializeSystemState
- Try
- Me.StoreTimeout(Me._systemInitTimeout)
- Return True
- Catch
- Throw
- Finally
- Me.RestoreTimeout()
- End Try
- End Function
- Public Function InitializeSystemState(ByVal timeout As Integer) As Boolean Implements Core.IInitializable.InitializeSystemState
- Me._systemInitTimeout = timeout
- Return Me.InitializeSystemState
- End Function
- #End Region
- #Region " PROMPT HANDLING "
- ''' <summary>
- ''' Flushes the read buffer ignoring errors.
- ''' </summary>
- ''' <param name="reportUnderData">Specifies the condition for reporting unread data.</param>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Private Sub _discardUnreadData(ByVal reportUnderData As Boolean)
- Try
- Me.StoreTimeout(1000)
- MyBase.DiscardUnreadData(10, 100, reportUnderData)
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Verbose, "EXCEPTION occurred FLUSHING READ BUFFER",
- "Exception occurred flushing read buffer. Details: {0}. Ignored.", ex)
- Finally
- Me.RestoreTimeout()
- End Try
- End Sub
- Private _statusLatency As Integer
- ''' <summary>
- ''' Gets or sets the time to delay checking the instrument status. This allows the instrument
- ''' time to process a write command, return the status prompt and update the message and error available bits.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Property StatusLatency() As Integer
- Get
- Return Me._statusLatency
- End Get
- Set(ByVal value As Integer)
- Me._statusLatency = value
- End Set
- End Property
- Private _statusRepeatCount As Integer
- ''' <summary>
- ''' Gets or sets the number of time to check before returning status.
- ''' It seems that the instruments has some delay resetting the status that get cleared only after
- ''' repeated checks.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Property StatusRepeatCount() As Integer
- Get
- Return Me._statusRepeatCount
- End Get
- Set(ByVal value As Integer)
- Me._statusRepeatCount = value
- End Set
- End Property
- ''' <summary>Reads the device status data byte and returns True
- ''' if the message available bits were set.
- ''' Delays looking for the message status by the status latency to make sure
- ''' the instrument had enough time to process the previous command.
- ''' </summary>
- ''' <returns>True if the device has data in the queue
- ''' </returns>
- Public Overrides Function IsMessageAvailable() As Boolean
- ' wait for the instrument to process the previous command before checking the message status.
- If Me._statusLatency > 0 Then
- Threading.Thread.Sleep(Me._statusLatency)
- For i As Integer = 1 To Me.StatusRepeatCount
- MyBase.IsMessageAvailable()
- Next
- End If
- ' check if we have data in the queue
- Return MyBase.IsMessageAvailable
- End Function
- ''' <summary>
- ''' Flushes the read buffer.
- ''' </summary>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Overloads Function DiscardUnreadData() As Boolean
- Dim synopsis As String = "Flushing read buffer"
- If Me.IsMessageAvailable Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' flushing read buffer", Me.ResourceName)
- End If
- ' flush the input buffer in case the instrument has some left overs.
- Try
- Me.StoreTimeout(1000)
- MyBase.DiscardUnreadData(10, 100, True)
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Error, "EXCEPTION occurred FLUSHING READ BUFFER.",
- "Exception occurred flushing read buffer. Details: {0}", ex)
- Finally
- Me.RestoreTimeout()
- End Try
- End Function
- ''' <summary>
- ''' Flushes the read buffer.
- ''' </summary>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Sub DiscardUnsentData()
- Try
- Me.StoreTimeout(1000)
- Me.FlushWrite()
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Error, "EXCEPTION occurred FLUSHING WRITE BUFFER",
- "Exception occurred flushing write buffer. Details: {0}", ex)
- Finally
- Me.RestoreTimeout()
- End Try
- End Sub
- ''' <summary>
- ''' Turns off prompts and errors. It seems that the new systems come with prompts and errors off when
- ''' the instrument is started or reset so this is not needed.
- ''' </summary>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Sub TurnPromptsErrorsOff()
- Dim synopsis As String = "Turning Prompts Off"
- ' flush the input buffer in case the instrument has some left overs.
- Me._discardUnreadData(True)
- Try
- ' turn off prompt transmissions
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' turning off automatic sending of prompt messages. Ignoring errors.", Me.ResourceName)
- Me.WriteLine(TspSyntax.ShowPromptsCommand(False))
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Verbose, "EXCEPTION occurred TURNING OFF AUTOMATIC SENDING OF PROMPT MESSASGES",
- "Exception occurred turning off automatic sending of prompt messages. Details: {0}. Exception ignored.", ex)
- End Try
- ' flush again in case turning off prompts added stuff to the buffer.
- Me._discardUnreadData(True)
- Try
- ' turn off error transmissions
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' turning off automatic sending of error messages. Ignoring errors.", Me.ResourceName)
- Me.WriteLine(TspSyntax.ShowErrorsCommand(False))
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis,
- "Exception occurred turning off automatic sending of error messages. Details: {1}. Exception ignored.",
- Me.ResourceName, ex)
- End Try
- ' flush again in case turning off errors added stuff to the buffer.
- Me._discardUnreadData(True)
- ' flush visa and device errors
- ' Me.FlashVisaAndDeviceErrors(False, synopsis, "before or while turning off prompts and errors.")
- Me.ReportVisaDeviceOperationOkay(False, synopsis, "before or while turning off prompts and errors.")
- End Sub
- #End Region
- #Region " TSP: DISPLAY "
- ''' <summary>
- ''' Clears the display
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks>
- ''' Sets teh display to the user mode.
- ''' </remarks>
- Public Function ClearDisplay() As Boolean Implements ITspInstrument.ClearDisplay
- Me._displayStatus = DisplayScreens.User
- If Not Me.IsDisplayExists Then
- Return True
- End If
- Me.WriteLine("display.clear()")
- Return Me.ReportVisaDeviceOperationOkay(False, "Clear Display", "clearing display")
- End Function
- ''' <summary>
- ''' Clears the display if not in measurement mode and set measurement mode.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks>
- ''' Sets the display to the user mode.
- ''' </remarks>
- Public Function ClearDisplayMeasurement() As Boolean
- If Me.IsDisplayExists Then
- If (Me._displayStatus And DisplayScreens.Measurement) = 0 Then
- Me.ClearDisplay()
- End If
- End If
- Me._displayStatus = DisplayScreens.Measurement
- Return MyBase.LastOperationOkay
- End Function
- ''' <summary>
- ''' Displays message on line one of the display.
- ''' </summary>
- Public Function DisplayLine(ByVal lineNumber As Integer, ByVal format As String, ByVal ParamArray args() As Object) As Boolean Implements ITspInstrument.DisplayLine
- Return Me.DisplayLine(lineNumber, String.Format(Globalization.CultureInfo.CurrentCulture, format, args))
- End Function
- ''' <summary>
- ''' Displays a message on the display.
- ''' </summary>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DisplayLine(ByVal lineNumber As Integer, ByVal value As String) As Boolean Implements ITspInstrument.DisplayLine
- Me._displayStatus = DisplayScreens.User Or DisplayScreens.Custom
- If Not Me.IsDisplayExists Then
- Return True
- End If
- ' ignore empty strings.
- If String.IsNullOrEmpty(value) Then
- Return True
- End If
- Dim length As Integer = 20
- If lineNumber < 1 Then
- lineNumber = 1
- ElseIf lineNumber > 2 Then
- lineNumber = 2
- End If
- If lineNumber = 2 Then
- length = 33
- End If
- If Me.WriteLine("display.setcursor({0}, 1)", lineNumber) Then
- If value.Length < length Then
- value = value.PadRight(length)
- End If
- If Me.WriteLine("display.settext('{0}')", value) Then
- End If
- Else
- Return False
- End If
- Return Me.ReportVisaDeviceOperationOkay(False, "Display Line", "displaying line {0}.", lineNumber)
- End Function
- Private _displayStatus As DisplayScreens
- ''' <summary>
- ''' Gets the <see cref="DisplayScreens">display screen and status</see>.
- ''' </summary>
- ''' <remarks></remarks>
- Public ReadOnly Property DisplayScreen() As DisplayScreens
- Get
- Return Me._displayStatus
- End Get
- End Property
- ''' <summary>
- ''' Displays the program title.
- ''' </summary>
- ''' <param name="title">Top row data.</param>
- ''' <param name="subtitle">Bottom row data.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DisplayTitle(ByVal title As String, ByVal subtitle As String) As Boolean
- If Not Me.DisplayLine(0, title) Then
- Me._displayStatus = DisplayScreens.User Or DisplayScreens.Title
- Return False
- End If
- If Not Me.DisplayLine(2, subtitle) Then
- Me._displayStatus = DisplayScreens.User Or DisplayScreens.Title
- Return False
- End If
- Return True
- End Function
- Private _isDisplayExists As Boolean?
- ''' <summary>
- ''' Gets the display existence indicator. Some TSP instruments (e.g., 3706) may have no display.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property IsDisplayExists() As Boolean Implements ITspInstrument.IsDisplayExists
- Get
- If Not Me._isDisplayExists.HasValue Then
- Try
- ' detect the display
- Me._isDisplayExists = Not Me.IsNil("display")
- Catch ex As isr.Visa.BaseException
- ' throw an exception
- Me.OnMessageAvailable(TraceEventType.Error, "EXCEPTION OCCURRED CHECKING DISPLAY EXISTANCE.",
- "Exception occurred checking display existence. Details: {0}", ex)
- Me._isDisplayExists = False
- Finally
- End Try
- End If
- Return Me._isDisplayExists.Value
- End Get
- End Property
- ''' <summary>
- ''' Restores the instrument display to its main mode.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function RestoreDisplay() As Boolean Implements ITspInstrument.RestoreDisplay
- Me._displayStatus = DisplayScreens.Default
- If Not Me.IsDisplayExists Then
- Return True
- End If
- ' Documentation error: Display Main equals 1, not 0. This code should work on
- ' other instruments.
- Me.WriteLine("display.screen = display.MAIN or 0")
- Return Me.ReportVisaDeviceOperationOkay(False, "Restore Display", "restoring display")
- End Function
- #End Region
- #Region " TSP: ERRORS "
- Private _showErrors As Nullable(Of Boolean)
- ''' <summary>Gets the condition for showing errors.
- ''' </summary>
- Public ReadOnly Property ShowErrors() As Nullable(Of Boolean) Implements ITspInstrument.ShowErrors
- Get
- Return Me._showErrors
- End Get
- End Property
- ''' <summary>Returns the condition for showing errors.
- ''' When true, the unit will automatically display the errors stored in the
- ''' error queue, and then clear the queue. Errors will be processed at the
- ''' end of executing a command message (just prior to issuing a prompt if
- ''' prompts are enabled).
- ''' When false, errors will not display. Errors will be left in the error
- ''' queue and must be explicitly read or cleared. The error prompt (TSP?)
- ''' is enabled.
- ''' </summary>
- ''' <param name="access"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ShowErrorsGetter(ByVal access As isr.Visa.ResourceAccessLevels) As Boolean Implements ITspInstrument.ShowErrorsGetter
- If (access = Visa.ResourceAccessLevels.Device) OrElse Not Me._showErrors.HasValue Then
- If Me.WriteQueryLine(TspSyntax.ShowErrorsQueryCommand) Then
- If Me.RaiseVisaOrDeviceException("failed getting error prompts status") Then
- Me._showErrors = 1 = Me.ReadInt32().Value
- End If
- End If
- Me.RaiseVisaOrDeviceException("failed getting error prompts status")
- End If
- Return Me._showErrors.Value
- End Function
- ''' <summary>Sets the condition for showing errors.
- ''' When true, the unit will automatically display the errors stored in the
- ''' error queue, and then clear the queue. Errors will be processed at the
- ''' end of executing a command message (just prior to issuing a prompt if
- ''' prompts are enabled).
- ''' When false, errors will not display. Errors will be left in the error
- ''' queue and must be explicitly read or cleared. The error prompt (TSP?)
- ''' is enabled.
- ''' </summary>
- ''' <param name="access"></param>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ShowErrorsSetter(ByVal value As Boolean, ByVal access As isr.Visa.ResourceAccessLevels) As Boolean Implements ITspInstrument.ShowErrorsSetter
- If (access = Visa.ResourceAccessLevels.Device) OrElse (Not Me._showErrors.HasValue) OrElse (value <> showErrors.Value) Then
- ' now send the command. This will also update the status.
- If Me.WriteLine(TspSyntax.ShowErrorsCommand(value)) Then
- Me._showErrors = value
- End If
- Me.RaiseVisaOrDeviceException("failed setting error prompts status to {0}", value)
- End If
- Return Me._showErrors.Value
- End Function
- #End Region
- #Region " TSP: GLOBAL "
- ''' <summary>
- ''' Sends a collect garbage command.
- ''' </summary>
- Public Function CollectGarbage() As Boolean Implements ITspInstrument.CollectGarbage
- ' send the message
- Return Me.WriteLine(TspSyntax.CollectGarbageCommand)
- End Function
- ''' <summary>
- ''' Collects garbage on the specified node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function CollectGarbage(ByVal nodeNumber As Integer) As Boolean Implements ITspInstrument.CollectGarbage
- ' send the message
- Return Me.WriteLine(TspSyntax.CollectNodeGarbage, nodeNumber)
- End Function
- #End Region
- #Region " TSP: NODE "
- ''' <summary>
- ''' Gets the error count on a remote node.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Overloads Function ErrorQueueCount(ByVal nodeNumber As Integer) As Integer
- If nodeNumber <= 1 Then
- Return MyBase.ErrorQueueCount(Visa.ResourceAccessLevels.Device)
- Else
- Dim count As Integer? = Me.QueryInt32("print(string.format('%d',node[{0}].errorqueue.count)) waitcomplete()", nodeNumber)
- If Me.ReportVisaOperationOkay("Fetch error queue count", "Failed fetching error queue count from node {0}", nodeNumber) Then
- Return count.Value
- Else
- Return 0
- End If
- End If
- End Function
- ''' <summary>
- ''' Fetches the error queue.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks>Error messages are formatted as follows:<para>
- ''' Error #,message,level=#.</para>
- ''' <list type="bullet">
- ''' <listheader><description>Error levels are:</description>
- ''' </listheader>
- ''' <item><description>0 - Informational.</description></item>
- ''' <item><description>10 - Informational.</description></item>
- ''' <item><description>30 - Serious.</description></item>
- ''' <item><description>40 - Critical.</description></item>
- ''' </list>
- ''' </remarks>
- Public Function DequeueErrorQueue(ByVal nodeNumber As Integer) As String
- If nodeNumber <= 1 Then
- Return MyBase.ErrorQueue(Visa.ResourceAccessLevels.Device)
- Else
- Dim errors As New System.Text.StringBuilder(2048)
- Do While Me.ErrorQueueCount(nodeNumber) > 0
- Dim message As String = Me.QueryPrintFormat(String.Format(Globalization.CultureInfo.CurrentCulture,
- "error %d,%s,level=%d,node{0}", nodeNumber),
- String.Format(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].errorqueue.next()", nodeNumber))
- If Me.ReportVisaDeviceOperationOkay(True, "dequeue node error", "failed dequeuing errors from node {0}", nodeNumber) Then
- errors.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "{0},node={1}", message, nodeNumber)
- errors.AppendLine()
- Else
- errors.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "Error occurred fetching error queue element from node {0}", nodeNumber)
- errors.AppendLine()
- Return errors.ToString
- End If
- Loop
- Return errors.ToString
- End If
- End Function
- ''' <summary>
- ''' Dequeues errors on all nodes.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DequeueErrorQueue() As String
- Dim builder As New isr.Core.MyStringBuilder
- For Each node As NodeEntity In Me._nodeEntities
- If Me.ErrorQueueCount(node.Number) > 0 Then
- Dim errors As String = Me.DequeueErrorQueue(node.Number)
- If Not String.IsNullOrEmpty(errors) Then
- builder.AppendLine("Node #{0} errors: {1}", node.Number, errors)
- End If
- End If
- Next
- Return builder.ToString
- End Function
- ''' <summary>
- ''' Reports if a device error occurred as set the <see cref="LastOperationOkay">success condition</see>
- ''' Can only be used after receiving a full reply from the instrument.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number.</param>
- ''' <param name="synopsis">Specifies a synopsis for the warning if an error occurred.</param>
- ''' <param name="format">Specifies the report format.</param>
- ''' <param name="args">Specifies the report arguments.</param>
- ''' <returns>True if success</returns>
- ''' <remarks></remarks>
- Public Function ReportDeviceOperationOkay(ByVal nodeNumber As Integer, ByVal synopsis As String,
- ByVal format As String, ByVal ParamArray args() As Object) As Boolean Implements ITspInstrument.ReportDeviceOperationOkay
- MyBase.ReportVisaDeviceOperationOkay(False, synopsis, format, args)
- If nodeNumber > 1 AndAlso Me.ErrorQueueCount(nodeNumber) > 0 Then
- Me.LastOperationOkay = False
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{1}' encountered errors {0}. Details:{3}{2}{3}{4}",
- String.Format(Globalization.CultureInfo.CurrentCulture, format, args),
- Me.ResourceName,
- Me.DequeueErrorQueue(nodeNumber),
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return Me.LastOperationOkay
- End Function
- ''' <summary>
- ''' Makes a script nil and returns true if the script was nilified.
- ''' Does not check if the script exists.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>Assumes the script is known to exist.
- ''' Waits till completion.
- ''' </remarks>
- Private Function _nilifyScript(ByVal nodeNumber As Integer, ByVal name As String) As Boolean
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Dim synopsis As String = "Nullifying Script"
- ' ignore errors as failure is handled below.
- Me.ExecuteCommandWaitComplete(nodeNumber, Me._nilifyTimeout, False, "{0} = nil", name)
- ' allow the next command to create an error if wait complete times out.
- If Me.IsNil(nodeNumber, name) Then
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' script {1} still exists on node {2} after nil.{3}{4}",
- Me.ResourceName, name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End Function
- ''' <summary>
- ''' Makes a script nil and returns true if the script was nullified.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function NilifyScript(ByVal nodeNumber As Integer, ByVal name As String) As Boolean Implements ITspInstrument.NilifyScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If Me.IsNil(nodeNumber, name) Then
- Return True
- Else
- Return Me._nilifyScript(nodeNumber, name)
- End If
- End Function
- ''' <summary>
- ''' Sets the connect rule on the specified node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ConnectRuleSetter(ByVal nodeNumber As Integer, ByVal value As Integer) As Boolean Implements ITspInstrument.ConnectRuleSetter
- Return Me.WriteLine(TspSyntax.ConnectRuleSetter, nodeNumber, value)
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> script.
- ''' Also nilifies the script if delete command worked.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DeleteScript(ByVal nodeNumber As Integer, ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.DeleteScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If Me.SavedScriptExists(nodeNumber, name, refreshScriptCatalog) Then
- Return Me.DeleteSavedScript(nodeNumber, name)
- Else
- Return Me.NilifyScript(nodeNumber, name)
- End If
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> script.
- ''' Also nilifies the script if delete command worked.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DeleteScript(ByVal node As INodeEntity, ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If node.IsController Then
- Return DeleteScript(name, refreshScriptCatalog)
- Else
- Return DeleteScript(node.Number, name, refreshScriptCatalog)
- End If
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> saved script.
- ''' Also nilifies the script if delete command worked.
- ''' Then checks if the script was deleted and if so returns true.
- ''' Otherwise, returns false.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>Presumes the saved script exists.
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function DeleteSavedScript(ByVal nodeNumber As Integer, ByVal name As String) As Boolean
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Dim synopsis As String = "Deleting Saved Script"
- ' failure is handled below.
- Me.ExecuteCommandWaitComplete(nodeNumber, Me.DeleteTimeout, False, "script.delete('{0}')", name)
- ' make script nil
- If Me.NilifyScript(nodeNumber, name) Then
- ' make sure to re-check that script is gone.
- If Me.SavedScriptExists(nodeNumber, name, True) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' saved script {1} still exists after nil on node {2}{3}{4}",
- Me.ResourceName, name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Return True
- End If
- Else
- Return False
- End If
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> saved script.
- ''' Also nilifies the script if delete command worked.
- ''' Returns true if the script was deleted.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function DeleteSavedScript(ByVal nodeNumber As Integer, ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.DeleteSavedScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Dim synopsis As String = "Deleting Saved Script"
- If Me.SavedScriptExists(nodeNumber, name, refreshScriptCatalog) Then
- ' execute command but ignore errors as they are handled below.
- Me.ExecuteCommandWaitComplete(nodeNumber, Me.DeleteTimeout, False, "script.delete('{0}')", name)
- ' make script nil
- If Me.NilifyScript(nodeNumber, name) Then
- ' make sure to re-check that script is gone.
- If Me.SavedScriptExists(nodeNumber, name, True) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' saved script {1} still exists after nil on node {2}{3}{4}",
- Me.ResourceName, name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Return True
- End If
- Else
- Return False
- End If
- Else
- Return True
- End If
- End Function
- ''' <summary>
- ''' Executes a command on the node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number.</param>
- ''' <param name="isQuery">Specifies the condition indicating if the command is a query, which determines how errors are fetched.</param>
- ''' <param name="format">Specifies the command format.</param>
- ''' <param name="args">Specifies the command arguments.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ExecuteCommandWaitComplete(ByVal nodeNumber As Integer,
- ByVal timeout As Integer,
- ByVal isQuery As Boolean,
- ByVal format As String,
- ByVal ParamArray args() As Object) As Boolean
- Dim synopsis As String = "Execute node command"
- Dim command As String = String.Format(Globalization.CultureInfo.CurrentCulture, format, args)
- If Me.WriteLine(TspSyntax.ExecuteCommand, nodeNumber, command) Then
- IssueWaitComplete(0)
- Me.AwaitOperationCompleted(timeout, timeout \ 10 + 10)
- If isQuery Then
- If Not ReportVisaOperationOkay(synopsis, "executing '{0}' on node {1}", command, nodeNumber) Then
- Return False
- End If
- Else
- If Not ReportDeviceOperationOkay(nodeNumber, synopsis, "executing '{0}' on node {1}", command, nodeNumber) Then
- Return False
- End If
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed executing '{1}' on node {2}.{3}{4}",
- Me.ResourceName, command, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Executes a command on the node.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="isQuery">Specifies the condition indicating if the command is a query, which determines how errors are fetched.
- ''' While the remote command will not return values, the local node may.</param>
- ''' <param name="format">Specifies the command format.</param>
- ''' <param name="args">Specifies the command arguments.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ExecuteCommandWaitComplete(ByVal node As INodeEntity,
- ByVal timeout As Integer,
- ByVal isQuery As Boolean,
- ByVal format As String,
- ByVal ParamArray args() As Object) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Dim synopsis As String = "Execute node command"
- Dim command As String = String.Format(Globalization.CultureInfo.CurrentCulture, format, args)
- If Me.WriteLine(format, args) Then
- IssueWaitComplete(0)
- Me.AwaitOperationCompleted(timeout, timeout \ 10 + 10)
- If isQuery Then
- If Not ReportVisaOperationOkay(synopsis, "executing '{0}' on node {1}", command, node.Number) Then
- Return False
- End If
- Else
- If Not ReportDeviceOperationOkay(node.Number, synopsis, "executing '{0}' on node {1}", command, node.Number) Then
- Return False
- End If
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed executing '{1}' on node {2}.{3}{4}",
- Me.ResourceName, command, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Return True
- Else
- Return Me.ExecuteCommandWaitComplete(node.Number, timeout, isQuery, format, args)
- End If
- End Function
- ''' <summary>
- ''' Executes a command on the remote node. This leaves an item in the input buffer that must be retried.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number.</param>
- ''' <param name="format">Specifies the command format.</param>
- ''' <param name="args">Specifies the command arguments.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ExecuteValueGetter(ByVal nodeNumber As Integer, ByVal format As String, ByVal ParamArray args() As Object) As Boolean Implements ITspInstrument.ExecuteValueGetter
- If String.IsNullOrEmpty(format) Then
- Throw New ArgumentNullException("format")
- Else
- Return Me.WriteLine(TspSyntax.ValueGetterCommand1, nodeNumber,
- String.Format(Globalization.CultureInfo.CurrentCulture, format, args))
- End If
- Return False
- End Function
- Private _lastFetchedSavedRemoteScripts As String
- ''' <summary>
- ''' Gets a comma-separated and comma-terminated list of the saved scripts
- ''' that was fetched last from the remote node. A new script is fetched after save and delete.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property LastFetchedSavedRemoteScripts() As String Implements ITspInstrument.LastFetchedSavedRemoteScripts
- Get
- Return Me._lastFetchedSavedRemoteScripts
- End Get
- End Property
- ''' <summary>
- ''' Fetches the list of saved scripts and saves it in the <see cref="LastFetchedSavedScripts"></see>
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function FetchSavedScripts(ByVal nodeNumber As Integer) As Boolean Implements ITspInstrument.FetchSavedScripts
- Dim synopsis As String = "Fetch Saved Scripts"
- Try
- Me.StoreTimeout(Me._saveTimeout)
- Me._lastFetchedSavedRemoteScripts = ""
- If Me.WriteQueryLine(TspSyntax.ValueGetterCommand2, nodeNumber, TspSyntax.ScriptCatalogGetterCommand, "names") Then
- If Me.ReportVisaDeviceOperationOkay(True, "Fetch Node Saved Scripts", "Failed fetching catalog from node {0}", nodeNumber) Then
- Me._lastFetchedSavedRemoteScripts = Me.ReadLineTrimEnd
- Else
- Return False
- End If
- If String.IsNullOrEmpty(Me._lastFetchedSavedRemoteScripts) Then
- Me._lastFetchedSavedRemoteScripts = ""
- End If
- End If
- Return ReportDeviceOperationOkay(nodeNumber, synopsis, "Failed fetching catalog from node {0}", nodeNumber)
- Catch
- Throw
- Finally
- MyBase.RestoreTimeout()
- End Try
- End Function
- ''' <summary>
- ''' Fetches the list of saved scripts and saves it in the <see cref="LastFetchedSavedScripts"></see>
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FetchSavedScripts(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return FetchSavedScripts()
- Else
- Return FetchSavedScripts(node.Number)
- End If
- End Function
- ''' <summary>
- ''' Executes a command on the remote node and retrieves a string.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number to validate.</param>
- ''' <param name="format">Specifies the command format.</param>
- ''' <param name="args">Specifies the command arguments.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function GetString(ByVal nodeNumber As Integer, ByVal format As String, ByVal ParamArray args() As Object) As String Implements ITspInstrument.GetString
- If Me.ExecuteValueGetter(nodeNumber, format, args) Then
- Return MyBase.ReadLineTrimEnd()
- Else
- Return ""
- End If
- End Function
- ''' <summary>
- ''' Executes a command on the remote node and retrieves a string.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number to validate.</param>
- ''' <param name="format">Specifies the command format.</param>
- ''' <param name="args">Specifies the command arguments.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function GetBoolean(ByVal nodeNumber As Integer, ByVal format As String, ByVal ParamArray args() As Object) As Boolean? Implements ITspInstrument.GetBoolean
- If Me.ExecuteValueGetter(nodeNumber, format, args) Then
- Return MyBase.ReadBoolean
- Else
- Return New Boolean?
- End If
- End Function
- ''' <summary>
- ''' Checks the series of values and return true if any one of them is nil.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number to validate.</param>
- ''' <param name="values">Specifies a list of nil objects to check.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsNil(ByVal nodeNumber As Integer, ByVal ParamArray values() As String) As Boolean Implements ITspInstrument.IsNil
- If values Is Nothing OrElse values.Length = 0 Then
- Throw New ArgumentNullException("values")
- Else
- For Each value As String In values
- If Not String.IsNullOrEmpty(value) Then
- Dim outcome As Boolean? = Me.GetBoolean(nodeNumber, "{0}==nil", value)
- If outcome.HasValue AndAlso outcome.Value Then
- Return True
- End If
- End If
- Next
- End If
- Return False
- End Function
- ''' <summary>
- ''' Checks the series of values and return true if any one of them is nil.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="values">Specifies a list of nil objects to check.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsNil(ByVal node As INodeEntity, ByVal ParamArray values() As String) As Boolean Implements ITspInstrument.IsNil
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return Me.IsNil(values)
- Else
- Return Me.IsNil(node.Number, values)
- End If
- End Function
- ''' <summary>
- ''' Loops until the name is found or timeout.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="timeout"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Private Function WaitNotNil(ByVal nodeNumber As Integer, ByVal name As String, ByVal timeout As Integer) As Boolean
- ' verify that the script exists.
- Dim endTime As DateTime = DateTime.Now.AddMilliseconds(timeout)
- Dim detected As Boolean = Not Me.IsNil(nodeNumber, name)
- Do Until detected OrElse DateTime.Now > endTime
- Windows.Forms.Application.DoEvents()
- Threading.Thread.Sleep(10)
- detected = Not Me.IsNil(nodeNumber, name)
- Loop
- Return detected
- End Function
- ''' <summary>
- ''' Resets the local TSP node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ResetNode() As Boolean
- Me.WriteLine("localnode.reset()")
- Me.ReportVisaDeviceOperationOkay(False, "Reset Node", "resetting local TSP node")
- End Function
- ''' <summary>
- ''' Resets a remote node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ResetNode(ByVal nodeNumber As Integer) As Boolean
- Dim synopsis As String = "Reset Node"
- Dim details As String = "resetting TSP node {0}"
- Me.WriteLine("node[{0}].reset()", nodeNumber)
- Return Me.ReportDeviceOperationOkay(nodeNumber, synopsis, details, nodeNumber)
- End Function
- ''' <summary>
- ''' Resets a node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ResetNode(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return Me.ResetNode()
- Else
- Return Me.ResetNode(node.Number)
- End If
- End Function
- ''' <summary>
- ''' Loads the binary script function for creating binary scripts.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks>
- ''' Non-A instruments require having a special function for creating the binary scripts.
- ''' </remarks>
- Private Function LoadBinaryScriptsFunction(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Const scriptName As String = "CreateBinaries"
- Using script As New ScriptEntity(scriptName, Tsp.NodeEntity.ModelFamilyMask(Tsp.InstrumentModelFamily.K2600))
- script.Source = EmbeddedResourceManager.EmbeddedTextResourceGetter("BinaryScripts.tsp")
- Return Me.LoadRunUserScript(script, node)
- End Using
- End Function
- ''' <summary>
- ''' Returns true if the script is a binary script.
- ''' </summary>
- ''' <param name="name">Specifies the name of the script.</param>
- ''' <param name="node">Specifies the node entity.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsBinaryScript(ByVal name As String, ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return Me.IsStatementTrue("_G.isr.script.isBinary({0})", name)
- Else
- Return Me.IsStatementTrue("_G.isr.script.isBinary({0},{1})", name, node.Number)
- End If
- End Function
- ''' <summary>
- ''' Converts the script to binary format.
- ''' Returns true if the script was converted.
- ''' </summary>
- ''' <param name="node">Specifies the node entity.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function ConvertBinaryScript(ByVal name As String, ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If String.IsNullOrEmpty(name) Then
- Return False
- ElseIf Me.IsBinaryScript(name, node) Then
- Return True
- End If
- Dim synopsis As String = "Convert Binary Script"
- If node.InstrumentModelFamily = InstrumentModelFamily.K2600A OrElse
- node.InstrumentModelFamily = InstrumentModelFamily.K3700 Then
- If Me.ExecuteCommandWaitComplete(node, Me.SaveTimeout, False, "{0}.source = nil waitcomplete()", name) Then
- End If
- Return Me.ReportVisaDeviceOperationOkay(False, synopsis, "creating binary script '{0}' on node {1}", name, node.Number)
- Else
- ' non-A instruments require having a special function for creating the binary scripts.
- If Me.LoadBinaryScriptsFunction(node) Then
- ' create the binary script.
- If Me.ExecuteCommandWaitComplete(node, Me.SaveTimeout, False, "CreateBinaryScript('{0}', {1}) waitcomplete()",
- name, name) Then
- Dim fullName As String = "script.user.scripts." & name
- If Me.WaitNotNil(node.Number, fullName, Me._saveTimeout) Then
- ' assign the new script name
- If Me.ExecuteCommandWaitComplete(node, Me.SaveTimeout, False,
- "{0} = nil waitcomplete() {0} = {1} waitcomplete()", name, fullName) Then
- If Me.WaitNotNil(node.Number, name, Me._saveTimeout) Then
- If IsBinaryScript(name, node) Then
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed creating binary script '{1}' reference to script '{2}' on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, name, fullName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed creating script '{1}' reference to script '{2}' on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, name, fullName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "creating script script '{0}'", name) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed creating reference to script '{1}' using '{2}' on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, fullName, name, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed creating script '{1}' from script {2} on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, fullName, name, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- ElseIf Me.ReportVisaDeviceOperationOkay(False, synopsis, "loading binary scripts function") Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed creating binary script {1}.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Return False
- End If
- Else
- Return False
- End If
- End If
- Return True
- End Function
- ''' <summary>
- ''' Saves the specifies script to non-volatile memory.
- ''' Returns true if the script was saved.
- ''' </summary>
- ''' <param name="node">Specifies the node entity.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="isSaveAsBinary">Specifies the condition requesting clearing the source before saving</param>
- ''' <param name="isBootScript">Specifies the condition indicating if this is a boot script</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function SaveScript(ByVal name As String, ByVal node As INodeEntity, ByVal isSaveAsBinary As Boolean, ByVal isBootScript As Boolean) As Boolean Implements ITspInstrument.SaveScript
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- ' saving just the script name does not work if script was created and name assigned.
- Dim commandFormat As String = "script.user.scripts.{0}.save() waitcomplete()"
- If isSaveAsBinary Then
- If Not Me.ConvertBinaryScript(name, node) Then
- Return False
- End If
- End If
- If isBootScript Then
- commandFormat = "script.user.scripts.{0}.autorun = 'yes' " & commandFormat
- End If
- If node.IsController Then
- Me.EnableWaitComplete()
- If Me.WriteLine(commandFormat, name) Then
- Me.AwaitOperationCompleted(Me.SaveTimeout, Me.SaveTimeout \ 10 + 10)
- End If
- Else
- If Me.ExecuteCommandWaitComplete(node.Number, Me.SaveTimeout, False, commandFormat, name) Then
- End If
- End If
- Return Me.SavedScriptExists(name, node, True)
- End Function
- ''' <summary>
- ''' Returns true if the specified script exists as a saved script on the remote node.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LastSavedRemoteScriptExists(ByVal name As String) As Boolean Implements ITspInstrument.LastSavedRemoteScriptExists
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Return Me._lastFetchedSavedRemoteScripts.IndexOf(name & ",", 0, StringComparison.OrdinalIgnoreCase) >= 0
- End Function
- ''' <summary>
- ''' Returns true if the specified script exists as a saved script.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number to validate.</param>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="refreshScriptCatalog">True to refresh the list of saved scripts.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SavedScriptExists(ByVal nodeNumber As Integer, ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.SavedScriptExists
- If refreshScriptCatalog Then
- Me.FetchSavedScripts(nodeNumber)
- End If
- Return LastSavedRemoteScriptExists(name)
- End Function
- ''' <summary>
- ''' Returns true if the specified script exists as a saved script.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="node">Specifies the node to validate.</param>
- ''' <param name="refreshScriptCatalog">True to refresh the list of saved scripts.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SavedScriptExists(ByVal name As String, ByVal node As INodeEntity, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.SavedScriptExists
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return SavedScriptExists(name, refreshScriptCatalog)
- Else
- Return SavedScriptExists(node.Number, name, refreshScriptCatalog)
- End If
- End Function
- Private _serialNumberReading As String = ""
- ''' <summary>
- ''' Reads and returns the instrument serial number
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ReadSerialNumber() As String
- Me._serialNumberReading = Me.QueryPrintFormat("%d", "localnode.serialno").Trim
- Return Me._serialNumberReading
- End Function
- Private _serialNumber As Long?
- ''' <summary>
- ''' Reads and returns the instrument serial number
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SerialNumber() As Long
- If Not Me._serialNumber.HasValue Then
- Dim numericValue As Long = 0
- If Long.TryParse(Me.ReadSerialNumber, Globalization.NumberStyles.Number, Globalization.CultureInfo.InvariantCulture, numericValue) Then
- Me._serialNumber = numericValue
- End If
- Me._serialNumber = numericValue
- End If
- Return Me._serialNumber.Value
- End Function
- #End Region
- #Region " TSP: NODES "
- Private _controllerNode As INodeEntity
- ''' <summary>
- ''' Gets reference to the controller node.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property ControllerNode() As INodeEntity
- Get
- Return Me._controllerNode
- End Get
- End Property
- Private _nodeEntities As NodeEntityCollection
- ''' <summary>
- ''' Returns the enumerated list of node entities.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function NodeEntities() As NodeEntityCollection Implements ITspInstrument.NodeEntities
- Return Me._nodeEntities
- End Function
- Private _maximumNodeCount As Integer
- ''' <summary>
- ''' Gets the maximum number of node to iterate when enumerating nodes.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Property MaximumNodeCount() As Integer
- Get
- Return Me._actualNodeCount
- End Get
- Set(ByVal value As Integer)
- Me._actualNodeCount = value
- End Set
- End Property
- Private _actualNodeCount As Integer
- ''' <summary>
- ''' Gets the number of nodes detected in the system.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property ActualNodeCount() As Integer
- Get
- Return Me._actualNodeCount
- End Get
- End Property
- ''' <summary>
- ''' Enumerates the collection of nodes on the TSP Link net.
- ''' </summary>
- ''' <param name="nodeCount">Specifies the maximum expected node number.
- ''' There could be up to 64 nodes on the TSP link. Specify 0 to use the maximum node count.</param>
- ''' <remarks></remarks>
- Public Function EnumerateNodes(ByVal nodeCount As Integer) As Boolean
- Dim synopsis As String = "Enumerating nodes"
- Me._actualNodeCount = 0
- If nodeCount <= 0 Then
- nodeCount = Me._maximumNodeCount
- End If
- Me._nodeEntities = New NodeEntityCollection()
- Dim controllerNodeNumber As Integer = Me.LocalNodeNumber
- If nodeCount = 1 Then
- Me._actualNodeCount = 1
- Dim modelNumber As String = Me.QueryTrimEnd("print(localnode.model)")
- Me._controllerNode = New NodeEntity(Me.LocalNodeNumber, modelNumber, controllerNodeNumber)
- If Me._controllerNode.InstrumentModelFamily = InstrumentModelFamily.None Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument model {0} has no defined instrument family.{1}{2}",
- modelNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Else
- Me._nodeEntities.Add(Me._controllerNode)
- End If
- Else
- For i As Integer = 1 To nodeCount
- If Not Me.IsStatementTrue("node[{0}] == nil", i) Then
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "Failed enumerating nodes") Then
- Me._actualNodeCount += 1
- ' set the group number.
- Dim modelNumber As String = Me.QueryTrimEnd("print(node[{0}].model)", i)
- Dim node As Tsp.INodeEntity = New NodeEntity(i, modelNumber, controllerNodeNumber)
- node.FirmwareVersion = Me.QueryTrimEnd("print(node[{0}].revision)", i)
- node.SerialNumber = Me.QueryTrimEnd("print(node[{0}].serialno)", i)
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument model {0} S/N={1} Firmware={2} enumerated on node {3}.",
- node.ModelNumber, node.SerialNumber, node.FirmwareVersion, node.Number)
- If i = controllerNodeNumber Then
- Me._controllerNode = node
- End If
- If node.InstrumentModelFamily = InstrumentModelFamily.None Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument model {0} has no defined instrument family.{1}{2}",
- modelNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Else
- Me._nodeEntities.Add(node)
- End If
- End If
- End If
- Next
- End If
- Return Me._nodeEntities.Count = Me._actualNodeCount
- End Function
- #End Region
- #Region " TSP OPC "
- ''' <summary>
- ''' Waits for completion of last operation.
- ''' </summary>
- ''' <param name="timeout"></param>
- ''' <param name="pollDelay"></param>
- ''' <returns>True if operation completed within the specified timeout.</returns>
- ''' <remarks>
- ''' Assumes requesting service event is registered with the instrument.
- ''' </remarks>
- Public Function AwaitOperationCompleted(ByVal timeout As Integer, ByVal pollDelay As Integer) As Boolean
- Me.AwaitServiceRequest(Visa.Ieee4882.ServiceRequests.RequestingService, timeout, pollDelay)
- Me.ReportVisaDeviceOperationOkay(False, "Await Completion", "waiting operation completion. Error ignored.")
- Return Not Me.TimedOut
- End Function
- ''' <summary>
- ''' Enabled detection of completion.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks>
- ''' 3475. Add Or Visa.Ieee4882.ServiceRequests.OperationEvent
- ''' </remarks>
- Public Function EnableWaitComplete() As Boolean
- Return Me.EnableServiceRequestComplete(Visa.Ieee4882.StandardEvents.All And Not Visa.Ieee4882.StandardEvents.RequestControl,
- Visa.Ieee4882.ServiceRequests.StandardEvent)
- End Function
- ''' <summary>
- ''' Issues wait complete for the node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IssueWaitComplete() As Boolean
- If Me.EnableWaitComplete Then
- Return Me.WriteLine("waitcomplete()")
- Else
- Return False
- End If
- End Function
- ''' <summary>
- ''' Issues wait complete for the group.
- ''' </summary>
- ''' <param name="groupNumber">Specifies the group number. That would be the same as the
- ''' TSP Link group number for the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IssueWaitComplete(ByVal groupNumber As Integer) As Boolean
- If Me.EnableWaitComplete Then
- Return Me.WriteLine("waitcomplete({0})", groupNumber)
- Else
- Return False
- End If
- End Function
- ''' <summary>
- ''' Queries the instrument and returns true if received an operation completed value (1).
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsOperationCompleted() As Boolean
- IsOperationCompleted = Me.OperationCompleted(Visa.ResourceAccessLevels.Device)
- Me.ReportVisaDeviceOperationOkay(False, "Read OPC value", "reading OPC value. Error ignored.")
- End Function
- #End Region
- #Region " TSP LINK "
- #Region " DATA QUEUE "
- ''' <summary>
- ''' clears the data queue for the specified node.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ClearDataQueue(ByVal nodeNumber As Integer, ByVal reportQueueNotEmpty As Boolean) As Boolean
- If IsStatementTrue("node[{0}] == nil", nodeNumber) Then
- Return True
- Else
- If reportQueueNotEmpty Then
- If DataQueueCount(nodeNumber) > 0 Then
- Me.OnMessageAvailable(TraceEventType.Information, "Clear Data Queue", "Data queue not empty on node {0}", nodeNumber)
- Return MyBase.WriteLine("node[{0}].dataqueue.clear() waitcomplete({0})", nodeNumber)
- End If
- Else
- Return MyBase.WriteLine("node[{0}].dataqueue.clear() waitcomplete({0})", nodeNumber)
- End If
- End If
- Return True
- End Function
- ''' <summary>
- ''' Clears dataqueue on all nodes.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ClearDataQueue(ByVal reportQueueNotEmpty As Boolean) As Boolean
- Dim success As Boolean = True
- If Me._nodeEntities IsNot Nothing Then
- For Each node As INodeEntity In Me._nodeEntities
- If Not ClearDataQueue(node.Number, reportQueueNotEmpty) Then
- success = False
- End If
- Next
- End If
- Return success
- End Function
- ''' <summary>
- ''' Returns true if the node dataqueue has elements in it.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DataQueueCapacity(ByVal nodeNumber As Integer) As Integer
- If IsStatementTrue("node[{0}] == nil", nodeNumber) Then
- Return 0
- Else
- Dim count As String = Me.QueryPrintFormat("%d", String.Format(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].dataqueue.capacity", nodeNumber))
- Dim value As Integer = 0
- If Integer.TryParse(count, Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, value) Then
- Return value
- Else
- Return 0
- End If
- End If
- End Function
- ''' <summary>
- ''' Returns true if the node dataqueue has elements in it.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DataQueueCount(ByVal nodeNumber As Integer) As Integer
- If IsStatementTrue("node[{0}] == nil", nodeNumber) Then
- Return 0
- Else
- Dim count As String = Me.QueryPrintFormat("%d", String.Format(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].dataqueue.count", nodeNumber))
- Dim value As Integer = 0
- If Integer.TryParse(count, Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, value) Then
- Return value
- Else
- Return 0
- End If
- End If
- End Function
- #End Region
- #Region " ERROR QUEUE "
- ''' <summary>
- ''' Clears the error queue for the specified node.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Overloads Function ClearErrorQueue(ByVal nodeNumber As Integer) As Boolean
- If IsStatementTrue("node[{0}] == nil", nodeNumber) Then
- Return True
- Else
- Return MyBase.WriteLine("node[{0}].errorqueue.clear() waitcomplete({0})", nodeNumber)
- End If
- End Function
- ''' <summary>
- ''' Clears error queue on all nodes or the controller if no nodes are defined.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Overrides Function ClearErrorQueue() As Boolean
- Dim success As Boolean = True
- If Me._nodeEntities Is Nothing Then
- MyBase.ClearErrorQueue()
- Else
- For Each node As INodeEntity In Me._nodeEntities
- If Not ClearErrorQueue(node.Number) Then
- success = False
- End If
- Next
- End If
- Return success
- End Function
- #End Region
- Private _usingTspLink As Boolean
- ''' <summary>
- ''' Gets or sets the condition for using TSP Link.
- ''' Must be affirmative otherwise TSP link reset commands are ignored.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Property UsingTspLink() As Boolean
- Get
- Return Me._usingTspLink
- End Get
- Set(ByVal value As Boolean)
- Me._usingTspLink = value
- End Set
- End Property
- Private _isTspLinkOnline As Boolean?
- ''' <summary>
- ''' Checks if TSP System is ready.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property IsTspLinkOnline() As Boolean
- Get
- If Me._usingTspLink Then
- If Not Me._isTspLinkOnline.HasValue Then
- Me._isTspLinkOnline = Me.IsStatementTrue("tsplink.state == 'online'")
- End If
- Else
- Me._isTspLinkOnline = False
- End If
- Return Me._isTspLinkOnline.Value
- End Get
- End Property
- ''' <summary>
- ''' Assigns group numbers to the nodes.
- ''' A unique group number is required for executing
- ''' concurrent code on all nodes.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history date="09/08/2009" by="David Hary" revision="3.0.3538.x">
- ''' Allows setting groups even if TSP Link is not on line.
- ''' </history>
- Public Function AssignNodeGroupNumbers() As Boolean
- If Me._nodeEntities IsNot Nothing Then
- For Each node As INodeEntity In Me._nodeEntities
- If Me.IsTspLinkOnline Then
- Me.WriteLine("node[{0}].tsplink.group = {0}", node.Number)
- Else
- Me.WriteLine("localnode.tsplink.group = {0}", node.Number)
- End If
- If Not Me.ReportVisaDeviceOperationOkay(False, "Assign group numbers", "Failed assigning group to node number {0}", node.Number) Then
- Return False
- End If
- Next
- 'If Me.IsTspLinkOnline Then
- 'End If
- End If
- Return True
- End Function
- ''' <summary>
- ''' Reset TSP Link with error reporting.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history date="09/22/2009" by="David Hary" revision="3.0.3552.x">
- ''' The procedure caused error 1220 - TSP link failure on the remote instrument. The error occurred only
- ''' if the program was stopped and restarted without toggling power on the instruments.
- ''' Waiting completion of the previous task helped even though that task did not access the remote node!
- ''' </history>
- Private Function _resetTspLinkIgnoreError() As Boolean
- Dim synopsis As String = "Resetting TSP Link"
- Me._isTspLinkOnline = New Boolean?
- Me.IssueWaitComplete(0)
- If Not Me.AwaitOperationCompleted(Me.SaveTimeout, Me.SaveTimeout \ 10 + 10) Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' timed out awaiting completion before reseting TSP Link. Failure ignored.{1}{2}",
- Me.ResourceName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Me.EnableWaitComplete()
- If Me.WriteLine("tsplink.reset() waitcomplete(0) errorqueue.clear() waitcomplete()") Then
- If Not Me.AwaitOperationCompleted(Me.SaveTimeout, Me.SaveTimeout \ 10 + 10) Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' timed out awaiting completion after reseting TSP Link. Failure ignored.{1}{2}",
- Me.ResourceName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Else
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "Failed sending the TSP Link reset command.") Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed sending the TSP Link reset command.{1}{2}",
- Me.ResourceName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Reset TSP Link with error reporting.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")>
- Private Function _resetTspLinkReportError() As Boolean
- Dim synopsis As String = "Resetting TSP Link"
- Me._isTspLinkOnline = New Boolean?
- Me.EnableWaitComplete()
- If Me.WriteLine("tsplink.reset() waitcomplete(0)") Then
- If Me.AwaitOperationCompleted(Me.SaveTimeout, Me.SaveTimeout \ 10 + 10) Then
- If Not Me.ReportVisaDeviceOperationOkay(False, synopsis, "Failed resetting TSP Link") Then
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed awaiting completion after reseting TSP Link.{1}{2}",
- Me.ResourceName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "Failed resetting TSP Link") Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed reseting TSP Link.{1}{2}",
- Me.ResourceName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- End Function
- ''' <summary>
- ''' Resets the TSP link if not on line.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history date="09/08/2009" by="David Hary" revision="3.0.3538.x">
- ''' Allows to complete TSP Link reset even on failure in case we have a single node.
- ''' </history>
- Public Function ResetTspLink() As Boolean
- Me._nodeEntities = New NodeEntityCollection()
- If Me._usingTspLink Then
- If Not Me._resetTspLinkIgnoreError() Then
- Return False
- End If
- End If
- If Me.IsTspLinkOnline Then
- ' enumerate all nodes.
- If Not Me.EnumerateNodes(0) Then
- Return False
- End If
- ' enumerate the controller node.
- ElseIf Not Me.EnumerateNodes(1) Then
- Return False
- End If
- ' assign node group numbers.
- Me.AssignNodeGroupNumbers()
- ' clear the error queue on all nodes.
- Me.ClearErrorQueue()
- ' clear data queues.
- Me.ClearDataQueue(True)
- Return True
- End Function
- #End Region
- #Region " TSP: PROMPTS "
- Private _showPrompts As Nullable(Of Boolean)
- ''' <summary>Gets the condition for showing prompts.
- ''' </summary>
- Public ReadOnly Property ShowPrompts() As Nullable(Of Boolean) Implements ITspInstrument.ShowPrompts
- Get
- Return Me._showPrompts
- End Get
- End Property
- ''' <summary>Return the condition for showing prompts.
- ''' Controls prompting.
- ''' When true, prompts are issued after each command message is
- ''' processed by the instrument.
- ''' When false prompts are not issued.
- ''' Command messages do not generate prompts. Rather, the TSP instrument
- ''' generates prompts in response to command messages.
- ''' When prompting is enabled, the instrument generates prompts in
- ''' response to command messages. There are three prompts that might be
- ''' returned:
- ''' “TSP>” is the standard prompt. This prompt indicates that everything is
- ''' normal and the command is done processing.
- ''' “TSP?” is issued if there are entries in the error queue when the prompt
- ''' is issued. Like the “TSP>” prompt, it indicates the command is done
- ''' processing. It does not mean the previous command generated an error,
- ''' only that there are still errors in the queue when the command was done
- ''' processing.
- ''' “>>>>” is the continuation prompt. This prompt is used when downloading
- ''' scripts or flash images. When downloading scripts or flash images, many
- ''' command messages must be sent as a unit. The continuation prompt indicates
- ''' that the instrument is expecting more messages as part of the current
- ''' command.
- ''' </summary>
- ''' <param name="access"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ShowPromptsGetter(ByVal access As isr.Visa.ResourceAccessLevels) As Boolean Implements ITspInstrument.ShowPromptsGetter
- If (access = Visa.ResourceAccessLevels.Device) OrElse Not Me._showPrompts.HasValue Then
- If Me.WriteQueryLine(TspSyntax.ShowPromptsQueryCommand) Then
- If Me.RaiseVisaOrDeviceException("failed getting the condition for showing prompts.") Then
- Me._showPrompts = 1 = Me.ReadInt32().Value
- End If
- End If
- Me.RaiseVisaOrDeviceException("failed getting the condition for showing prompts.")
- End If
- Return Me._showPrompts.Value
- End Function
- ''' <summary>Sets the condition for showing prompts.
- ''' Controls prompting.
- ''' When true, prompts are issued after each command message is
- ''' processed by the instrument.
- ''' When false prompts are not issued.
- ''' Command messages do not generate prompts. Rather, the TSP instrument
- ''' generates prompts in response to command messages.
- ''' When prompting is enabled, the instrument generates prompts in
- ''' response to command messages. There are three prompts that might be
- ''' returned:
- ''' “TSP>” is the standard prompt. This prompt indicates that everything is
- ''' normal and the command is done processing.
- ''' “TSP?” is issued if there are entries in the error queue when the prompt
- ''' is issued. Like the “TSP>” prompt, it indicates the command is done
- ''' processing. It does not mean the previous command generated an error,
- ''' only that there are still errors in the queue when the command was done
- ''' processing.
- ''' “>>>>” is the continuation prompt. This prompt is used when downloading
- ''' scripts or flash images. When downloading scripts or flash images, many
- ''' command messages must be sent as a unit. The continuation prompt indicates
- ''' that the instrument is expecting more messages as part of the current
- ''' command.
- ''' </summary>
- ''' <param name="access"></param>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ShowPromptsSetter(ByVal value As Boolean, ByVal access As isr.Visa.ResourceAccessLevels) As Boolean Implements ITspInstrument.ShowPromptsSetter
- If (access = Visa.ResourceAccessLevels.Device) OrElse (Not Me._showPrompts.HasValue) OrElse (value <> showPrompts.Value) Then
- Dim previousValue As Nullable(Of Boolean) = Me._showErrors
- Me._showPrompts = value
- ' now send the command. This will also update the status.
- If Not Me.WriteLine(TspSyntax.ShowPromptsCommand(value)) Then
- Me._showErrors = previousValue
- End If
- Me.RaiseVisaOrDeviceException("failed setting the condition for showing prompts.")
- End If
- Return Me._showPrompts.Value
- End Function
- #End Region
- #Region " TSP SCRIPTS "
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> script.
- ''' Also nilifies the script if delete command worked.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DeleteScript(ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.DeleteScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If Me.SavedScriptExists(name, refreshScriptCatalog) Then
- Return Me.DeleteSavedScript(name)
- Else
- Return Me.NilifyScript(name)
- End If
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> saved script.
- ''' Also nilifies the script if delete command worked.
- ''' Returns true if the script was deleted.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>Assumes the script is known to exist.
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function DeleteSavedScript(ByVal name As String) As Boolean
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Me.EnableWaitComplete()
- Dim synopsis As String = "Deleting Saved Script"
- If Me.WriteLine("script.delete('{0}') waitcomplete()", name) Then
- ' make script nil
- Me.AwaitOperationCompleted(Me.DeleteTimeout, Me.DeleteTimeout \ 10 + 10)
- If Me.NilifyScript(name) Then
- ' make sure to re-check that script is gone.
- If Me.SavedScriptExists(name, True) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' script {1} still exists after nil.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Return True
- End If
- Else
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' sending the command to delete script {1}.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End Function
- ''' <summary>
- ''' Deletes the <paramref name="name">specified</paramref> saved script.
- ''' Also nilifies the script if delete command worked.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function DeleteSavedScript(ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.DeleteSavedScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If Me.SavedScriptExists(name, refreshScriptCatalog) Then
- Return DeleteSavedScript(name)
- Else
- Return True
- End If
- End Function
- Private _deleteTimeout As Integer
- ''' <summary>
- ''' Gets or sets the time out for deleting a script.
- ''' </summary>
- Public Property DeleteTimeout() As Integer
- Get
- Return Me._deleteTimeout
- End Get
- Set(ByVal Value As Integer)
- Me._deleteTimeout = Value
- End Set
- End Property
- ''' <summary>
- ''' Fetches the list of saved scripts and saves it in the <see cref="LastFetchedSavedScripts"></see>
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function FetchSavedScripts() As Boolean Implements ITspInstrument.FetchSavedScripts
- Try
- MyBase.StoreTimeout(Me._saveTimeout)
- Me._lastFetchedSavedScripts = ""
- If Me.WriteQueryLine("do {0} print( names ) end ", TspSyntax.ScriptCatalogGetterCommand) Then
- If Me.ReportVisaDeviceOperationOkay(True, "Fetch Saved Scripts", "Failed fetching catalog") Then
- Me._lastFetchedSavedScripts = Me.ReadLineTrimEnd
- Else
- Return False
- End If
- If String.IsNullOrEmpty(Me._lastFetchedSavedScripts) Then
- Me._lastFetchedSavedScripts = ""
- End If
- End If
- Return Me.ReportVisaDeviceOperationOkay(True, "Fetch Saved Scripts", "Failed fetching catalog. Timeout={0}", MyBase.Timeout)
- Catch
- Throw
- Finally
- MyBase.RestoreTimeout()
- End Try
- End Function
- Private _lastFetchedSavedScripts As String = ""
- ''' <summary>
- ''' Gets a comma-separated and comma-terminated list of the saved scripts
- ''' that was fetched last. A new script is fetched after save and delete.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property LastFetchedSavedScripts() As String Implements ITspInstrument.LastFetchedSavedScripts
- Get
- Return Me._lastFetchedSavedScripts
- End Get
- End Property
- Private _lastFetchScriptSource As String
- ''' <summary>
- ''' Gets the last source fetched from the instrument
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property LastFetchScriptSource() As String Implements ITspInstrument.LastFetchScriptSource
- Get
- Return Me._lastFetchScriptSource
- End Get
- End Property
- ''' <summary>
- ''' Fetches the <paramref name="value">specified</paramref> script source.
- ''' </summary>
- ''' <param name="name">Specifies the script name.</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' No longer trimming spaces as this caused failure to load script to the 2602.
- ''' </remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function FetchScriptSource(ByVal name As String) As Boolean Implements ITspInstrument.FetchScriptSource
- Dim synopsis As String = "Fetch Script Source"
- Me._lastFetchScriptSource = ""
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Try
- If Me.WriteLine("isr.script.list({0})", name) Then
- ' give the instrument time to get the code.
- Threading.Thread.Sleep(500)
- Me._lastFetchScriptSource = MyBase.ReadLines(10, 400, True)
- #If True Then
- ' trap non-empty buffer.
- Try
- If Me.IsMessageAvailable Then
- Debug.Assert(Not Debugger.IsAttached, "Buffer not empty")
- End If
- IsStatementTrue("node[{0}] == nil", 1)
- Catch
- Debug.Assert(Not Debugger.IsAttached, "Buffer not empty")
- End Try
- #End If
- Return Me.ReportVisaDeviceOperationOkay(True, synopsis, "Failed listing script {0}", name)
- Else
- If Me.ReportVisaDeviceOperationOkay(True, synopsis, "Failed listing script {0}", name) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Failed writing to the instrument.{0}{1}.",
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- Catch
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Failed fetching script {0}", name)
- Return False
- Finally
- End Try
- End Function
- ''' <summary>
- ''' Fetches the the <paramref name="value">specified</paramref> script source.
- ''' </summary>
- ''' <param name="name">Specifies the script name.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function FetchScriptSource(ByVal nodeNumber As Integer, ByVal name As String) As Boolean
- Dim synopsis As String = "Fetch Script Source"
- Me._lastFetchScriptSource = ""
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- ' clear data queue and report if not empty.
- Me.ClearDataQueue(nodeNumber, True)
- If Me.WriteLine("isr.script.list({0},{1})", name, nodeNumber) Then
- Try
- ' give the instrument time to get the code.
- Threading.Thread.Sleep(500)
- Me._lastFetchScriptSource = MyBase.ReadLines(10, 400, True)
- #If True Then
- ' trap non-empty buffer.
- Try
- If Me.IsMessageAvailable Then
- Debug.Assert(Not Debugger.IsAttached, "Buffer not empty")
- End If
- IsStatementTrue("node[{0}] == nil", 1)
- Catch
- Debug.Assert(Not Debugger.IsAttached, "Buffer not empty")
- End Try
- #End If
- Return Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "Failed listing script {0} from node {1}", name, nodeNumber)
- Catch
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Failed fetching script {0}", name)
- Return False
- Finally
- End Try
- Else
- If Me.ReportVisaDeviceOperationOkay(True, synopsis, "Failed fetching script {0} source from node {1}", name, nodeNumber) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Failed fetching script source from node{0}.{1}{2}", nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- End Function
- ''' <summary>
- ''' Fetches the script source.
- ''' </summary>
- ''' <param name="script">Specifies the script.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FetchScriptSource(ByVal script As IScriptEntity, ByVal node As INodeEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return FetchScriptSource(script.Name)
- Else
- Return FetchScriptSource(node.Number, script.Name)
- End If
- End Function
- Private _nilifyTimeout As Integer
- ''' <summary>
- ''' Gets or sets the time out for nilifying a script.
- ''' </summary>
- Public Property NilifyTimeout() As Integer
- Get
- Return Me._nilifyTimeout
- End Get
- Set(ByVal Value As Integer)
- Me._nilifyTimeout = Value
- End Set
- End Property
- ''' <summary>
- ''' Makes a script nil. Return true if the script is nil.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Assumes the script is known to exist.
- ''' Waits for operation completion.
- ''' </remarks>
- Private Function _nilifyScript(ByVal name As String) As Boolean
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Dim synopsis As String = "Nullifying script"
- Me.EnableWaitComplete()
- If Me.WriteLine("{0} = nil waitcomplete()", name) Then
- Me.AwaitOperationCompleted(Me._nilifyTimeout, Me._nilifyTimeout \ 10 + 10)
- If Me.IsNil(name) Then
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' script {1} still exists after nil.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed nullifying script {1}.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End Function
- ''' <summary>
- ''' Makes a script nil
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function NilifyScript(ByVal name As String) As Boolean Implements ITspInstrument.NilifyScript
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- If Me.IsNil(name) Then
- Return True
- Else
- Return Me._nilifyScript(name)
- End If
- End Function
- ''' <summary>
- ''' Runs the named script.
- ''' </summary>
- ''' <param name="name">Specifies the script name.</param>
- ''' <param name="timeout">Specifies the time to wait for the instrument to
- ''' return operation completed.</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function RunScript(ByVal name As String, ByVal timeout As Integer) As Boolean Implements ITspInstrument.RunScript
- ' Check name
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Dim returnedValue As Integer = 1
- If Me.WriteLine("{0}.run() waitcomplete() print('{1}') ", name, returnedValue) Then
- ' wait till we get a reply from the instrument or timeout.
- Dim endTime As DateTime = DateTime.Now.Add(TimeSpan.FromMilliseconds(timeout))
- Do
- Threading.Thread.Sleep(50)
- Loop Until endTime < DateTime.Now Or Me.IsMessageAvailable
- If Me.IsMessageAvailable Then
- Dim value As Integer? = Me.ReadInt32()
- Return value.HasValue AndAlso value.Value = returnedValue
- Else
- Throw New isr.Tsp.ScriptCallException("Timeout waiting operation completion running the script '" & name & "'")
- End If
- Else
- Return False
- End If
- End Function
- ''' <summary>
- ''' Runs the named script.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the subsystem node.</param>
- ''' <param name="name">Specifies the script name.</param>
- ''' <param name="timeout">Specifies the time to wait for the instrument to
- ''' return operation completed.</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function RunScript(ByVal nodeNumber As Integer, ByVal name As String, ByVal timeout As Integer) As Boolean Implements ITspInstrument.RunScript
- Dim synopsis As String = "Run Script"
- ' Check name
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- 'If Not Me.WriteLine("node[{1}].execute( 'script.user.scripts.{0}()' ) waitcomplete({1})", name, nodeNumber) Then
- If Me.ExecuteCommandWaitComplete(nodeNumber, timeout, False, "{0}.run()", name) Then
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' timed out waiting for script '{1}' on node {2}.{3}{4}",
- Me.ResourceName, name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End Function
- ''' <summary>
- ''' Runs the script.
- ''' </summary>
- ''' <param name="node">Specifies the subsystem node.</param>
- ''' <param name="script">Specifies the script.</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' Waits for operation completion.
- ''' </remarks>
- Public Function RunScript(ByVal script As IScriptEntity, ByVal node As INodeEntity) As Boolean Implements ITspInstrument.RunScript
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Run Script"
- ' Check name
- If String.IsNullOrEmpty(script.Name) Then
- Return False
- End If
- 'If Not Me.WriteLine("node[{1}].execute( 'script.user.scripts.{0}()' ) waitcomplete({1})", name, nodeNumber) Then
- If Not Me.WriteLine("node[{1}].execute( '{0}.run()' ) waitcomplete({1})", script.Name, node.Number) Then
- Return False
- End If
- Me.IssueWaitComplete(0)
- If Not Me.AwaitOperationCompleted(script.Timeout, script.Timeout \ 10 + 10) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' timed out waiting for script '{1}' on node {2}.{3}{4}",
- Me.ResourceName, script.Name, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End Function
- Private _saveTimeout As Integer
- ''' <summary>
- ''' Gets or sets the time out for saving a script.
- ''' </summary>
- Public Property SaveTimeout() As Integer
- Get
- Return Me._saveTimeout
- End Get
- Set(ByVal Value As Integer)
- Me._saveTimeout = Value
- End Set
- End Property
- ''' <summary>
- ''' Returns true if the specified script exists as a saved script.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LastSavedScriptExists(ByVal name As String) As Boolean Implements ITspInstrument.LastSavedScriptExists
- If String.IsNullOrEmpty(name) Then
- Return False
- End If
- Return Me._lastFetchedSavedScripts.IndexOf(name & ",", 0, StringComparison.OrdinalIgnoreCase) >= 0
- End Function
- ''' <summary>
- ''' Returns true if the specified script exists as a saved script.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="refreshScriptCatalog">True to refresh the list of saved scripts.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SavedScriptExists(ByVal name As String, ByVal refreshScriptCatalog As Boolean) As Boolean Implements ITspInstrument.SavedScriptExists
- If refreshScriptCatalog Then
- Me.FetchSavedScripts()
- End If
- Return LastSavedScriptExists(name)
- End Function
- #End Region
- #Region " TSP SCRIPTS: PARSE, READ, WRITE "
- ''' <summary>
- ''' Reads the scripts, parses them and saves them to file.
- ''' </summary>
- ''' <param name="filePath">Specifies the folder where scripts are stored.</param>
- ''' <param name="retainOutline">Specifies if the code outline is retained or trimmed.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ReadParseWriteScript(ByVal filePath As String, ByVal retainOutline As Boolean) As Boolean
- Dim synopsis As String = "Read, Parse, Write Script"
- Dim scriptSource As String = ""
- ' check if file exists.
- If isr.Core.IOExtensions.FileSize(filePath) < 2 Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Script file '{0}' not found.{1}{2}",
- filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- scriptSource = TspUserScript.ReadScript(filePath)
- If String.IsNullOrEmpty(scriptSource) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Script file '{0}' includes no source.{1}{2}",
- filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- scriptSource = TspUserScript.ParseScript(scriptSource, retainOutline)
- If String.IsNullOrEmpty(scriptSource) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Parse script '{0}' is empty.{1}{2}",
- filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- filePath = filePath & ".debug"
- If Not TspUserScript.WriteScript(scriptSource, filePath) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Failed writing script to '{0}'.{1}{2}",
- filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End If
- End If
- End If
- Return True
- End Function
- ''' <summary>
- ''' Reads the scripts, parses them and saves them to file.
- ''' </summary>
- ''' <param name="folderPath">Specifies the folder where scripts are stored.</param>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="retainOutline">Specifies if the code outline is retained or trimmed.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ReadParseWriteScripts(ByVal folderPath As String, ByVal scripts As ScriptEntityCollection,
- ByVal retainOutline As Boolean) As Boolean
- If folderPath Is Nothing Then
- Throw New ArgumentNullException("folderPath")
- End If
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- Dim synopsis As String = "Read, Parse, Write Scripts"
- Dim success As Boolean = True
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- For Each script As IScriptEntity In scripts
- If script.IsModelMatch(Me._controllerNode.ModelNumber) AndAlso script.RequiresReadParseWrite Then
- If String.IsNullOrEmpty(script.FileName) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "File name not specified for script '{0}'.{1}{2}",
- script.FileName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Else
- Dim filePath As String = System.IO.Path.Combine(folderPath, script.FileName)
- If Not Me.ReadParseWriteScript(filePath, retainOutline) Then
- success = False
- End If
- End If
- End If
- Next
- End If
- Return success
- End Function
- #End Region
- #Region " TSP SCRIPTS: LOAD FROM FILE "
- ''' <summary>
- ''' Loads a named script into the instrument.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="filePath">The file path.</param>
- ''' <returns><c>true</c> if success, <c>false</c> otherwise</returns>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function LoadScriptFileSimple(ByVal name As String, ByVal filePath As String) As Boolean
- Dim passed As Boolean
- Try
- Using tspFile As System.IO.StreamReader = TspUserScript.OpenScriptFile(filePath)
- passed = Not tspFile Is Nothing
- Dim isFirstLine As Boolean
- Dim line As String
- If passed Then
- isFirstLine = True
- Do While passed AndAlso Not tspFile.EndOfStream
- line = tspFile.ReadLine.Trim
- If Not String.IsNullOrEmpty(line) Then
- If isFirstLine Then
- passed = Me.WriteLine("loadscript " & name)
- isFirstLine = False
- End If
- If passed Then
- passed = Me.WriteLine(line)
- End If
- End If
- Loop
- If passed Then
- passed = Me.WriteLine("endscript")
- End If
- End If
- End Using
- Return passed
- Catch
- Throw
- Finally
- End Try
- End Function
- ''' <summary>
- ''' Loads a named script into the instrument allowing control over how
- ''' errors and prompts are handled.
- ''' For loading a script that does not includes functions, turn off errors
- ''' and turn on the prompt.
- ''' </summary>
- ''' <param name="name">Specifies the script name</param>
- ''' <param name="filePath">Specifies the script file name</param>
- ''' <param name="retainOutline">Specifies if the code outline is retained or trimmed.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function LoadScriptFileLegacy(ByVal name As String, ByVal filePath As String, ByVal retainOutline As Boolean) As Boolean
- Dim chunkLine As String
- Dim commandLine As String
- Try
- Using tspFile As System.IO.StreamReader = TspUserScript.OpenScriptFile(filePath)
- If tspFile Is Nothing Then
- ' now report the error to the calling module
- Throw New BaseException("Failed opening TSP Script File '" & filePath & "'.")
- End If
- Using debugFile As System.IO.StreamWriter = New System.IO.StreamWriter(filePath & ".debug")
- Dim deviceErrors As String = String.Empty
- Dim isInCommentBlock As Boolean
- isInCommentBlock = False
- Dim lineNumber As Integer
- lineNumber = 0
- Dim isFirstLine As Boolean
- isFirstLine = True
- Dim wasInCommentBlock As Boolean
- Dim lineType As isr.Tsp.TspChunkLineContentType
- Do While Not tspFile.EndOfStream
- chunkLine = tspFile.ReadLine()
- chunkLine = TspUserScript.TrimTspChuckLine(chunkLine, retainOutline)
- lineNumber = lineNumber + 1
- wasInCommentBlock = isInCommentBlock
- lineType = TspUserScript.ParseTspChuckLine(chunkLine, isInCommentBlock)
- If lineType = TspChunkLineContentType.None Then
- ' if no data, nothing to do.
- ElseIf wasInCommentBlock Then
- ' if was in a comment block exit the comment block if
- ' received a end of comment block
- If lineType = isr.Tsp.TspChunkLineContentType.EndCommentBlock Then
- isInCommentBlock = False
- End If
- ElseIf lineType = TspChunkLineContentType.StartCommentBlock Then
- isInCommentBlock = True
- ElseIf lineType = TspChunkLineContentType.Comment Then
- ' if comment line do nothing
- ElseIf lineType = TspChunkLineContentType.Syntax OrElse lineType = TspChunkLineContentType.SyntaxStartCommentBlock Then
- If lineType = TspChunkLineContentType.SyntaxStartCommentBlock Then
- chunkLine = chunkLine.Substring(0, chunkLine.IndexOf(TspSyntax.StartCommentChunk, StringComparison.OrdinalIgnoreCase))
- End If
- ' end each line with a space
- chunkLine &= " "
- If isFirstLine Then
- ' issue a start of script command. The command
- ' 'loadscript' identifies the beginning of the named script.
- commandLine = "loadscript " & name & " "
- If Me.WriteLine(commandLine) Then
- isFirstLine = False
- Else
- ' now report the error to the calling module
- If Me.HandleInstrumentErrorIfError(True) Then
- deviceErrors = Me.DeviceErrors
- End If
- Dim messageFormat As String = "{0} failed sending a 'loadscript' for script '{1}' from file '{2}'"
- Throw New ScriptLoadingException(messageFormat, Me.ResourceName, name, filePath, deviceErrors)
- End If
- End If
- If Me.WriteLine(chunkLine) Then
- ' increment debug line number
- debugFile.WriteLine(chunkLine)
- Else
- ' now report the error to the calling module
- If Me.HandleInstrumentErrorIfError(True) Then
- deviceErrors = Me.DeviceErrors
- End If
- Dim messageFormat As String = "{0} failed sending failed sending a syntax line: {4}{1}{4} for script '{2}' from file '{3}'"
- Throw New ScriptLoadingException(messageFormat, Me.ResourceName, chunkLine, name, filePath, deviceErrors)
- End If
- If lineType = TspChunkLineContentType.SyntaxStartCommentBlock Then
- isInCommentBlock = True
- End If
- End If
- Loop
- End Using
- End Using
- ' Tell TSP complete script has been downloaded.
- commandLine = "endscript waitcomplete() print('1') "
- ' now report the error to the calling module
- If Not Me.ReportVisaDeviceOperationOkay(Not Me.WriteLine(commandLine),
- "Failed Loading Script",
- "{0} failed sending an 'endscript' for script '{1}' from file '{2}'", Me.ResourceName, name, filePath) Then
- Return False
- End If
- ' wait till we get a reply from the instrument or timeout.
- ' The command above does not seem to work! It looks like the print does not get executed!
- Dim endTime As DateTime = DateTime.Now.Add(TimeSpan.FromMilliseconds(3000))
- Dim value As String = String.Empty
- Do
- Do
- Threading.Thread.Sleep(50)
- Loop Until endTime < DateTime.Now Or Me.IsMessageAvailable
- If Me.IsMessageAvailable Then
- value = Me.ReadLine
- End If
- Loop Until endTime < DateTime.Now Or value.StartsWith("1", StringComparison.OrdinalIgnoreCase)
- If endTime < DateTime.Now Then
- 'Throw New isr.Tsp.ScriptCallException("Timeout waiting operation completion loading the script '" & Me._name & "'")
- End If
- ' add a wait to ensure the system returns the last status.
- Threading.Thread.Sleep(100)
- ' flush the receive buffer until empty.
- Me._discardUnreadData(True)
- Return True
- Catch
- ' flush the receive buffer until empty.
- Me._discardUnreadData(True)
- Throw
- Finally
- End Try
- End Function
- ''' <summary>
- ''' Loads the specified TSP script from file.
- ''' </summary>
- ''' <param name="folderPath">Specifies the script folder path</param>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <returns>Returns True if ok.</returns>
- ''' <remarks></remarks>
- Public Function LoadUserScriptFile(ByVal folderPath As String, ByVal script As IScriptEntity) As Boolean
- If folderPath Is Nothing Then
- Throw New ArgumentNullException("folderPath")
- End If
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim synopsis As String = "Load Custom Firmware"
- If Not Me.IsNil(script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already exists.", Me.ResourceName, script.Name)
- Return True
- End If
- Dim filePath As String = System.IO.Path.Combine(folderPath, script.FileName)
- ' check if file exists.
- If isr.Core.IOExtensions.FileSize(filePath) < 2 Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Script file '{0}' not found.{1}{2}",
- filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Me.DisplayLine(2, "Loading {0} from file", script.Name)
- If Not Me.LoadScriptFileLegacy(script.Name, filePath, True) Then
- Me.DisplayLine(2, "Failed loading {0} from file", script.Name)
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "loading {0} from {1}", script.Name, filePath) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed loading {1} from {2}.{3}{4}",
- Me.ResourceName, script.Name, filePath,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- ' do a garbage collection
- Me.CollectGarbageWaitComplete(script.Timeout, synopsis, "collecting garbage. Error ignored")
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' {1} script loaded.", Me.ResourceName, script.Name)
- Me.DisplayLine(2, "Done loading {0} from file", script.Name)
- Return True
- End Function
- #End Region
- #Region " TSP SCRIPTS: LOAD "
- ''' <summary>
- ''' Load the code. Code could be embedded as a comma separated string table format, in
- ''' which case the script should be concatenated first.
- ''' </summary>
- ''' <param name="value">Includes the script as a long string.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadString(ByVal value As String) As Boolean Implements ITspInstrument.LoadString
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- End If
- Dim scriptLines As String() = value.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
- Return LoadString(scriptLines)
- End Function
- ''' <summary>
- ''' Load the code. Code could be embedded as a comma separated string table format, in
- ''' which case the script should be concatenated first.
- ''' </summary>
- ''' <param name="scriptLines">Includes the script in lines.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadString(ByVal scriptLines() As String) As Boolean Implements ITspInstrument.LoadString
- If scriptLines Is Nothing Then
- Throw New ArgumentNullException("scriptLines")
- End If
- If scriptLines IsNot Nothing Then
- For Each scriptLine As String In scriptLines
- scriptLine = scriptLine.Trim
- If Not String.IsNullOrEmpty(scriptLine) Then
- If Not Me.WriteLine(scriptLine) Then
- Return False
- End If
- End If
- Next
- End If
- Return True
- End Function
- ''' <summary>
- ''' Load the script embedded in the string.
- ''' </summary>
- ''' <param name="scriptLines">Contains the script code line by line</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadScript(ByVal name As String, ByVal scriptLines() As String) As Boolean Implements ITspInstrument.LoadScript
- If scriptLines Is Nothing Then
- Throw New ArgumentNullException("scriptLines")
- End If
- Dim synopsis As String = "Load Script"
- Try
- Dim firstLine As String = scriptLines(0)
- ' check if we already have the load/end constructs.
- If firstLine.Contains(name) OrElse firstLine.Contains("loadscript") Then
- Return Me.LoadString(scriptLines)
- Else
- If Me.WriteLine("loadscript " & name) Then
- If Me.LoadString(scriptLines) Then
- If Me.WriteLine("endscript waitcomplete()") Then
- Return Me.ReportVisaDeviceOperationOkay(True, synopsis, "loading script")
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed loading script '{1}'.{2}{3}",
- Me.ResourceName, name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- Return False
- End If
- Else
- Return False
- End If
- End If
- Catch
- Throw
- End Try
- End Function
- ''' <summary>
- ''' Load the script embedded in the string.
- ''' </summary>
- ''' <param name="name">Contains the script name</param>
- ''' <param name="source">Contains the script code line by line</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadScript(ByVal name As String, ByVal source As String) As Boolean
- If name Is Nothing Then
- Throw New ArgumentNullException("name")
- End If
- If source Is Nothing Then
- Throw New ArgumentNullException("source")
- End If
- If source.Substring(0, 50).Trim.StartsWith("{", True, Globalization.CultureInfo.CurrentCulture) Then
- source = "loadstring(table.concat(" & source & "))() "
- End If
- Dim scriptLines() As String = source.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
- Return Me.LoadScript(name, scriptLines)
- End Function
- ''' <summary>
- ''' Load an anonymous script embedded in the string.
- ''' </summary>
- ''' <param name="source">Contains the script code line by line</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadScript(ByVal source As String) As Boolean
- If source Is Nothing Then
- Throw New ArgumentNullException("source")
- End If
- If source.Substring(0, 50).Trim.StartsWith("{", True, Globalization.CultureInfo.CurrentCulture) Then
- source = "loadstring(table.concat(" & source & "))() "
- End If
- Return Me.LoadString(source)
- End Function
- #End Region
- #Region " TSP: STATUS "
- Public Overrides Property OperationEventEnable(ByVal access As Visa.ResourceAccessLevels) As Integer
- Get
- Return MyBase.OperationEventEnable(access)
- End Get
- Set(ByVal value As Integer)
- MyBase.OperationEventEnable(access) = value
- If (value And OperationEventBits.UserRegister) <> 0 Then
- ' if enabling the user register, enable all events on the user register.
- Me.WriteLine("status.operation.user.enable = {0}", &H4FFF)
- End If
- End Set
- End Property
- #End Region
- #Region " TSPX: EXTENDED FUNCTIONS WITH ERROR MANAGEMENT "
- ''' <summary>
- ''' Do garbage collection. Reports operations synopsis.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function CollectGarbageWaitComplete(ByVal timeout As Integer, ByVal synopsis As String, ByVal format As String, ByVal ParamArray args() As Object) As Boolean
- If Me.CollectGarbage() Then
- IssueWaitComplete(0)
- Me.AwaitOperationCompleted(timeout, timeout \ 10 + 10)
- Return Me.ReportVisaDeviceOperationOkay(False, synopsis, format, args)
- Else
- Me.ReportVisaDeviceOperationOkay(True, synopsis, synopsis, format, args)
- Return False
- End If
- End Function
- ''' <summary>
- ''' Do garbage collection. Reports operations synopsis.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function CollectGarbageWaitComplete(ByVal nodeNumber As Integer, ByVal timeout As Integer, ByVal synopsis As String, ByVal format As String, ByVal ParamArray args() As Object) As Boolean
- If Me.CollectGarbage(nodeNumber) Then
- IssueWaitComplete(nodeNumber)
- Me.AwaitOperationCompleted(timeout, timeout \ 10 + 10)
- Return Me.ReportDeviceOperationOkay(nodeNumber, synopsis, format, args)
- Else
- Me.ReportDeviceOperationOkay(nodeNumber, synopsis, format, args)
- Return False
- End If
- End Function
- ''' <summary>
- ''' Do garbage collection. Reports operations synopsis.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function CollectGarbageWaitComplete(ByVal node As INodeEntity, ByVal timeout As Integer, ByVal synopsis As String, ByVal format As String, ByVal ParamArray args() As Object) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return CollectGarbageWaitComplete(timeout, synopsis, format, args)
- Else
- Return CollectGarbageWaitComplete(node.Number, timeout, synopsis, format, args)
- End If
- End Function
- #End Region
- #Region " TSPX: SCRIPT COLLECTION - LEGACY "
- Private _legacyScripts As ScriptEntityCollection
- ''' <summary>
- ''' Gets the list of legacy scripts.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LegacyScripts() As ScriptEntityCollection Implements ITspInstrument.LegacyScripts
- Return Me._legacyScripts
- End Function
- ''' <summary>
- ''' Adds a new script to the list of legacy scripts.
- ''' </summary>
- ''' <param name="name"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AddLegacyScript(ByVal name As String) As IScriptEntity Implements ITspInstrument.AddLegacyScript
- Dim script As New ScriptEntity(name, "")
- Me._legacyScripts.Add(script)
- Return script
- End Function
- ''' <summary>
- ''' Create a new instance of the legacy scripts
- ''' </summary>
- ''' <remarks></remarks>
- Public Sub NewLegacyScripts() Implements ITspInstrument.NewLegacyScripts
- Me._legacyScripts = New ScriptEntityCollection
- End Sub
- #End Region
- #Region " TSPX: SCRIPT COLLECTION "
- Private _scripts As ScriptEntityCollection
- ''' <summary>
- ''' Gets the list of scripts.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function Scripts() As ScriptEntityCollection Implements ITspInstrument.Scripts
- Return Me._scripts
- End Function
- ''' <summary>
- ''' Adds a new script to the list of scripts.
- ''' </summary>
- ''' <param name="name">Specifies the name of the script</param>
- ''' <param name="modelMask">Specifies the family of instrument models for this script.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AddScript(ByVal name As String, ByVal modelMask As String) As IScriptEntity Implements ITspInstrument.AddScript
- Dim script As New ScriptEntity(name, modelMask)
- Me._scripts.Add(script)
- Return script
- End Function
- ''' <summary>
- ''' Create a new instance of the scripts
- ''' </summary>
- ''' <remarks></remarks>
- Public Sub NewScripts() Implements ITspInstrument.NewScripts
- Me._scripts = New ScriptEntityCollection()
- End Sub
- #End Region
- #Region " TSPX: SCRIPTS "
- ''' <summary>
- ''' Checks and returns true if all scripts are loaded on the specified node.
- ''' </summary>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AllUserScriptsExist(ByVal scripts As ScriptEntityCollection, ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- For Each script As IScriptEntity In scripts
- ' return false if any script is not loaded.
- If script.IsModelMatch(node.ModelNumber) AndAlso Not Me.IsNil(node, script.Name) Then
- Return False
- End If
- Next
- Else
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Checks and returns true if all scripts were executed.
- ''' </summary>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AllUserScriptsExecuted(ByVal scripts As ScriptEntityCollection, ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- For Each script As IScriptEntity In scripts
- ' return false if any script is not loaded.
- If script.IsModelMatch(node.ModelNumber) AndAlso
- script.Namespaces IsNot Nothing AndAlso script.Namespaces.Length > 0 AndAlso Me.IsNil(node, script.Namespaces) Then
- Return False
- End If
- Next
- Else
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Checks and returns true if all scripts are loaded.
- ''' </summary>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AllUserScriptsSaved(ByVal scripts As ScriptEntityCollection, ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- If Not Me.FetchSavedScripts(node) Then
- Me.OnMessageAvailable(TraceEventType.Warning, "All User Scripts Saved", "Instrument '{0}' node {1} failed fetching catalog of saved scripts.{2}{3}",
- Me.ResourceName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- For Each script As IScriptEntity In scripts
- ' return false if any script is not saved.
- If script.IsModelMatch(node.ModelNumber) AndAlso Not Me.SavedScriptExists(script.Name, node, False) Then
- Return False
- End If
- Next
- Else
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Returns true if any of the specified scripts exists.
- ''' </summary>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function AnyUserScriptExists(ByVal scripts As ScriptEntityCollection, ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- For Each script As IScriptEntity In scripts
- If Not String.IsNullOrEmpty(script.Name) Then
- If script.IsModelMatch(node.ModelNumber) AndAlso Not Me.IsNil(node, script.Name) Then
- Return True
- End If
- End If
- Next
- End If
- Return False
- End Function
- #End Region
- #Region " TSPX: SCRIPTS FIRMWARE "
- ''' <summary>
- ''' Returns the released main firmware version.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareReleasedVersionGetter() As String
- If Me._controllerNode Is Nothing Then
- Return Me._scripts.Item(0).ReleasedFirmwareVersion
- Else
- Return FirmwareReleasedVersionGetter(Me._controllerNode)
- End If
- End Function
- ''' <summary>
- ''' Returns the released main firmware version.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareReleasedVersionGetter(ByVal node As INodeEntity) As String
- If Me._controllerNode Is Nothing Then
- Return Me._scripts.Item(0).ReleasedFirmwareVersion
- Else
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return Me._scripts.SerialNumberScript(node).ReleasedFirmwareVersion
- End If
- End Function
- ''' <summary>
- ''' Returns the embedded main firmware version.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareVersionGetter(ByVal node As INodeEntity) As String
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return Me._scripts.SerialNumberScript(node).EmbeddedFirmwareVersion
- End Function
- ''' <summary>
- ''' Returns the main firmware name from the controller node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareNameGetter() As String
- Return FirmwareNameGetter(Me._controllerNode)
- End Function
- ''' <summary>
- ''' Returns the main firmware name.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareNameGetter(ByVal node As INodeEntity) As String
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return Me._scripts.SerialNumberScript(node).Name
- End Function
- Private _firmwareExists As Boolean?
- ''' <summary>
- ''' Returns the existence status of the main firmware on the controller node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareExists() As Boolean
- Return FirmwareExists(Me._controllerNode)
- End Function
- ''' <summary>
- ''' Returns the existence status of the main firmware.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function FirmwareExists(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If Me._firmwareExists Is Nothing OrElse Not Me._firmwareExists.HasValue Then
- Me._firmwareExists = Not Me.IsNil(Me.FirmwareNameGetter(node))
- End If
- Return Me._firmwareExists.Value
- End Function
- ''' <summary>
- ''' Reads and returns the local node number.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LocalNodeNumber() As Integer
- Return CInt(Me.QueryPrintFormat("%d", "_G.tsplink.node"))
- End Function
- ''' <summary>
- ''' Reads and returns the instrument serial number
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SerialNumberReading() As String
- Return Me.QueryPrintFormat("%d", "_G.localnode.serialno").Trim
- End Function
- ''' <summary>
- ''' Returns the Support firmware name.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SupportFirmwareNameGetter(ByVal node As INodeEntity) As String
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return Me._scripts.SupportScript(node).Name
- End Function
- Private _supportfirmwareExists As Boolean?
- ''' <summary>
- ''' Returns the existence status of the Support firmware on the controller node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SupportFirmwareExists() As Boolean
- Return SupportFirmwareExists(Me._controllerNode)
- End Function
- ''' <summary>
- ''' Returns the existence status of the Support firmware.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SupportFirmwareExists(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If Me._supportfirmwareExists Is Nothing OrElse Not Me._supportfirmwareExists.HasValue Then
- Me._supportfirmwareExists = Not Me.IsNil(SupportFirmwareNameGetter(node))
- End If
- Return Me._supportfirmwareExists.Value
- End Function
- ''' <summary>
- ''' Reads the firmware versions of the controller node.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function ReadFirmwareVersions(ByVal node As INodeEntity) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return Me._scripts.ReadFirmwareVersions(node, Me)
- End Function
- ''' <summary>
- ''' Returns true if all scripts were saved.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <value></value>
- ''' <param name="refreshScriptCatalog">Specifies the condition for updating the catalog of saved scripts before
- ''' checking the status of these scripts.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AllScriptsSaved(ByVal refreshScriptCatalog As Boolean, ByVal node As INodeEntity) As Boolean
- Get
- If node IsNot Nothing Then
- Return Me._scripts.FindSavedScripts(node, Me, refreshScriptCatalog)
- End If
- End Get
- End Property
- ''' <summary>
- ''' Returns true if all scripts exist.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AllScriptsExist(ByVal node As INodeEntity) As Boolean
- Get
- If node IsNot Nothing Then
- Return Me._scripts.FindScripts(node, Me)
- End If
- End Get
- End Property
- ''' <summary>
- ''' Returns true if any script exists on the controller node.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AnyScriptExists() As Boolean
- Get
- Return AnyScriptExists(Me.ControllerNode)
- End Get
- End Property
- ''' <summary>
- ''' Returns true if any script exists.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AnyScriptExists(ByVal node As INodeEntity) As Boolean
- Get
- If node IsNot Nothing Then
- Return Me._scripts.FindAnyScript(node, Me)
- End If
- End Get
- End Property
- ''' <summary>
- ''' Returns true if any legacy scripts exist on the controller node.
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AnyLegacyScriptExists() As Boolean
- Get
- Return AnyLegacyScriptExists(Me.ControllerNode)
- End Get
- End Property
- ''' <summary>
- ''' Returns true if any legacy scripts exist.
- ''' </summary>
- ''' <param name="node">Specifies the node.</param>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public ReadOnly Property AnyLegacyScriptExists(ByVal node As INodeEntity) As Boolean
- Get
- If node IsNot Nothing Then
- Return Me._legacyScripts.FindAnyScript(node, Me)
- End If
- End Get
- End Property
- #End Region
- #Region " TSPX: DELETE SCRIPTS "
- ''' <summary>
- ''' Check the script version and determines if the script needs to be deleted.
- ''' </summary>
- ''' <param name="script">Specifies the <see cref="IScriptEntity">script</see>to delete</param>
- ''' <param name="node">Specifies the system node</param>
- ''' <returns>
- ''' Returns true if script was deleted or did not exit. Returns false if a
- ''' VISA error was encountered. Assumes that the list of saved scripts is current.
- ''' </returns>
- ''' <remarks></remarks>
- Public Function IsDeleteUserScriptRequired(ByVal script As IScriptEntity,
- ByVal node As INodeEntity,
- ByVal allowDeletingNewerScripts As Boolean) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Is script deletion required"
- If Me.IsNil(node, script.Name) Then
- ' ignore error if nil
- If ReportDeviceOperationOkay(node.Number, synopsis, "looking for script '{0}'. Ignoring error.", script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis,
- "Instrument '{0}' script {1} not found on node. Nothing to do.", Me.ResourceName, script.Name, node.Number)
- End If
- ' return false, script does not exists.
- Return False
- ' check if can read version
- ElseIf Me.IsNil(node, script.Namespaces) Then
- ' reading version requires an intact namespace. A missing name space may be missing, this might
- ' indicate that referenced scripts were deleted or failed loading so this script should be deleted.
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' some namespaces '{1}' on node {2} are nil -- script '{3}' will be deleted.",
- Me.ResourceName, script.Namespaces, node.Number, script.Name)
- Return True
- ElseIf Not script.FirmwareVersionDefined(node, Me) Then
- ' reading version requires a supported version function. Delete if a firmware version function is not
- ' defined.
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' firmware version function not defined -- script '{1}' will be deleted.",
- Me.ResourceName, script.Name)
- Return True
- End If
- ' read the script firmware version
- script.ReadFirmwareVersion(node, Me)
- Dim validation As FirmwareVersionStatus = script.ValidateFirmware()
- Select Case validation
- Case FirmwareVersionStatus.None
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' '{1}' script firmware version on node {2} is irrelevant -- Script will be deleted.",
- Me.ResourceName, script.Name, node.Number)
- Return True
- Case FirmwareVersionStatus.Current
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis,
- "Instrument '{0}' script {1} on node {2} is up to date. Nothing to do.",
- Me.ResourceName, script.Name, node.Number)
- Return False
- Case FirmwareVersionStatus.Missing
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' custom firmware '{1}' version on node {2} is not known because script version function is not defined. Script will be deleted.",
- Me.ResourceName, script.Name, node.Number)
- Return True
- Case FirmwareVersionStatus.Newer
- If allowDeletingNewerScripts Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' existing custom firmware '{1}' on node {2} version '{3}' is newer than the specified version '{4}'. The scripts will be deleted to allow uploading the older script.",
- Me.ResourceName, script.Name, node.Number, script.EmbeddedFirmwareVersion, script.ReleasedFirmwareVersion)
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' existing custom firmware '{1}' on node {2} version '{3}' is newer than the specified version '{4}'. A newer version of the program is required. Script will not be deleted.",
- Me.ResourceName, script.Name, node.Number, script.EmbeddedFirmwareVersion, script.ReleasedFirmwareVersion)
- Return False
- End If
- Case FirmwareVersionStatus.Older
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' existing custom firmware '{1}' on node {2} version '{3}' is older than the specified version '{4}'. Script will be deleted.",
- Me.ResourceName, script.Name, node.Number, script.EmbeddedFirmwareVersion, script.ReleasedFirmwareVersion)
- Return True
- Case FirmwareVersionStatus.ReferenceUnknown
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "Instrument '{0}' custom firmware '{1}' released version not given. Script will not be deleted.{2}{3}",
- Me.ResourceName, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Case FirmwareVersionStatus.Unknown
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "Instrument '{0}' firmware '{1}' on node {2} version was not read. Script will be deleted.",
- Me.ResourceName, script.Name, node.Number)
- Return True
- Case Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "Instrument '{0}' encountered unhandled firmware version status {1} on node {2}. Nothing to do. Ignored.",
- Me.ResourceName, validation, node.Number)
- Return False
- End Select
- Return False
- End Function
- ''' <summary>
- ''' Returns true if delete is required on any user script.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="refreshScriptsCatalog">Refresh catalog before checking if script exists.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function IsDeleteUserScriptRequired(ByVal scripts As ScriptEntityCollection,
- ByVal node As INodeEntity,
- ByVal refreshScriptsCatalog As Boolean) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- ' true if any delete action was executed
- ' Dim scriptsDeleted As Boolean = False
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- If refreshScriptsCatalog AndAlso Not Me.FetchSavedScripts(node) Then
- Me.OnMessageAvailable(TraceEventType.Warning, "INSTRUMENT FAILED FETCHING CATALOG OF SAVED SCRIPTS",
- "Instrument '{0}' failed fetching catalog of saved scripts from node {1}.{2}{3}",
- Me.ResourceName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- ' deletion of scripts must be done in reverse order.
- For i As Integer = scripts.Count - 1 To 0 Step -1
- Dim script As IScriptEntity = scripts.Item(i)
- If script.IsModelMatch(node.ModelNumber) Then
- Try
- If Not script.IsBootScript AndAlso Me.IsDeleteUserScriptRequired(script, node, scripts.AllowDeletingNewerScripts) Then
- ' stop in design time to make sure delete is not incorrect.
- Debug.Assert(Not Debugger.IsAttached, "ARE YOU SURE?")
- Return Me.IsDeleteUserScriptRequired(script, node, scripts.AllowDeletingNewerScripts)
- End If
- Catch ex As Exception
- Me.OnMessageAvailable(TraceEventType.Error, "EXCEPTION OCCURRED TESTING IF DELETE IS REQUIRED",
- "Exception occurred testing if delete is required for firmware {0} from node {1}. Details: {2}",
- script.Name, node.Number, ex)
- End Try
- End If
- Next
- End If
- Return False
- End Function
- ''' <summary>
- ''' Returns true if delete is required on any node.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="nodes">Specifies the list of nodes on which scripts are deleted.</param>
- ''' <param name="refreshScriptsCatalog">Refresh catalog before checking if script exists.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsDeleteUserScriptRequired(ByVal scripts As ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection,
- ByVal refreshScriptsCatalog As Boolean) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear buffers before deleting.
- Me._discardUnreadData(True)
- For Each node As isr.Tsp.INodeEntity In nodes
- If Me.IsDeleteUserScriptRequired(scripts, node, refreshScriptsCatalog) Then
- Return True
- End If
- Next
- Return False
- End Function
- ''' <summary>
- ''' Deletes the user script.
- ''' </summary>
- ''' <param name="script">Specifies the <see cref="IScriptEntity">script</see>to delete</param>
- ''' <param name="node">Specifies the system node</param>
- ''' <param name="refreshScriptsCatalog">Refresh catalog before checking if script exists.</param>
- ''' <returns>
- ''' Returns true if script was deleted or did not exit.
- ''' Returns false if deletion failed.
- ''' </returns>
- ''' <remarks></remarks>
- Public Function DeleteUserScript(ByVal script As IScriptEntity,
- ByVal node As INodeEntity,
- ByVal refreshScriptsCatalog As Boolean) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Delete Custom Firmware"
- If Me.IsNil(node, script.Name) Then
- ' ignore error if nil
- If ReportDeviceOperationOkay(node.Number, synopsis, "looking for script '{0}'. Ignoring error.", script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis,
- "Instrument '{0}' script {1} not found on node. Nothing to do.", Me.ResourceName, script.Name, node.Number)
- End If
- script.IsDeleted = True
- Return True
- End If
- Me.DisplayLine(2, "Deleting {0}:{1}", node.Number, script.Name)
- If node.IsController Then
- If Me.DeleteScript(script.Name, refreshScriptsCatalog) Then
- If ReportVisaDeviceOperationOkay(False, synopsis, "deleted {0}", script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' deleted script {1} on node {2}.",
- Me.ResourceName, script.Name, node.Number)
- Else
- Return False
- End If
- Else
- If ReportVisaDeviceOperationOkay(False, synopsis, "deleting {0}", script.Name) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed deleting script {1} on node {2}.{3}{4}",
- Me.ResourceName, script.Name, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- ' do a garbage collection
- Me.CollectGarbageWaitComplete(Me.DeleteTimeout, synopsis, "collecting garbage. Ignoring error.")
- Else
- If Me.DeleteScript(node.Number, script.Name, refreshScriptsCatalog) Then
- If ReportDeviceOperationOkay(node.Number, synopsis, "deleted {0} on node {1}", script.Name, node.Number) Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' deleted {1} on node {2}.", Me.ResourceName, script.Name, node.Number)
- Else
- Return False
- End If
- Else
- If ReportDeviceOperationOkay(node.Number, synopsis, "deleting {0} on node {1}", script.Name, node.Number) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed deleting {1} on node {2}.{3}{4}",
- Me.ResourceName, script.Name, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- ' do a garbage collection
- Me.CollectGarbageWaitComplete(node.Number, Me.DeleteTimeout, synopsis, "collecting garbage on node {0}. Ignoring error.", node.Number)
- End If
- script.IsDeleted = True
- Return True
- End Function
- ''' <summary>
- ''' Deletes user scripts that are out-dated or where a deletion is set for the script.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="refreshScriptsCatalog">Refresh catalog before checking if script exists.</param>
- ''' <param name="deleteOutDatedOnly">if set to <c>true</c> deletes only if scripts is out of date.</param>
- ''' <returns><c>true</c> if success, <c>false</c> otherwise</returns>
- ''' <exception cref="System.ArgumentNullException">scripts</exception>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function DeleteUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal node As INodeEntity,
- ByVal refreshScriptsCatalog As Boolean,
- ByVal deleteOutdatedOnly As Boolean) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim success As Boolean = True
- Dim synopsis As String = "Deleting firmware"
- ' true if any delete action was executed
- Dim scriptsDeleted As Boolean = False
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- If refreshScriptsCatalog AndAlso Not Me.FetchSavedScripts(node) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "Instrument '{0}' failed fetching catalog of saved scripts from node {1}.{2}{3}",
- Me.ResourceName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- ' deletion of scripts must be done in reverse order.
- For i As Integer = scripts.Count - 1 To 0 Step -1
- Dim script As IScriptEntity = scripts.Item(i)
- If script.IsModelMatch(node.ModelNumber) Then
- Try
- If Not script.IsDeleted AndAlso (script.RequiresDeletion OrElse
- (Not deleteOutdatedOnly OrElse
- Me.IsDeleteUserScriptRequired(script, node, scripts.AllowDeletingNewerScripts))) Then
- If Me.DeleteUserScript(script, node, False) Then
- ' mark that scripts were deleted, i.e., that any script was deleted
- ' or if a script that existed no longer exists.
- scriptsDeleted = True
- Else
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' failed deleting script '{1}' from node {2}.",
- Me.ResourceName, script.Name, node.Number)
- success = False
- End If
- End If
- Catch ex As Exception
- Try
- success = success AndAlso Me.IsNil(script.Name)
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception occurred deleting firmware {0} from node {1}. Details: {2}",
- script.Name, node.Number, ex)
- Catch
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception occurred checking existence after attempting deletion of firmware {0} from node {1}. Details: {2}",
- script.Name, node.Number, ex)
- success = False
- End Try
- End Try
- End If
- Next
- End If
- If scriptsDeleted Then
- ' reset to refresh the instrument display.
- Me.ResetNode(node)
- End If
- Return success
- End Function
- ''' <summary>
- ''' Deletes user scripts from the remote instrument.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="nodes">Specifies the list of nodes on which scripts are deleted.</param>
- ''' <param name="refreshScriptsCatalog">Refresh catalog before checking if script exists.</param>
- ''' <param name="deleteOutDatedOnly">if set to <c>true</c> [delete out dated only].</param>
- ''' <returns><c>true</c> if success, <c>false</c> otherwise</returns>
- ''' <exception cref="System.ArgumentNullException">scripts</exception>
- Public Function DeleteUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection,
- ByVal refreshScriptsCatalog As Boolean,
- ByVal deleteOutdatedOnly As Boolean) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear buffers before deleting.
- Me._discardUnreadData(True)
- Dim success As Boolean = True
- For Each node As isr.Tsp.INodeEntity In nodes
- success = success And Me.DeleteUserScripts(scripts, node, refreshScriptsCatalog, deleteOutdatedOnly)
- Next
- Return success
- End Function
- #End Region
- #Region " TSPX: LOAD AND RUN SCRIPTS "
- ''' <summary>
- ''' Loads and executes the specified TSP script from file.
- ''' </summary>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns>Returns True if ok.</returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function LoadRunUserScript(ByVal script As IScriptEntity,
- ByVal node As INodeEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Load and run scripts"
- Try
- If Me.IsNil(node, script.Name) Then
- If String.IsNullOrEmpty(script.Source) AndAlso script.Source.Length > 10 Then
- Me.DisplayLine(2, "Attempted loading empty script {0}:{1}", node.Number, script.Name)
- Return False
- End If
- If node.IsController Then
- If Me.LoadUserScript(script) Then
- If Not Me.RunUserScript(script) Then
- Return False
- End If
- Else
- Return False
- End If
- Else
- If Me.LoadUserScript(node.Number, script) Then
- If Not Me.RunUserScript(node.Number, script) Then
- Return False
- End If
- Else
- Return False
- End If
- End If
- End If
- Catch ex As Exception
- Try
- If Me.IsNil(node, script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception occurred loading and running deleting firmware {0}. Details: {1}",
- script.Name, ex)
- Return False
- Else
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception ignored loading and running deleting firmware {0}. Details: {1}",
- script.Name, ex)
- End If
- Catch
- Me.OnMessageAvailable(TraceEventType.Error, synopsis, "Exception occurred reading script status after attempting loading and running deleting firmware {0}. Details: {1}",
- script.Name, ex)
- Return False
- End Try
- End Try
- Return True
- End Function
- ''' <summary>
- ''' Loads and runs the user scripts on the controller instrument.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="node">Specifies the node.</param>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function LoadRunUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- ' reset all status values so as to force a read.
- ResetLocalKnownState()
- ' true if any load and run action was executed
- Dim resetRequired As Boolean = False
- If scripts IsNot Nothing AndAlso scripts.Count > 0 Then
- For Each script As IScriptEntity In scripts
- If script.IsModelMatch(node.ModelNumber) Then
- ' reset if a new script will be loaded.
- resetRequired = resetRequired OrElse Me.IsNil(node, script.Name)
- If Not LoadRunUserScript(script, node) Then
- Return False
- End If
- End If
- Next
- End If
- If resetRequired Then
- ' reset to refresh the instrument display.
- Me.ResetNode(node)
- End If
- Return True
- End Function
- ''' <summary>
- ''' Loads and runs the user scripts on the controller instrument for the specified node.
- ''' </summary>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <param name="scripts">Specifies the collection of scripts.</param>
- ''' <param name="nodes">Specifies the nodes.</param>
- Public Function LoadRunUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear buffers before deleting.
- Me._discardUnreadData(True)
- For Each node As INodeEntity In nodes
- If Not LoadRunUserScripts(scripts, node) Then
- Return False
- End If
- Next
- Return True
- End Function
- ''' <summary>
- ''' Copies a script source.
- ''' </summary>
- ''' <param name="sourceName">The name of the source script.</param>
- ''' <param name="destinationName">The name of the destination script.</param>
- ''' <returns></returns>
- ''' <remarks>For binary scripts, the controller and remote nodes must be binary compatible.</remarks>
- Public Function CopyScript(ByVal sourceName As String, ByVal destinationName As String) As Boolean
- ' loads and runs the specified script.
- Return Me.WriteLine("{1}=script.new( {0}.source , '{1}' ) waitcomplete()", sourceName, destinationName)
- End Function
- ''' <summary>
- ''' Copies a script from the controller node to a remote node.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <param name="sourceName">The script name on the controller node.</param>
- ''' <param name="destinationName">The script name on the remote node.</param>
- ''' <returns></returns>
- ''' <remarks>For binary scripts, the controller and remote nodes must be binary compatible.</remarks>
- Public Function CopyScript(ByVal nodeNumber As Integer, ByVal sourceName As String, ByVal destinationName As String) As Boolean
- ' loads and runs the specified script.
- Dim commands As String = String.Format(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].execute('waitcomplete() {2}=script.new({1}.source,[[{2}]])') waitcomplete({0}) waitcomplete()",
- nodeNumber, sourceName, destinationName)
- Return LoadString(commands)
- End Function
- ''' <summary>
- ''' Copies script source from one script to another.
- ''' </summary>
- ''' <param name="node">Specifies a node on which to copy.</param>
- ''' <param name="sourceName">The script name on the controller node.</param>
- ''' <param name="destinationName">The script name on the remote node.</param>
- ''' <returns></returns>
- ''' <remarks>For binary scripts, the controller and remote nodes must be binary compatible.</remarks>
- Public Function CopyScript(ByVal node As INodeEntity, ByVal sourceName As String, ByVal destinationName As String) As Boolean
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- If node.IsController Then
- Return Me.CopyScript(sourceName, destinationName)
- Else
- Return Me.CopyScript(node.Number, sourceName, destinationName)
- End If
- End Function
- ''' <summary>
- ''' Loads and runs an anonymous script.
- ''' </summary>
- ''' <param name="commands">Specifies the script commands.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function LoadRunAnonymousScript(ByVal commands As String) As Boolean
- Dim prefix As String = "loadandrunscript"
- Dim suffix As String = "endscript waitcomplete()"
- Dim loadCommand As String = String.Format(Globalization.CultureInfo.CurrentCulture, "{1}{0}{2}{0}{3}",
- Environment.NewLine, prefix, commands, suffix)
- Return LoadString(loadCommand)
- End Function
- ''' <summary>
- ''' Builds a script for loading a script to the remote node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the remote node number</param>
- ''' <param name="script">Specifies the script.</param>
- ''' <param name="loadingScriptName">Specifies the name of the loading script that will be deleted after the
- ''' process is done.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Private Shared Function buildScriptLoaderScript(ByVal nodeNumber As Integer,
- ByVal script As IScriptEntity, ByVal loadingScriptName As String) As System.Text.StringBuilder
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim prefix As String = "loadstring(table.concat("
- Dim suffix As String = "))()"
- Dim binaryDecorationRequire As Boolean = script.IsBinary AndAlso Not script.Source.Contains(prefix)
- Dim loadCommands As New System.Text.StringBuilder(script.Source.Length + 512)
- loadCommands.AppendFormat("loadandrunscript {0}", loadingScriptName)
- loadCommands.AppendLine()
- loadCommands.AppendLine("do")
- loadCommands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].dataqueue.add([[", nodeNumber)
- If binaryDecorationRequire Then
- loadCommands.Append(prefix)
- End If
- loadCommands.AppendLine(script.Source)
- If binaryDecorationRequire Then
- loadCommands.AppendLine(suffix)
- End If
- loadCommands.AppendFormat(Globalization.CultureInfo.CurrentCulture, "]]) waitcomplete()", nodeNumber)
- loadCommands.AppendLine()
- loadCommands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].execute([[waitcomplete() {1}=script.new(dataqueue.next(),'{1}')]])",
- nodeNumber, script.Name)
- loadCommands.AppendLine()
- loadCommands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "waitcomplete({0})", nodeNumber)
- loadCommands.AppendLine(" waitcomplete()")
- loadCommands.AppendLine("end")
- loadCommands.AppendLine("endscript")
- Return loadCommands
- End Function
- ''' <summary>
- ''' Create a new script on the remote node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number</param>
- ''' <param name="script"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function UploadScript(ByVal nodeNumber As Integer, ByVal script As IScriptEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim synopsis As String = "Create Node Script"
- If script.IsBinary OrElse (Not Me.IsNil(script.Name) AndAlso IsBinaryScript(script.Name, Me._controllerNode)) Then
- ' clear the data queue.
- Me.ClearDataQueue(nodeNumber, False)
- Dim tempName As String = "isr_temp"
- Dim scriptLoaderScript As String = buildScriptLoaderScript(nodeNumber, script, tempName).ToString
- ' load and ran the temporary script.
- If LoadString(scriptLoaderScript) Then
- ' enable wait completion (the wait complete command is included in the loader script
- If Me.EnableWaitComplete Then
- If Me.AwaitOperationCompleted(script.Timeout, script.Timeout \ 10 + 10) Then
- If Not Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "loading script '{0}'", tempName) Then
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' timed out waiting loading script '{1}'.{2}{3}",
- Me.ResourceName, tempName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed enabling wait completion after loading script '{1}'.{2}{3}",
- Me.ResourceName, tempName,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- ElseIf Not Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "loading and running script '{0}'", tempName) Then
- Return False
- End If
- ' remove the temporary script if there.
- If Not IsNil(tempName) Then
- Me.DeleteScript(tempName, False)
- End If
- Else
- ' if scripts is already stored in the controller node in non-binary format, just
- ' copy it (upload) from the controller to the remote node.
- If Not Me.UploadScript(nodeNumber, script.Name, script.Timeout) Then
- Return False
- End If
- End If
- ' verify that the script was loaded.
- ' check if the script short name exists.
- If Me.WaitNotNil(nodeNumber, script.Name, script.Timeout) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' loaded script '{1}' to node {2}.",
- Me.ResourceName, script.Name, nodeNumber)
- Return True
- Else
- ' if script short name not found, check to see if the script long name is found.
- Dim fullName As String = "script.user.scripts." & script.Name
- If Me.WaitNotNil(nodeNumber, fullName, script.Timeout) Then
- ' in design mode, assert this as a problem.
- ' 3783. this was asserted the first time after upgrading the 3706 to firmware 1.32.a
- Debug.Assert(Not Debugger.IsAttached, "Failed setting script short name")
- ' assign the new script name
- If Me.ExecuteCommandWaitComplete(nodeNumber, Me._saveTimeout, False, "{0} = {1} waitcomplete() ", script.Name, fullName) Then
- If Me.WaitNotNil(nodeNumber, script.Name, script.Timeout) Then
- Return True
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed referencing script '{1}' using '{2}' on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, script.Name, fullName, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Else
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "uploading script '{0}'.", script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed referencing script '{1}' using name '{2}' on node {3}--new script not found on the remote node.{4}{5}",
- Me.ResourceName, fullName, script.Name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- Else
- ' if both long and short names not found, report failure.
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed uploading script '{1}' to node {2} from script '{3}'--new script not found on the remote node.{4}{5}",
- Me.ResourceName, fullName, nodeNumber, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End If
- End Function
- ''' <summary>
- ''' Uploads a script from the controller node to a remote node using the same name on the remote node.
- ''' Does not require having the ISR Support script on the controller node.
- ''' </summary>
- ''' <param name="nodeNumber"></param>
- ''' <param name="scriptName">The script name on the controller node.</param>
- ''' <returns></returns>
- ''' <remarks>For binary scripts, the controller and remote nodes must be binary compatible.</remarks>
- Public Function UploadScript(ByVal nodeNumber As Integer, ByVal scriptName As String,
- ByVal timeout As Integer) As Boolean
- If scriptName Is Nothing Then
- Throw New ArgumentNullException("scriptName")
- End If
- Dim synopsis As String = "Upload Node Script"
- ' NOTE: WAIT COMPLETE is required on the system before a wait complete is tested on the node
- ' otherwise getting error 1251.
- Dim commands As New System.Text.StringBuilder(1024)
- If Me.IsNil(Scripts.SupportScript(Me.ControllerNode).Namespaces) Then
- ' loads and runs the specified script.
- commands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].dataqueue.add({1}.source) waitcomplete()", nodeNumber, scriptName)
- commands.AppendLine()
- commands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "node[{0}].execute('waitcomplete() {1}=script.new(dataqueue.next(),[[{1}]])')",
- nodeNumber, scriptName)
- Else
- commands.AppendFormat(Globalization.CultureInfo.CurrentCulture,
- "isr.script.uploadScript(node[{0}],{1})", nodeNumber, scriptName)
- End If
- commands.AppendLine()
- commands.AppendLine("waitcomplete(0)")
- If Not LoadString(commands.ToString) Then
- Return False
- End If
- Me.IssueWaitComplete(0)
- If Me.AwaitOperationCompleted(timeout, timeout \ 10 + 10) Then
- If Not Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "timeout uploading script '{0}' to node {1}", scriptName, nodeNumber) Then
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' timed out waiting loading script '{1}' on node {2}.{3}{4}",
- Me.ResourceName, scriptName, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- Return True
- End Function
- ''' <summary>
- ''' Loads the specified script from the local to the remote node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number</param>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <returns></returns>
- ''' <remarks>Will not load a script list that includes the create script command.</remarks>
- Public Function LoadUserScript(ByVal nodeNumber As Integer, ByVal script As IScriptEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim synopsis As String = "Load Node Script"
- If Not Me.IsNil(nodeNumber, script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already exists on node {2}. Nothing to do.",
- Me.ResourceName, script.Name, nodeNumber)
- Return True
- End If
- Me.DisplayLine(2, "Uploading {0}:{1}", nodeNumber, script.Name)
- If Not Me.UploadScript(nodeNumber, script) Then
- Me.DisplayLine(2, "Failed uploading {0}:{1}", nodeNumber, script.Name)
- Return False
- End If
- Me.DisplayLine(2, "Verifying {0}:{1}", nodeNumber, script.Name)
- If Not Me.WaitNotNil(nodeNumber, script.Name, Me._saveTimeout) Then
- Me.DisplayLine(2, "{0}:{1} not found after loading", nodeNumber, script.Name)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed loading script '{1}' to node {2}--new script not found on the remote node.{3}{4}",
- Me.ResourceName, script.Name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- ' do a garbage collection
- Me.DisplayLine(2, "Cleaning local node")
- Me.CollectGarbageWaitComplete(script.Timeout, synopsis, "collecting garbage after loading script {0} on node {1}. Error ignored.", script.Name, nodeNumber)
- ' do a garbage collection
- Me.DisplayLine(2, "Cleaning node {0}", nodeNumber)
- Me.CollectGarbageWaitComplete(nodeNumber, script.Timeout, synopsis, "collecting garbage after loading script {0} on node {1}. Error ignored.", script.Name, nodeNumber)
- Me.DisplayLine(2, "{0}:{1} Loaded", nodeNumber, script.Name)
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' {1} script loaded from local node to node {2}.",
- Me.ResourceName, script.Name, nodeNumber)
- Return True
- End Function
- ''' <summary>
- ''' Loads the specified TSP script from code.
- ''' </summary>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <returns>Returns True if ok.</returns>
- ''' <remarks></remarks>
- Public Function LoadUserScript(ByVal script As IScriptEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim synopsis As String = "Load Custom Firmware"
- If Not Me.IsNil(script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already exists.", Me.ResourceName, script.Name)
- Return True
- End If
- Me.DisplayLine(2, "Loading {0}", script.Name)
- If Not Me.LoadScript(script.Name, script.Source) Then
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "loading {0}", script.Name) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed loading {1}.{2}{3}",
- Me.ResourceName, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- ' do a garbage collection
- Me.CollectGarbageWaitComplete(script.Timeout, synopsis, "collecting garbage. Error ignored")
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' {1} script loaded.", Me.ResourceName, script.Name)
- Me.DisplayLine(2, "{0} Loaded", script.Name)
- Return True
- End Function
- ''' <summary>
- ''' Executes the specified TSP script from file.
- ''' </summary>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <returns>Returns True if ok.</returns>
- ''' <remarks></remarks>
- ''' <history date="05/13/2009" by="David Hary" revision="3.0.3420.x">
- ''' Modified to run irrespective of the existence of the name spaces because
- ''' a new script can be loaded on top of existing old code and the new version number
- ''' will not materialize..
- ''' </history>
- Public Function RunUserScript(ByVal script As IScriptEntity) As Boolean
- Dim synopsis As String = "Run Custom Firmware"
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If Me.IsNil(script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed running {1} because it does not exist.{2}{3}",
- Me.ResourceName, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- #If False Then
- ' taken out to run always.
- If False AndAlso script.Namespaces IsNot Nothing AndAlso script.Namespaces.Length > 0 AndAlso Not Me.IsNil(script.Namespaces) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already run. Nothing to do.",
- Me.ResourceName, script.Name)
- Return True
- End If
- #End If
- Me.DisplayLine(2, "Running {0}", script.Name)
- If Not Me.RunScript(script.Name, script.Timeout) Then
- Me.DisplayLine(2, "Failed running {0}", script.Name)
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "running {0}", script.Name) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed running {1}.{2}{3}",
- Me.ResourceName, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- If Me.IsNil(script.Name) Then
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "script {0} not found after running from {1}", script.Name) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed running script {1}.{2}{3}",
- Me.ResourceName, script.Name,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- ElseIf script.Namespaces IsNot Nothing AndAlso script.Namespaces.Length > 0 AndAlso Me.IsNil(script.Namespaces) Then
- If Me.ReportVisaDeviceOperationOkay(False, synopsis, "some of the namespace(s) {0} are nil after running {1}", script.NamespaceList, script.Name) Then
- ' if not a visa error, report the specific namespaces.
- For Each value As String In script.Namespaces
- If Me.IsNil(value) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' namespace {1} is nil.{2}{3}",
- Me.ResourceName, value,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Next
- End If
- Return False
- Else
- Me.DisplayLine(2, "Done running {0}", script.Name)
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' {1} script run okay.", Me.ResourceName, script.Name)
- Return True
- End If
- Return True
- End Function
- ''' <summary>
- ''' Executed a loaded script on the local node.
- ''' </summary>
- ''' <param name="nodeNumber">Specifies the node number</param>
- ''' <param name="script">Specifies reference to a valid <see cref="ScriptEntity">script</see></param>
- ''' <returns></returns>
- ''' <remarks>
- ''' </remarks>
- ''' <history date="05/13/2009" by="David Hary" revision="3.0.3420.x">
- ''' Modified to run irrespective of the existence of the name spaces because
- ''' a new script can be loaded on top of existing old code and the new version number
- ''' will not materialize..
- ''' </history>
- Public Function RunUserScript(ByVal nodeNumber As Integer, ByVal script As IScriptEntity) As Boolean
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- Dim synopsis As String = "Run Node Firmware"
- If Me.IsNil(nodeNumber, script.Name) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed running {1} because it does not exist on node {2}.{3}{4}",
- Me.ResourceName, script.Name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- #If False Then
- If False AndAlso script.Namespaces IsNot Nothing AndAlso script.Namespaces.Length > 0 AndAlso Not Me.IsNil(nodeNumber, script.Namespaces) Then
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already run on node {2}. Nothing to do.",
- Me.ResourceName, script.Name, nodeNumber)
- Return True
- End If
- #End If
- Me.DisplayLine(2, "Running {0}:{1}", nodeNumber, script.Name)
- If Me.ExecuteCommandWaitComplete(nodeNumber, script.Timeout, False, "script.user.scripts.{0}()", script.Name) Then
- If Not Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "running '{0}' script on node {1}", script.Name, nodeNumber) Then
- Me.DisplayLine(2, "Failed running {0}:{1}", nodeNumber, script.Name)
- End If
- Else
- Me.DisplayLine(2, "Failed running {0}:{1}", nodeNumber, script.Name)
- If Not Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "running '{0}' script on node {1}", script.Name, nodeNumber) Then
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed running script {1} on node {2}.{3}{4}",
- Me.ResourceName, script.Name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- End If
- ' do a garbage collection
- Me.DisplayLine(2, "Waiting cleanup node {0}", nodeNumber)
- Me.CollectGarbageWaitComplete(nodeNumber, script.Timeout, synopsis, "collecting garbage after running script {0} on node {1}. Error ignored.", script.Name, nodeNumber)
- If Me.IsNil(nodeNumber, script.Name) Then
- If Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "script {0} not found after running on node {1}", script.Name, nodeNumber) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed loading script {1} to node {2}.{3}{4}",
- Me.ResourceName, script.Name, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- ElseIf script.Namespaces IsNot Nothing AndAlso script.Namespaces.Length > 0 AndAlso Me.IsNil(nodeNumber, script.Namespaces) Then
- If Me.ReportDeviceOperationOkay(nodeNumber, synopsis, "some of the namespace(s) {0} are nil after running {1} on node {2}",
- script.NamespaceList, script.Name, nodeNumber) Then
- ' if not a visa error, report the specific namespaces.
- For Each value As String In script.Namespaces
- If Me.IsNil(value) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' namespace {1} is nil on node {2}.{3}{4}",
- Me.ResourceName, value, nodeNumber,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Next
- End If
- Return False
- Else
- Me.DisplayLine(2, "Done running {0}:{1}", nodeNumber, script.Name)
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' {1} script run on node {2}.", Me.ResourceName, script.Name, nodeNumber)
- Return True
- End If
- Return True
- End Function
- #End Region
- #Region " TSPX: AUTO RUN SCRIPTS "
- ''' <summary>
- ''' Builds the commands for the auto run script.
- ''' </summary>
- ''' <param name="commands">Specifies the list of commands to add to the script.</param>
- ''' <param name="scripts">Specifies the list of scripts which to include in the run.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Shared Function BuildAutoRunScript(ByVal commands As System.Text.StringBuilder,
- ByVal scripts As ScriptEntityCollection) As String
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- Dim script As New System.Text.StringBuilder(1024)
- Dim uniqueScripts As New Collections.Specialized.ListDictionary()
- ' add code to run all scripts other than the boot script
- If scripts IsNot Nothing Then
- For Each scriptEntity As IScriptEntity In scripts
- If Not String.IsNullOrEmpty(scriptEntity.Name) Then
- If Not scriptEntity.IsBootScript Then
- If Not uniqueScripts.Contains(scriptEntity.Name) Then
- uniqueScripts.Add(scriptEntity.Name, scriptEntity)
- script.AppendFormat("{0}.run()", scriptEntity.Name)
- script.AppendLine()
- End If
- End If
- End If
- Next
- End If
- ' add the custom commands.
- If commands IsNot Nothing AndAlso commands.Length > 1 Then
- script.AppendLine(commands.ToString)
- End If
- Return script.ToString
- End Function
- #End Region
- #Region " TSPX: SAVE SCRIPTS "
- ''' <summary>
- ''' Returns true if save is required fr the specified script.
- ''' Presumes list of saved scripts was retrieved.
- ''' </summary>
- ''' <param name="scriptName">Specifies the script to save.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="isSaveAsBinary">Specifies the condition requesting saving the source as binary</param>
- ''' <param name="isBootScript">Specifies the condition indicating if this is a boot script</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsSaveRequired(ByVal scriptName As String, ByVal node As INodeEntity,
- ByVal isSaveAsBinary As Boolean, ByVal isBootScript As Boolean) As Boolean
- If scriptName Is Nothing Then
- Throw New ArgumentNullException("scriptName")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Return (isSaveAsBinary AndAlso Not Me.IsBinaryScript(scriptName, node)) OrElse
- Not Me.SavedScriptExists(scriptName, node, False) OrElse
- (isBootScript AndAlso node.BootScriptSaveRequired)
- End Function
- ''' <summary>
- ''' Saves the user script in non-volatile memory.
- ''' </summary>
- ''' <param name="scriptName">Specifies the script to save.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="isSaveAsBinary">Specifies the condition requesting saving the source as binary</param>
- ''' <param name="isBootScript">Specifies the condition indicating if this is a boot script</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SaveUserScript(ByVal scriptName As String,
- ByVal node As INodeEntity,
- ByVal isSaveAsBinary As Boolean, ByVal isBootScript As Boolean,
- ByVal timeout As Integer) As Boolean
- If scriptName Is Nothing Then
- Throw New ArgumentNullException("scriptName")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Save Custom Firmware"
- If Me.IsNil(node, scriptName) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' custom firmware {1} not saved on node {2} because it is not loaded. Error may be ignored.{3}{4}",
- Me.ResourceName, scriptName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- If IsSaveRequired(scriptName, node, isSaveAsBinary, isBootScript) Then
- If Not isBootScript Then
- ' if a script is saved, boot save is required.
- node.BootScriptSaveRequired = True
- End If
- ' do a garbage collection
- Me.DisplayLine(2, "Cleaning node {0}", node.Number)
- Me.CollectGarbageWaitComplete(node, timeout, synopsis, "collecting garbage before saving script {0} on node {1}. Error ignored.",
- scriptName, node.Number)
- Me.DisplayLine(2, "Saving {0}:{1}", node.Number, scriptName)
- If Me.SaveScript(scriptName, node, isSaveAsBinary, isBootScript) Then
- ' if saved boot script, boot script save no longer required.
- If isBootScript Then
- node.BootScriptSaveRequired = False
- End If
- Me.OnMessageAvailable(TraceEventType.Information, synopsis, "Instrument '{0}' saved script {1} on node {2}.",
- Me.ResourceName, scriptName, node.Number)
- Else
- If Me.ReportDeviceOperationOkay(node.Number, synopsis, "saving script {0} on node {1}", scriptName, node.Number) Then
- ' report failure if not an instrument or VISA error (handler returns Okay.)
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed saving script {1} on node {2}.{3}{4}",
- Me.ResourceName, scriptName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- End If
- Else
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "Instrument '{0}' script {1} already saved on node {2}",
- Me.ResourceName, scriptName, node.Number)
- End If
- Return True
- End Function
- ''' <summary>
- ''' Saves the user scripts.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of scripts to save.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SaveUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal node As INodeEntity) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Save Firmware"
- Dim success As Boolean = True
- ' true if any save action was executed
- Dim resetRequired As Boolean = False
- If Not Me.FetchSavedScripts(node) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "Instrument '{0}' failed fetching catalog of saved scripts from node {1}.{2}{3}",
- Me.ResourceName, node.Number,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- If scripts IsNot Nothing Then
- For Each script As IScriptEntity In scripts
- If script.IsModelMatch(node.ModelNumber) AndAlso Not String.IsNullOrEmpty(script.Name) Then
- If Not IsNil(node, script.Name) Then
- resetRequired = resetRequired OrElse IsSaveRequired(script.Name, node,
- ((script.FileFormat And ScriptFileFormats.Binary) <> 0),
- script.IsBootScript)
- success = success And Me.SaveUserScript(script.Name, node,
- ((script.FileFormat And ScriptFileFormats.Binary) <> 0),
- script.IsBootScript, script.Timeout)
- End If
- End If
- Next
- End If
- If resetRequired Then
- ' reset to refresh the instrument display.
- Me.ResetNode(node)
- End If
- If success Then
- Me.DisplayLine(2, "All scripts saved on node {0}", node.Number)
- Else
- Me.DisplayLine(2, "Failed saving script on node {0}", node.Number)
- End If
- Return success
- End Function
- ''' <summary>
- ''' Saves all users scripts.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="nodes">Specifies the list of nodes on which scripts are deleted.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function SaveUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear buffers before deleting.
- Me._discardUnreadData(True)
- Dim success As Boolean = True
- For Each node As isr.Tsp.INodeEntity In nodes
- success = success And SaveUserScripts(scripts, node)
- Next
- Return success
- End Function
- ''' <summary>
- ''' Updates users scripts. Deletes out-dated scripts and loads and runs new scripts as required on all nodes.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="node">Specifies the node on which scripts are updated.</param>
- ''' <param name="isSecondPass">Set true on the second pass through if first pass requires loading new scripts.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function UpdateUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal node As INodeEntity, ByVal isSecondPass As Boolean) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim synopsis As String = "Updating scripts"
- Dim prefix As String = ""
- If node.IsController Then
- prefix = String.Format(Globalization.CultureInfo.CurrentCulture, "Instrument '{0}'", Me.ResourceName)
- Else
- prefix = String.Format(Globalization.CultureInfo.CurrentCulture, "Instrument '{0}' node #{1}", Me.ResourceName, node.Number)
- End If
- ' run scripts so that we can read their version numbers. Scripts will run only if not ran, namely
- ' if there namespaces are not defined.
- If Not scripts.RunScripts(node, Me) Then
- ' report any failure.
- If isSecondPass Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "{0} failed running some firmware scripts because {1}.{2}{3}",
- prefix, scripts.OutcomeDetails,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "{0} failed running some firmware scripts because {1}. Problem ignored.",
- prefix, scripts.OutcomeDetails)
- End If
- End If
- ' read scripts versions.
- If Not scripts.ReadFirmwareVersions(node, Me) Then
- If isSecondPass Then
- ' report any failure.
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- " failed reading some firmware versions because {1}.{2}{3}",
- prefix, scripts.OutcomeDetails,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- ' report any failure.
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- " failed reading some firmware versions because {1}. Problem ignored.",
- prefix, scripts.OutcomeDetails)
- End If
- End If
- ' make sure program is up to date.
- If Not isSecondPass AndAlso scripts.IsProgramOutdated(node) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "{0} program out of date because {1}. System initialization aborted.{2}{3}",
- prefix, scripts.OutcomeDetails,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- If scripts.VersionsUnspecified(node) Then
- If isSecondPass Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "{0} failed verifying firmware version because because {1}.{2}{3}",
- prefix, scripts.OutcomeDetails,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- Else
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "{0} failed verifying firmware version because because {1}. Problem ignored.",
- prefix, scripts.OutcomeDetails)
- End If
- End If
- If scripts.AllVersionsCurrent(node) Then
- Return True
- ElseIf isSecondPass Then
- If String.IsNullOrEmpty(scripts.OutcomeDetails) Then
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "{0} failed updating scripts. Check log for details.{1}{2}",
- prefix,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis, "{0} failed updating scripts because {1}.{2}{3}",
- prefix,
- scripts.OutcomeDetails,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- End If
- Return False
- Else
- isSecondPass = True
- ' delete scripts that are out-dated or slated for deletion.
- Me.OnMessageAvailable(TraceEventType.Verbose, synopsis, "{0} deleting out-dated scripts", prefix)
- If Not Me.DeleteUserScripts(scripts, node, True, True) Then
- Me.OnMessageAvailable(TraceEventType.Information, synopsis,
- "{0} failed deleting out-dated scripts. Check log for details. Problem ignored.",
- prefix)
- End If
- If LoadRunUserScripts(scripts, node) Then
- Return Me.UpdateUserScripts(scripts, node, True)
- Else
- Me.OnMessageAvailable(TraceEventType.Warning, synopsis,
- "{0} failed loading and/or running scripts. Check log for details.{1}{2}",
- prefix,
- Environment.NewLine, isr.Core.StackTraceParser.UserCallStack(4, 8))
- Return False
- End If
- End If
- End Function
- ''' <summary>
- ''' Updates users scripts deleting, as necessary, those that are out of date.
- ''' </summary>
- ''' <param name="scripts">Specifies the list of the scripts to be deleted.</param>
- ''' <param name="nodes">Specifies the list of nodes on which scripts are deleted.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function UpdateUserScripts(ByVal scripts As ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection) As Boolean
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear buffers before deleting.
- Me._discardUnreadData(True)
- For Each node As isr.Tsp.INodeEntity In nodes
- If Not UpdateUserScripts(scripts, node, False) Then
- Return False
- End If
- Next
- Return True
- End Function
- #End Region
- #Region " TSPX: WRITE "
- ''' <summary>
- ''' Writes the script to file.
- ''' </summary>
- ''' <param name="folderPath">Specifies the script file folder</param>
- ''' <param name="script">Specifies the script.</param>
- ''' <param name="node">Specifies the node.</param>
- ''' <param name="compress">Specifies the compression condition. True to compress the source before saving.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function WriteScriptFile(ByVal folderPath As String, ByVal script As IScriptEntity,
- ByVal node As INodeEntity, ByVal compress As Boolean) As Boolean Implements ITspInstrument.WriteScriptFile
- If folderPath Is Nothing Then
- Throw New ArgumentNullException("folderPath")
- End If
- If script Is Nothing Then
- Throw New ArgumentNullException("script")
- End If
- If node Is Nothing Then
- Throw New ArgumentNullException("node")
- End If
- Dim filePath As String = String.Format(Globalization.CultureInfo.CurrentCulture, "{0}.{1}",
- script.FileName, node.ModelNumber)
- filePath = System.IO.Path.Combine(folderPath, filePath)
- Try
- Using scriptFile As System.IO.StreamWriter = New System.IO.StreamWriter(filePath)
- If scriptFile Is Nothing Then
- ' now report the error to the calling module
- Throw New BaseException("Failed opening TSP Script File '" & filePath & "'.")
- End If
- If Me.FetchScriptSource(script, node) Then
- If compress Then
- scriptFile.WriteLine("{0}{1}{2}", ScriptEntity.CompressedPrefix,
- Me.LastFetchScriptSource.Compress(),
- ScriptEntity.CompressedSuffix)
- Else
- scriptFile.WriteLine(Me.LastFetchScriptSource)
- End If
- Return True
- Else
- Return False
- End If
- End Using
- Catch
- ' clear receive buffer.
- Me._discardUnreadData(False)
- Throw
- Finally
- End Try
- End Function
- ''' <summary>
- ''' Writes the script to file.
- ''' </summary>
- ''' <param name="folderPath">Specifies the script file folder</param>
- ''' <param name="scripts">Specifies the scripts.</param>
- ''' <param name="nodes">Specifies the nodes.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")>
- Public Function WriteScriptFiles(ByVal folderPath As String,
- ByVal scripts As isr.Tsp.ScriptEntityCollection,
- ByVal nodes As isr.Tsp.NodeEntityCollection) As Boolean
- If folderPath Is Nothing Then
- Throw New ArgumentNullException("folderPath")
- End If
- If scripts Is Nothing Then
- Throw New ArgumentNullException("scripts")
- End If
- If nodes Is Nothing Then
- Throw New ArgumentNullException("nodes")
- End If
- ' clear receive buffer.
- Me._discardUnreadData(False)
- Dim success As Boolean = True
- For Each node As isr.Tsp.INodeEntity In nodes
- For Each script As isr.Tsp.IScriptEntity In scripts
- ' do not save the script if is has no file name. Future upgrade might suggest adding a file name to the boot script.
- If script.IsModelMatch(node.ModelNumber) AndAlso Not String.IsNullOrEmpty(script.FileName) AndAlso Not script.SavedToFile Then
- Me.DisplayLine(2, "Writing {0}:{1}", node.ModelNumber, script.Name)
- If Me.WriteScriptFile(folderPath, script, node, ((script.FileFormat And ScriptFileFormats.Compressed) <> 0)) Then
- script.SavedToFile = True
- success = success AndAlso True
- Else
- success = False
- End If
- End If
- Next
- Next
- Return success
- End Function
- #End Region
- #Region " TSP: SYNTAX "
- ''' <summary>
- ''' Checks the series of values and return true if any one of them is nil.
- ''' </summary>
- ''' <param name="values">Specifies a list of nil objects to check.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsNil(ByVal ParamArray values() As String) As Boolean Implements ITspInstrument.IsNil
- If values Is Nothing OrElse values.Length = 0 Then
- Throw New ArgumentNullException("values")
- Else
- For Each value As String In values
- If Not String.IsNullOrEmpty(value) Then
- If Me.IsStatementTrue("{0} == nil", value) Then
- Return True
- End If
- End If
- Next
- End If
- Return False
- End Function
- ''' <summary>
- ''' Returns true if the validation command returns true.
- ''' </summary>
- ''' <param name="format">Specifies the format statement for constructing the assertion.</param>
- ''' <param name="args">Specifies the arguments to use when formatting the assertion.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function IsStatementTrue(ByVal format As String, ByVal ParamArray args() As Object) As Boolean Implements ITspInstrument.IsStatementTrue
- If String.IsNullOrEmpty(format) Then
- Throw New ArgumentNullException("format")
- End If
- Dim outcome As Boolean? = MyBase.QueryBoolean("print({0}) waitcomplete()", String.Format(Globalization.CultureInfo.InvariantCulture, format, args))
- Return outcome.HasValue AndAlso outcome.Value
- End Function
- ''' <summary>
- ''' Sends a print command to the instrument using the specified format and arguments.
- ''' The format conforms to the 'C' query command and returns the Boolean outcome.
- ''' </summary>
- ''' <param name="format">Specifies the format statement</param>
- ''' <param name="args">Specifies the arguments to use when formatting the command.</param>
- ''' <returns></returns>
- ''' <remarks>
- ''' The format string follows the same rules as the printf family of standard C functions.
- ''' The only differences are that the options or modifiers *, l, L, n, p, and h are not
- ''' supported and that there is an extra option, q. The q option formats a string in a
- ''' form suitable to be safely read back by the Lua interpreter: the string is written
- ''' between double quotes, and all double quotes, newlines, embedded zeros, and backslashes
- ''' in the string are correctly escaped when written. For instance, the
- ''' call string.format('%q', 'a string with ''quotes'' and [BS]n new line') will produce the string:
- ''' a string with [BS]''quotes[BS]'' and [BS]new line
- ''' The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument,
- ''' whereas q and s expect a string. This function does not accept string values containing embedded zeros.
- ''' </remarks>
- Public Function QueryPrintFormat(ByVal format As String, ByVal ParamArray args() As String) As String Implements ITspInstrument.QueryPrintFormat
- If MyBase.WriteQueryLine("print(string.format('{0}',{1}))", format, isr.Tsp.TspScript.Parameterize(args)) Then
- If Me.RaiseVisaOrDeviceException("failed query " & format, args) Then
- Return MyBase.ReadLineTrimEnd()
- Else
- Return ""
- End If
- Else
- Return ""
- End If
- End Function
- #End Region
- End Class