import openpyxl
import time
from openpyxl.utils import get_column_letter
from enum import Enum
from epics import caget
from playsound import playsound, PlaysoundException  # used to play sound files to indicate when the test is done.
import sys
from errorHandler import outputError, testPrint, indentLevelInc
import globalVariables
from globalVariables import pinDict, listDict, routineDict, variableDict, maxSamples, sampleTime, \
    windows
from loopClass import Loop
from exprClass import Expr
from pinClass import PinIOType, Pin
from partClass import setAllExternalInputs
from listClass import List
from pauseForEPICSCheckClass import PauseForEPICSCheck
from variableClass import Variable

_pinsToCheck = []  # list of pins to check


def readWorksheet(s: openpyxl.workbook.workbook.Worksheet):
    """
    This routine reads all the cells it the worksheet and saves them in the 2D array rows
    :param s: a worksheet object
    :return: A 2D array: rows[iRow][iColumn] contain the contents of all the cells in the worksheet.
    """
    rows = []
    for row in s.rows:  # loop over all rows
        myRow = []
        for column in row:
            myRow.append(column.value)

        # # This while loop gets rid of all empty cells at the end of the row
        # while len(myRow) > 1 and myRow[-1] is None:
        #     myRow.pop()
        rows.append(myRow)

    return rows


def _doSet(indentLevel, item, value):
    """
    This routine sets the pin(s) to the requested value by using EPICS caput
    :param indentLevel: The number of spaces output should be indented
    :param item: The pin object to be set or a list of pins to be set
    :param value: The value to set the pin(s) to.
    :return:
    """
    if item == 'all':  # Set all bits
        setAllExternalInputs(value, indentLevel)
    else:  # item is a pin or a list of pins.
        item.setBit(value, indentLevel)


def _checkHeartbeat(indentLevel, pin: Pin, correctValue):
    """
    This routine checks for a heartbeat signal on output pin. It outputs an error if the existence of the
    heartbeat does agree with correctValue
    :param indentLevel: Amount to indent the output
    :param pin: The pin object that we are checking for a heartbeat signal
    :param correctValue: =1 if there should be a heartbeat, 0 otherwise.
    :return:
    """

    if correctValue:
        testPrint(indentLevel, f'___Check for heartbeat on pin: {pin.signalName} ({pin.PVname}).')
    else:
        testPrint(indentLevel, f'___Check for NO heartbeat on pin: {pin.signalName} ({pin.PVname}).')

    # read it out every half second for 6 seconds (i.e. read in 12 times)
    oldValue = 2
    foundTransition = 0
    for i in range(12):
        hardwareOut = caget(pin.PVname, timeout=2)
        if hardwareOut != oldValue:
            if oldValue != 2:  # We have seen a transition for 0 to 1 or vice versa
                foundTransition = 1
                break
            oldValue = hardwareOut
        time.sleep(0.5)
        windows[0].writeExamineInputs()  # display new data in the examine inputs window
        windows[0].writeExamineOutputs()  # display new data in the examine outputs window
        windows[0].update()  # Allow the GUI to update displays and check for user inputs
    #  end loop

    if foundTransition != correctValue:
        outputError(f'Looked for heartbeat on pin: {pin.signalName} ({pin.PVname}). Expected: {correctValue}, '
                    f'found: {foundTransition}.')


class Com(Enum):
    """This defines an enum used in the routine class. It contains a list of command names"""
    SUBROUTINE = 'subroutine'
    SET1 = 'set 1'
    SET0 = 'set 0'
    STOP_CHECKING = 'stop checking'
    CHECK1 = 'check 1'
    CHECK0 = 'check 0'
    CHECK_HEARTBEAT = 'check heartbeat'
    COMMENT = 'comment'
    WAIT = 'wait'
    LOOP = 'loop'
    LOOP_TABLE = 'loop table'
    LOOP_ALL_COMBINATIONS = 'loop all combinations'
    ENDLOOP = 'end loop'
    CALL = 'call'
    CHECK_EXPR = 'check expr'
    VARIABLE_SET = 'variable set'
    VARIABLE_SET_IF = 'variable set if first loop iteration'
    INSTANCE = 'instance'
    TABLE = 'table'

    # and hence have both inputs and outputs.


def _findComment(cells, iColStart: int):
    """
    This routine searches all columns in row iRow of sheet s starting column iCol for a comment.
    It returns a string with that comment. If there is now comment it returns an empty string.
    :param cells: list of cell values for the present row
    :param iColStart:
    :return: A string with the comment we found or a null string if there is no comment.
    """
    comment = ''
    for iCol in range(iColStart, len(cells)):
        if iCol < iColStart:
            pass
        value = cells[iCol]
        if value is not None:
            # The cell is not empty
            if value[0] == '#':  # it is a comment
                comment = value[1:].strip()  # get rid of the leading "#" and any leading spaces
                break
    # end loop over iCol
    return comment


class Routine:
    """This class handles routines which are a set of commands."""

    def __init__(self, s: openpyxl.workbook.workbook.Worksheet, iRowStart: int):
        """
        :param s: Excel sheet object that contains the commands for this routine
        :param iRowStart: The row of the Excel sheet which has the first line of the routine (counting starts from 0)
        """
        # Get all the worksheet data into a 2D array: rows[iRow][iColumn]
        rows = readWorksheet(s)

        self.commands = []  # Will contain a list of commands used in the routine. Each item will be a list which
        # contains a parsed version of a command.
        # The first element will be the command type expressed as an enum of type Com
        # The second element is a bool and indicates if we should pause to check the EPICS display
        # Then there is an element for each argument given in the command. The arguments are converted
        # from strings to pointers to the pin or list object that the string specified.
        # The next to last element is the contents of the cell that has a comment (starts with "#").
        # A null string is put the next to last element if no comment was given.
        # The last element is the row number on the Excel sheet that contains the command.

        self.nextRoutineRow = -1  # Flag that there are no routines following the present one
        globalVariables.loopStack = []
        self.pins = []  # list of pins and variables used by this routine (includes those any subroutines it calls)
        self.iRow = -1  # The row of the spreadsheet we are currently executing (counting from 0)

        # Note that columns as an element of the rows list are numbered from 0.
        COL_ARG1 = 2  # Column which has the first argument
        COL_COMMAND = 0  # Column which has the command
        COL_PAUSE = 1  # Column which has 'y' or 'n' indicating if we should pause for the operator to check

        # the first element is the command name and later elements the other columns of the command.
        if rows[iRowStart][COL_COMMAND] == Com.SUBROUTINE.value:
            self.name = rows[iRowStart][COL_ARG1]
            self.isSubroutine = True
        else:
            self.name = s.title  # not a subroutine, so the name of routine is the sheet name
            self.isSubroutine = False

        for iRow in range(iRowStart, len(rows)):  # loop over rows in sheet
            row = rows[iRow]
            command = [row[COL_COMMAND]]
            pause = False
            pauseString = row[COL_PAUSE]  # Get cell which says whether we should pause.
            if pauseString is not None:
                if pauseString == 'y':
                    if (command[COL_COMMAND] == Com.CHECK_EXPR.value or
                            command[COL_COMMAND] == Com.CHECK1.value or
                            command[COL_COMMAND] == Com.CHECK0.value or
                            command[COL_COMMAND] == Com.COMMENT.value):
                        pause = True
                    else:
                        outputError(f'Cell: {get_column_letter(1)}{iRow + 1}, has a "y" in it indicating '
                                    f'we should stop to let the user check the EPICS display. '
                                    f'This is only valid for "check 0," "check 1", "check expr" and '
                                    f'"comment" commands. The "y" will be ignored.')
            command.append(pause)

            commentSaved = False  # flag that we have not yet saved a comment (which is always the last
            # element of the command list
            if command[0] is None:  # the cell is blank
                # skip the blank command line
                continue

            elif command[0] == Com.SUBROUTINE.value:
                if iRow != iRowStart:  # We have come to a new routine.
                    # Save the row number of the new routine and return so a new object can be created
                    # for the new routine.
                    self.nextRoutineRow = iRow
                    break
                else:  # This is a subroutine command.  Save the arguments and comment
                    for iCol in range(COL_ARG1 + 1, len(row)):
                        value = row[iCol]
                        if value is not None:
                            # The cell is not empty
                            if value[0] == '#':  # it is a comment
                                command.append(value)
                                commentSaved = True
                                # A comment is always the last cell in a row.
                                break
                            else:  # It should be an argument to the routine
                                if value in pinDict:  # it is a pin name
                                    command.append(pinDict[value])  # save the corresponding pin object
                                elif value in listDict:  # it is a list name
                                    command.append(listDict[value])  # save the corresponding list object
                                else:  # error
                                    outputError(f'Invalid routine argument: {value},'
                                                f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                                f'Should be a pin name or a list name. Will be ignored.')
                    # end loop over iCol
                    if not commentSaved:  # Line doesn't have a comment. Save a null one.
                        command.append('')

            elif command[0] == Com.COMMENT.value:
                myText = row[COL_ARG1]
                if myText is None:  # The cell was blank, so, a blank comment line was desired.
                    myText = ''
                command.append(myText)

            elif command[0] == Com.WAIT.value:
                iCol = COL_ARG1
                value = row[iCol]
                # This should be an integer number of seconds to wait.
                if value is not None and str(value).isdigit():  # it is a valid positive number
                    # save the number of seconds to wait.
                    command.append(int(value))
                else:  # error
                    outputError(f'Invalid wait argument: {value},'
                                f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                f'Should be a positive integer number of seconds to wait. '
                                f'The wait command will be ignored.')
                    continue  # go on to next row

            elif command[0] == Com.CHECK_HEARTBEAT.value:
                # This takes 2 arguments: The output pin which has the heartbeat signal we are checking, and
                # and a correct value where 1 means it is pulsing and 0 means it is not.
                iCol = COL_ARG1
                value = row[iCol]
                pin = None
                if value in pinDict:  # it is a pin name
                    pin = pinDict[value]  # save the corresponding pin object
                if pin is None:  # error
                    outputError(f'Invalid argument to {command[0]} command: {value},'
                                f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                f'Should be a pin name . Command will be ignored.')
                    continue

                if pin.pinIOType != PinIOType.OUTPUT:
                    outputError(f'The "Check heartbeat" command in row: {iRow + 1}, tries to check an input: {value}. '
                                f'You can only check an output. Command will be ignored.')
                    continue
                command.append(pin)
                iCol += 1  # go on to the second argument which should be 0 or a 1
                value = str(row[iCol])
                if value == '0':
                    correctAnswer = 0
                elif value == '1':
                    correctAnswer = 1
                else:
                    outputError(f'Invalid argument to {command[0]} command: {value},'
                                f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                f'Should be "0" or "1". Command will be ignored.')
                    continue
                command.append(correctAnswer)
                command.append(_findComment(row, iCol + 1))
                self._addToPins(pin)  # Add these pins to the list of all pins used by this routine

            elif (command[0] == Com.SET0.value or
                  command[0] == Com.SET1.value or
                  command[0] == Com.CHECK0.value or
                  command[0] == Com.CHECK1.value or
                  command[0] == Com.STOP_CHECKING.value):
                # These all take 1 argument which can be a pin or list name.
                iCol = COL_ARG1
                pinOrList = None
                argIsAll = False
                value = row[iCol]
                if value in pinDict:  # it is a pin name
                    pinOrList = pinDict[value]  # save the corresponding pin object
                elif value in listDict:  # it is a list name
                    pinOrList = listDict[value]  # save the corresponding list object
                elif value in variableDict:  # it is a list name
                    pinOrList = variableDict[value]  # save the corresponding list object
                elif value == 'all' and (command[0] == Com.SET0.value or command[0] == Com.SET1.value):
                    # 'all' is a special case which means to set all input bits.
                    argIsAll = True
                for loopLevel in globalVariables.loopStack:  # loop over all levels of loop we may be in
                    # When list is created as part of the loop command, it has suffix to make the name unique.
                    # Check for that first.
                    outName = value + loopLevel.loopID
                    if outName in listDict:
                        pinOrList = listDict[outName]
                if pinOrList is None and not argIsAll:  # error
                    outputError(f'Invalid argument to {command[0]} command: {value},'
                                f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                f'Should be a pin name or a list name or a variable name. Command will be ignored.')
                    continue

                if pinOrList is not None and value not in variableDict:
                    # Require set command to have an input pin or list as an argument and check command
                    # to have output
                    if command[0] == Com.SET0.value or command[0] == Com.SET1.value:
                        if pinOrList.pinIOType == PinIOType.OUTPUT:
                            outputError(f'The "Set" command in row: {iRow + 1}, tries to set an output: {value}. '
                                        f'You can only set an input. Command will be ignored.')
                            continue
                    else:  # It is a "check" command
                        if pinOrList.pinIOType == PinIOType.INPUT:
                            outputError(f'The "Check" command in row: {iRow + 1}, tries to check an input: {value}. '
                                        f'You can only check an output. Command will be ignored.')
                            continue
                if argIsAll:
                    pinOrList = 'all'
                command.append(pinOrList)
                command.append(_findComment(row, iCol + 1))
                self._addToPins(pinOrList)  # Add these pins to the list of all pins used by this routine

            elif command[0] == Com.LOOP_TABLE.value or command[0] == Com.LOOP_ALL_COMBINATIONS.value or \
                    command[0] == Com.LOOP.value:
                newLoop = Loop(rows, iRow, len(self.commands), s.title)
                if newLoop.successfulInit:
                    command.append(newLoop)
                    globalVariables.loopStack.append(newLoop)
                    # Save all pins used in this loop
                    for myList in newLoop.lists:  # loop over all lists used in the loop
                        self._addToPins(myList)  # Add the pins in this list to the list of all pins used
                        # by this routine
                else:
                    continue  # There was a problem, so this command should not be saved.

            elif command[0] == 'instance' or command[0] == 'table':
                # These will have been handled by the Loop class, so ignore them here.
                continue

            elif command[0] == Com.CHECK_EXPR.value or command[0] == Com.VARIABLE_SET.value or \
                    command[0] == Com.VARIABLE_SET_IF.value:
                try:
                    myExpr = Expr(row, iRow)
                    command.append(myExpr)
                    # save all the pins, lists and variables used by the expression.
                    self._addToPins(myExpr.outObject)
                    for pinOrList in myExpr.inObjects:
                        self._addToPins(pinOrList)
                except SyntaxError:
                    continue  # bad command syntax, so it will not be saved.

            elif command[0] == Com.CALL.value:
                # The first argument should be a subroutine name.
                value = row[COL_ARG1]
                if value in routineDict:
                    myRoutine = routineDict[value]
                    command.append(myRoutine)
                    # save all pins used in this routine
                    for myPin in myRoutine.pins:
                        self._addToPins(myPin)
                else:
                    outputError(f'Call to non-existent subroutine: {value}, in row: {iRow + 1}. '
                                f'Command will be ignored')
                    continue
                for iCol in range(COL_ARG1 + 1, len(row)):
                    value = row[iCol]
                    if value is not None:
                        # The cell is not empty
                        if value[0] == '#':  # it is a comment
                            command.append(value)
                            commentSaved = True
                            # A comment is always the last cell in a row.
                            break
                        else:  # It should be a list to be looped over or a pin
                            if value in pinDict:  # it is a pin name
                                command.append(pinDict[value])  # save the corresponding pin object
                            elif value in listDict:  # it is a list name
                                command.append(listDict[value])  # save the corresponding list object
                            else:
                                outputError(f'Invalid subroutine argument: {value},'
                                            f' in cell: {get_column_letter(iCol + 1)}{iRow + 1}. '
                                            f'Should be a list or pin name. Line will be ignored.')
                    # end loop over iCol

                if not commentSaved:  # Line doesn't have a comment. Save a null one.
                    command.append('')

            elif command[0] == Com.ENDLOOP.value:  # this is an end loop command
                if len(globalVariables.loopStack) <= 0:
                    outputError(f'Row: {iRow + 1}, has an "end loop" command without a preceding "loop" command. '
                                f'Command will be ignored.')
                    continue
                else:  # valid end loop command
                    loopObject = globalVariables.loopStack.pop()
                    loopObject._iLastCommandIndex = iRow
                    command.append(loopObject)  # Save the loop object this end loop
                    # is associated with.
                    command.append(_findComment(row, COL_ARG1 + 1))

            else:  # invalid
                outputError(f'Row: {iRow + 1}, has an invalid command: {command[0]}. '
                            f'Command will be ignored.')
                continue

            command.append(iRow)  # Save the Excel row number that contains the command.
            # save the command to the list of commands
            self.commands.append(command)
        # end loop over iRow

        # We have reached the end of a routine. Check to make sure we haven't had a loop without an end loop.
        if len(globalVariables.loopStack) != 0:
            outputError(f'The routine starting in row: {iRowStart + 1}, has {len(globalVariables.loopStack)}'
                        f' more "loop" commands '
                        f'than "end loop" commands. '
                        f'This is likely a major error. We will put the missing "end loops" at the '
                        f'end of the routine')
            for i in range(1, len(globalVariables.loopStack)):
                self.commands.append([Com.ENDLOOP.value])

    def _addToPins(self, pinOrList):
        """
        This routine adds adds pins or variables to the pins: the list of pins used by the routine
        :param pinOrList: Either a pin object or a list (of pins) object that will be added to pins
        :return:
        """
        if isinstance(pinOrList, List):
            # add all pins in this list to pins
            for pin in pinOrList.pinList:
                if pin not in self.pins:
                    self.pins.append(pin)
                    pin.used = True
        else:  # it is a pin  or variable object
            if pinOrList not in self.pins and pinOrList != 'all':
                self.pins.append(pinOrList)
                pinOrList.used = True

    def run(self, indentLevel: int = 0):
        """
        This routine actually runs the routine
        :type indentLevel: int: Number of spaces to indent stuff which gets printed
        :return:
        """
        COL_ARG1 = 2  # Column which has the first argument
        COL_COMMAND = 0  # Column which has the command
        COL_PAUSE = 1  # Column which has 'y' or 'n' indicating if we should pause for the operator to check

        if self.isSubroutine:
            testPrint(indentLevel, f'Doing: {self.name}, by doing the following:')
        else:
            testPrint(indentLevel, f'Running test: {self.name}', True)
            windows[0].root.title(f'Running test: {windows[0].testNameBeingRun}')
            # flag that none of the signals we will check in this routine have known correct values yet
            for pin in self.pins:
                pin.presentValue = 2

        indentLevel += indentLevelInc
        self.iRow = 0  # The routine row number we are currently executing.

        # Loop until we get to the last command line
        while self.iRow < len(self.commands) and not globalVariables.abortTest:
            commandLine = self.commands[self.iRow]
            command = commandLine[COL_COMMAND]
            arg1 = commandLine[COL_ARG1]
            comment = commandLine[-2]
            pause = commandLine[COL_PAUSE]

            if command == Com.SET1.value or command == Com.SET0.value:
                # Before we do a SET command which could result in outputs changing, do any checks which have
                # been deferred (so they could all be done at once.
                self._doDeferredChecks()

            if command == Com.COMMENT.value:
                testPrint(indentLevel, arg1, True)  # The last argument makes the output in a bold font.
                if pause and globalVariables.pauseForEPICSCheck:
                    PauseForEPICSCheck(None, comment)  # prompt user to check EPICS display

            elif command == Com.SUBROUTINE.value:
                pass

            elif command == Com.SET0.value:
                _doSet(indentLevel, arg1, 0)

            elif command == Com.SET1.value:
                _doSet(indentLevel, arg1, 1)

            elif command == Com.CHECK0.value:
                self._doPlanCheck(indentLevel, arg1, 0, pause, comment)

            elif command == Com.CHECK1.value:
                self._doPlanCheck(indentLevel, arg1, 1, pause, comment)

            elif command == Com.STOP_CHECKING.value:
                # A value of 2 means uninitialized which means the signal will be read out, but not checked.
                self._doPlanCheck(indentLevel, arg1, 2, pause, comment)

            elif command == Com.CHECK_HEARTBEAT.value:
                arg2 = commandLine[COL_ARG1 + 1]
                _checkHeartbeat(indentLevel, arg1, arg2)

            elif command == Com.CALL.value:
                arg1.run(indentLevel)

            elif command == Com.WAIT.value:
                testPrint(indentLevel, f'____Wait for {arg1} seconds')
                if globalVariables.haveRealHardware:
                    # no need to waste time sleeping if we don't have real hardware and are just checking that
                    # out tests do what we intend them to do.
                    self._doDeferredChecks()  # check outputs before the sleep
                    # Keep the GUI active by sleeping for short periods and then checking for GUI activity.
                    myTime = time.time()
                    wakeupTime = globalVariables.timeOfLastWaitOrCaput / 1000. + arg1  # time to wake up in seconds
                    if 110 < arg1 < 130:  # It is about a 2 minute wait. Probably testing the
                        # imminent beam warning message. So play a message just for the fun of it.
                        try:
                            playsound(globalVariables.pathToPythonApp + '\\soundFiles\\play_tape.mp3', False)
                        except PlaysoundException:
                            pass  # If sound file not found, just continue on without playing it.
                        except NotImplementedError:
                            pass  # Not implemented for this version or configuration of Linux
                    timeLeft = wakeupTime - myTime  # remaining time to wait
                    globalVariables.waiting = True  # flag we are waiting so writeExamineOutputs will read outputs
                    # before it updates the display of outputs
                    while timeLeft > 0:
                        if timeLeft > 4:  # we have time to update displays
                            windows[0].writeExamineOutputs()  # display new data in the examine outputs window
                        windows[0].update()  # allow GUI to update
                        if globalVariables.abortTest:  # User has requested the run be aborted
                            raise SystemExit
                        timeLeft = wakeupTime - time.time()  # remaining time to wait
                        if timeLeft > 0:
                            time.sleep(min(timeLeft, .2))
                            timeLeft = wakeupTime - time.time()
                    # end while
                    globalVariables.waiting = False
                    myTime = int(time.time() * 1000)  # Time in ms
                    globalVariables.timeOfLastWaitOrCaput = myTime

            elif command == Com.LOOP_ALL_COMBINATIONS.value or \
                    command == Com.LOOP_TABLE.value or \
                    command == Com.LOOP.value:  # it is the beginning of a loop
                self._doDeferredChecks()  # The loop command will set the pins it is loop over, so do checks first
                self.iRow = arg1.start_loop(indentLevel, self.iRow)
                # Note that iRow is set to the command after the end of the loop if the list the loop is looping
                # over has zero length. Otherwise it is left unchanged.
                indentLevel += indentLevelInc

            elif command == Com.ENDLOOP.value:
                self._doDeferredChecks()  # The endloop command will set the pins it is looping over,
                # so do checks first
                iRowSave = self.iRow
                self.iRow = arg1.end_loop(indentLevel - indentLevelInc, self.iRow)
                # Note that iRow is left unchanged if we are done executing the loop, or set to the beginning
                # of the loop to make us execute the loop contents again.
                if iRowSave == self.iRow:  # Done iterating through the loop
                    indentLevel -= indentLevelInc

            elif command == Com.VARIABLE_SET.value or \
                    command == Com.VARIABLE_SET_IF.value or \
                    command == Com.CHECK_EXPR.value:
                exprValue = arg1.evaluate(indentLevel)
                if exprValue is not None:  # It was a CHECK_EXPR command
                    # Do the check.
                    self._doPlanCheck(indentLevel, arg1.outObject, exprValue, pause, comment)

            else:
                outputError(f'Bug---Command: {command}, has not been implemented yet.')
            # end if command...

            self.iRow += 1  # go on to the next command line
        # end while loop

        if globalVariables.abortTest:
            self._doDeferredChecks()
            raise SystemExit  # User clicked the abort test button.

        # Do any checks that have have been requested, but not done yet.
        self._doDeferredChecks()

    def _doPlanCheck(self, indentLevel, item, value, pauseCommanded: bool, comment: str):
        """
        This routine saves the correct value for a bit and remembers that we want to read in the bit and check
        that it is correct later. We record this rather than immediately checking the bit so we can check
        all desired bits at once.
        :param indentLevel: The number of spaces output should be indented
        :param item: The pin object to be checked or a list of pins to be checked
        :param value: The correct value the pin should read..
        :param pauseCommanded: bool: True if we should pause and prompt the user to check the EPICS display
        :param comment: str: The comment that was given on the command line
        :return:
        """
        if isinstance(item, List):  # item is a list of pins
            if item.loopIndex >= 0:  # A loop is iterating through this list.
                if item.loopIndex < len(item.pinList):
                    # Just check the current pin in the list.
                    item = item.pinList[item.loopIndex]
                    item.presentValue = value  # Save the correct value
                    testPrint(indentLevel, f'____Check that output: {item.signalName}, is {value}'
                                           f' on part: {item.parent.partName}')
                    if value != 2:  # Don't bother adding it to the list if we are flagging that is shouldn't be checked
                        _pinsToCheck.append(item)  # add it to the list of pins to check.
                    if pauseCommanded and globalVariables.pauseForEPICSCheck:
                        item.pauseCommanded = True  # Flag so when we actually do the checks we will pause for the
                        item.pauseComment = comment  # user to check the EPICS displays
            else:
                testPrint(indentLevel, f'Checking list: {item.name}, is: {value}, by doing the following:')
                indentLevel += indentLevelInc
                for pin in item.pinList:
                    if globalVariables.abortTest:  # User clicked the "abort test" button
                        raise SystemExit
                    myPauseCommanded = pauseCommanded
                    if hasattr(pin, 'PVchan'):  # This pin is a physical output pin since it has PVchan to allow
                        # it to read by a Beckhoff
                        # There is no need to pause and check the EPICS display for physical output bits as only
                        # the virtual output bits make there way up to EPICS.
                        myPauseCommanded = False
                    self._doPlanCheck(indentLevel, pin, value, myPauseCommanded, comment)  # call ourself recursively
        elif isinstance(item, Variable):  # the item is a variable
            # Just check it now
            if item.presentValue != value:
                outputError(f'Error. Variable: {item.name}, should be {value} and is {item.presentValue}')
        else:  # item is a single pin
            item.presentValue = value  # Save the correct value
            testPrint(indentLevel, f'____Check that output: {item.signalName}, is {value}'
                                   f' on part: {item.parent.partName}')
            if value != 2:  # Don't bother adding it to the list if we are flagging that is shouldn't be checked
                _pinsToCheck.append(item)  # add it to the list of pins to check.
            if pauseCommanded and globalVariables.pauseForEPICSCheck:
                item.pauseCommanded = True  # Flag so when we actually do the checks we will pause for the
                item.pauseComment = comment  # user to check the EPICS displays

    @staticmethod
    def _doDeferredChecks():
        """
        This routine reads and checks all outputs ever checked by this routine object.
        This is done so they can all be seen
        on the display of outputs.
        It used to read all the above and only check the output pin(s) listed in _pinsToCheck are equal to
        their desired values.
        It outputs errors if an output is not at its desired value.
        :return:
        """
        allCorrect = True
        if globalVariables.mainRoutineRunning is None:
            outputError(f'Bug---Routine _doDeferredChecks called when globalVariables.mainRoutineRunning was None. '
                        f'This should never happen. Please inform author of ppsTest.')
            return
        else:
            myPins = globalVariables.mainRoutineRunning.pins

        if globalVariables.haveRealHardware and len(_pinsToCheck) != 0:
            # Set buffer to 2 to flag as uninitialized.
            globalVariables.readTime = [[2 for _ in range(maxSamples)] for _ in range(len(myPins) + 1)]
            globalVariables.readValue = [[2 for _ in range(maxSamples)] for _ in range(len(myPins) + 1)]
            myTime = int(time.time() * 1000)  # Time in ms
            timeSinceLastCaput = myTime - globalVariables.timeOfLastCaput
            timeDiff = globalVariables.calcTimePLC - float(timeSinceLastCaput)/1000.
            if timeDiff > 0:  # Wait more time to let recently changed inputs propagate through EPICS and the PLC.
                time.sleep(timeDiff)  # give the PLC time to update its outputs

            # check the real hardware for all the outputs listed in _pinToCheck
            hasBeenCorrect = [False] * len(myPins)
            cagetProblem = False

            for i in range(maxSamples):  # loop until all the outputs have been correct or 2 second.
                allCorrect = True

                for iPin, pin in enumerate(myPins):
                    # We will record all outputs, even if we are only checking a single output.
                    if isinstance(pin, Variable) or pin.pinIOType != PinIOType.OUTPUT:
                        # Don't deal with variables or input pins.
                        continue
                    correctValue = pin.presentValue
                    if i == 0 and correctValue != 2:
                        globalVariables.totalChecks += 1
                    hardwareOut = caget(pin.PVname, timeout=2)
                    sevr = caget(pin.PVsevr, timeout=2, as_string=True)
                    if hardwareOut is None:
                        # The operation timed out.
                        outputError(f'caget timed out reading signal: {pin.signalName}. '
                                    f'Is soft IOC running? Does the PV {pin.PVname} exist?')
                        hardwareOut = 'readError'
                        cagetProblem = True
                    elif sevr == 'INVALID':
                        outputError(f'caget returned a bad SEVR: {sevr}, reading signal: {pin.signalName} ({pin.PVname}). '
                                    f'Check PLC power and network connection.')
                        hardwareOut = sevr
                        cagetProblem = True
                    # We store the iteration number and current value in a list each
                    # time the actualValue changes. This will be used for the
                    # examineLogicBlock display
                    myTime = int(time.time() * 1000)
                    globalVariables.readTime[iPin][i] = myTime
                    globalVariables.readValue[iPin][i] = hardwareOut
                    if hardwareOut == correctValue:
                        hasBeenCorrect[iPin] = True
                    # if not hasBeenCorrect[iPin] and pin in _pinsToCheck:  # check only those pins which had
                    # explicit check commands.
                    if not hasBeenCorrect[iPin] and pin.presentValue != 2:
                        allCorrect = False
                # end loop over pins

                if allCorrect or cagetProblem:
                    globalVariables.nSamples = i  # save the number of readings we have recorded.
                    break
                time.sleep(sampleTime / 1000.)  # sleep to give time for PLC to finish processing and PVs to update
                windows[0].update()  # Allow the GUI to update displays and check for user inputs
            # end loop waiting until all the outputs are correct

            if not (allCorrect or cagetProblem):
                globalVariables.nSamples = maxSamples - 1  # save the number of readings we have recorded.

            if not allCorrect:
                # there are still incorrect outputs. Loop, checking 1 last time and report the errors.
                for iPin, pin in enumerate(myPins):
                    if isinstance(pin, Variable) or pin.pinIOType != PinIOType.OUTPUT:
                        # Don't deal with variables or input pins.
                        continue
                    # if not hasBeenCorrect[iPin] and pin in _pinsToCheck:
                    if not hasBeenCorrect[iPin] and pin.presentValue != 2:
                        outputError(f'Error. Output: {pin.signalName} ({pin.PVname}), should be {pin.presentValue}'
                                    f', but is actually '
                                    f'{globalVariables.readValue[iPin][globalVariables.nSamples]}.')
                if globalVariables.breakOnError:  # User has requested to break on error
                    testPrint(0, 'Breaking due to error')
                    globalVariables.brokeOnError = True
                    _pinsToCheck.clear()  # We have checked these pins, so clear the list of pins to check.
                    windows[0].writeExamineInputs()  # display new data in the examine inputs window
                    windows[0].writeExamineOutputs()  # display new data in the examine outputs window
                    raise SystemExit
            windows[0].writeExamineInputs()  # display new data in the examine inputs window
            windows[0].writeExamineOutputs()  # display new data in the examine outputs window

            for iPin, pin in enumerate(myPins):
                if isinstance(pin, Variable) or pin.pinIOType != PinIOType.OUTPUT:
                    # Don't deal with variables or input pins.
                    continue
                # If requested, pause so the user can check the EPICS display
                if pin.pauseCommanded:
                    PauseForEPICSCheck(pin, pin.pauseComment)  # prompt user to check EPICS display
                    pin.pauseCommanded = False
                    pin.pauseComment = ''
                if globalVariables.abortTest:  # User clicked the "abort test" button
                    _pinsToCheck.clear()  # We have checked these pins, so clear the list of pins to check.
                    raise SystemExit
        # end if globalVariables.haveRealHardware and len(_pinsToCheck) != 0:

        _pinsToCheck.clear()  # We have checked these pins, so clear the list of pins to check.
        return allCorrect
