def exec_command(self, msg: tuple) -> bool:
     """
     Executes command using message and arguments passed through the parameter
     :param msg: Tuple containing command and arguments
     :return: True if command was successfully executed
     """
     command, args = parse_command(msg)
     try:
         if command == "EXIT":
             self.exit()
             return True
         elif command == "DEBUG_DOT_SCREEN":
             self.debug_draw_dot(args[0], args[1], args[2])
             return True
         elif command == "DEBUG_TIME":
             graph_sent_time = args[0]
             game_sent_time = args[1]
             round_trip = round(time() - graph_sent_time, 4)
             graph_to_game = round(game_sent_time - graph_sent_time, 4)
             game_to_graph = round(time() - game_sent_time, 4)
             debug_out(
                 "Round trip: {}s, Graph->Game: {}s, Game->Graph: {}s".
                 format(round_trip, graph_to_game, game_to_graph))
             return True
     except IndexError:
         debug_out(
             "ERROR - Not enough arguments for the following command: " +
             "\nCommand: {}".format(command) + "\n{}".format(str(args)))
     return False
Beispiel #2
0
 def exit(self) -> None:
     """
     Called when node is supposed to exit
     :return: True if this node successfully exits
     """
     debug_out("Physics handler exiting...")
     self.__graphics_io_commands.append(("EXIT", None))
     self.__continue_to_update = False
 def exit(self) -> bool:
     """
     Called when node is supposed to exit
     :return: True if this node successfully exits
     """
     debug_out("Graphics-input handler exiting...")
     self.__game_commands.append(("EXIT", None))
     self.process_commands()
     self.close()
     return True
Beispiel #4
0
def phys_loop(objects_in: Queue, objects_out: Queue) -> None:
    """
    Receives updates from the game loop and modifies the physical status of objects in game
    Updates the physical properties of an object (force to velocity, velocity to position, etc)

    :param objects_in: Inputs updates to physical properties of objects
    :param objects_out: Outputs updates to graphics loop to be drawn
    :return:
    """
    debug_out("Initiating physics loop...")

    physics_handler = physics.PhysicsHandler(objects_in, objects_out)
    physics_handler.run()
Beispiel #5
0
def game_loop(objects_out: Queue, stats_out: Queue, user_in: Queue) -> None:
    """
    Reads user input and updates game statistics and object statuses

    :param objects_out: Outputs physical updates to this queue
    :param stats_out: Outputs information updates to this queue (stats)
    :param user_in: Receives user input to modify game
    :return:
    """
    debug_out("Initiating game loop...")

    game_instance = game.GameInstance(user_in, stats_out, objects_out)
    game_instance.run()
Beispiel #6
0
 def exec_command(self, msg: tuple) -> bool:
     """
     Executes command using message and arguments passed through the parameter
     :param msg: Tuple containing command and arguments
     :return: True if command was successfully executed
     """
     command, args = parse_command(msg)
     try:
         if command == "EXIT":
             self.exit()
             return True
     except IndexError:
         debug_out("ERROR - Not enough arguments for the following command: "
                   + "\nCommand: {}".format(command)
                   + "\n{}".format(str(args)))
     return False
Beispiel #7
0
def graphics_input_loop(phys_in: Queue, stats_in: Queue,
                        user_out: Queue) -> None:
    """
    Receives updates from physics loop and game loop
    Tracks user input and outputs back to game loop

    :param phys_in: Receives objects with positions to draw
    :param stats_in: Receives information to display on screen
    :param user_out: Outputs tracked user input
    :return:
    """
    debug_out("Initiating graphics loop...")

    graphics_input_handler = graphics_input.GraphicsInputHandler(
        phys_in, stats_in, user_out)
    graphics_input_handler.run()
Beispiel #8
0
 def exec_command(self, msg: tuple) -> bool:
     """
     Executes command using message and arguments passed through the parameter
     :param msg: Tuple containing command and arguments
     :return: True if command was successfully executed
     """
     command, args = parse_command(msg)
     try:
         if command == "EXIT":
             self.exit()
             return True
         elif command == 'USER_KEY_PRESS':
             self.process_key_input(args[0], args[1])
             self.stats_cmd("DEBUG_TIME", [args[2], get_time()])
             return True
     except IndexError:
         debug_out(
             "ERROR - Not enough arguments for the following command: " +
             "\nCommand: {}".format(command) + "\n{}".format(str(args)))
     return False
Beispiel #9
0
 def update_options(self, *args):
     self.typeListInput.set(self.dict[self.testListInput.get()][0])
     self.enclosureListInput.set(self.dict1[self.testListInput.get()][0])
     #                           self.dict#['NEW STRING'] -> default param in menu
     change_menu = self.typeMenu["menu"]
     change_menu1 = self.enclosureMenu["menu"]
     #
     change_menu.delete(0, "end")
     change_menu1.delete(0, "end")
     #
     for string in self.dict[self.testListInput.get()]:
         change_menu.add_command(
             label=string,
             command=lambda value=string: self.typeListInput.set(value))
     for string in self.dict1[self.testListInput.get()]:
         change_menu1.add_command(label=string,
                                  command=lambda value=string: self.
                                  enclosureListInput.set(value))
     #
     d.debug_out(self.dict[self.testListInput.get()])
     d.debug_out(self.dict1[self.testListInput.get()])
Beispiel #10
0
def rename_file(appendedFileName,test_name,datatype,importFileName,fileExtensionDEFAULT='.txt'):
    newFileName = appendedFileName.replace(fileExtensionDEFAULT,'') #remove the .txt extension
    d.debug_out(newFileName)
    newFileName = punctuate(punctuate(newFileName.replace(newFileName,test_name),importFileName.replace(fileExtensionDEFAULT,'')),datatype)
    d.debug_out(newFileName)
    #this becomes {Thermals} {name string} {Legacy/Converged} for example
    newFileName = punctuate(newFileName,'.txt','')
    d.debug_out(newFileName)
    return newFileName
Beispiel #11
0
def parse_thermal_file(importFile,
                       outputFile,
                       searchWord='Converged',
                       enclosureType='',
                       driveType=''):
    #
    #outputFile = fdvt.rename_file(outputFile,'Thermals',searchWord,importFile)
    #
    now = datetime.datetime.now()
    thermalsDirectory = os.getcwd() + '\\Thermals\\{}'.format(
        now.strftime("%Y-%m-%d"))

    if not os.path.exists(thermalsDirectory):
        try:
            os.makedirs(thermalsDirectory)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise

    outputFile = thermalsDirectory + '\\{} Thermals {} {} Parsed {}'.format(
        driveType, enclosureType, searchWord, now.strftime("%H-%M")) + '.txt'
    d.debug_out('Thermal file: {}'.format(outputFile))
    pos = a.thermalSelectionArray.index(searchWord)
    #
    #d.debug_out(importFile)
    #
    #d.debug_out("Length of array: {}".format(len(a.thermalMasterArray)))
    #
    for i in range(len(a.thermalMasterArray[pos])):
        a.thermalMasterArray[pos] = []
    #
    searchWordArray = tests.thermalSearchWordDict[searchWord]
    #Brings in the array of search words that we are interested in
    #
    d.debug_out(""
                "\n        Search word: {}"
                "\n        Format: {}".format(searchWord, searchWordArray))
    #pause(1)
    #
    incomingFile = open(importFile, "r")
    #
    #d.debug_out("Length of array: {}".format(len(a.thermalMasterArray)))
    #
    d.debug_out(searchWord)
    pause(1)
    #
    for line in incomingFile:
        for i in range(len(a.thermalMasterArray)):  #length of the array
            if searchWordArray[i] in line:
                line = line[26:]
                #d.debug_out(line)
                if i == 0:  #look for the first search word, which is "time" var
                    #pause(1)
                    #example of 'time = ' line: 02/24/2018 00:45:35 (now)
                    if searchWord == 'Converged':
                        newline = line[7:26]
                        newline = newline.replace(' ', ',')
                        #d.debug_out(newline)
                        a.thermalMasterArray[i].append(split_data(newline))
                        #newline data format: [02/24/2018,02:41:34] -> [mm/dd/yyyy, 24hr format]
                    else:
                        line = incomingFile.next()
                        newline = line[:12].replace(',', '')
                        #d.debug_out(line)
                        newline = newline + ',' + line[14:22]
                        #d.debug_out(newline)
                        a.thermalMasterArray[i].append(split_data(newline))
                        #newline data format: [,16:28:00] -> [24 hour format]
                if i == 1:  #look for the second search word, "CurDegreesC"
                    newline = line[25:48]
                    #d.debug_out(newline)
                    newline = newline.replace(' CurDegreesC ', ',')
                    #d.debug_out(newline)
                    a.thermalMasterArray[i].append(split_data(newline))
                    #newline data format: [00010000,32] -> [device number, temp reported]
                if i == 2:  #look for the third search word, "Reported:"
                    startPos = line.index(searchWordArray[i]) + len(
                        searchWordArray[i]) + 1
                    endPos = startPos + 15
                    newline = line[startPos:endPos]
                    #d.debug_out(newline)
                    newline = replace_string(newline, ' Actual:', '', '  ',
                                             ',')
                    #d.debug_out(newline)
                    a.thermalMasterArray[i].append(split_data(newline))
                    #newline data format: [65,65] -> [Reported, Actual]
                if i == 3:  #look for the fourth search word, "Tachometer "
                    if searchWord == 'Converged':
                        fanString = line[:5]
                        startPos = line.index(searchWordArray[i]) + len(
                            searchWordArray[i]) + 22
                        endPos = startPos + 4
                        newline = fanString + ',' + line[startPos:endPos]
                        #d.debug_out(newline)
                        a.thermalMasterArray[i].append(split_data(newline))
                        #newline data format: [Fan 1, 3630] -> [Fan number, rpm]
                    else:
                        newline = line[2:7]
                        newline = newline + ',' + line[
                            line.index(searchWordArray[i]) +
                            len(searchWordArray[i]) +
                            3:line.index(searchWordArray[i]) +
                            len(searchWordArray[i]) + 7]
                        #d.debug_out(newline)
                        a.thermalMasterArray[i].append(split_data(newline))
                        #newline data format: [Fan 1, 3600] -> [Fan number, rpm]
                if i == 4:  #look for the fifth search word, "Temperature: "
                    startPos = line.index(searchWordArray[i]) + len(
                        searchWordArray[i]) + 12
                    endPos = startPos + 2
                    #d.debug_out('startPos={} endPos: {} i={}: '.format(startPos,endPos,i))
                    newline = line[startPos:endPos]
                    #d.debug_out(newline)
                    a.thermalMasterArray[i].append(newline)
                    #newline data format: [31] -> [Battery degrees C]
                if i == 5:  #look for the sixth search word, "mfgCtlNeedsAttnSummaryShow"
                    newline = incomingFile.next()
                    #d.debug_out(newline)
                    newline = newline[26:]
                    newline = newline.replace('\n', '')
                    a.thermalMasterArray[i].append(newline)
                    #newline data format: [NO NEEDS ATTENTION ENTRIES] -> [Test Status]
                if i == 6:
                    endPos = line.index(searchWordArray[i]) - 1
                    startPos = endPos - 2
                    newline = line[startPos:endPos]
                    #d.debug_out(newline)
                    a.thermalMasterArray[i].append(newline)
                    #newline data format: [24] -> [Number of devices]

    outgoingFile = open(outputFile, "w")

    #find the number of devices in the test array
    devices = int(a.thermalMasterArray[6][0])
    systemTemps = 6
    fanTachData = 4

    d.debug_out("Devices: {}".format(devices))
    pause(1)
    '''
    #DEBUGGING ARRAY OUTPUT
    for i in range(len(a.thermalMasterArray)):
        outgoingFile.write("\nSearch:\n"+ '   ' + searchWordArray[i] + ':' + '\n')
        outgoingFile.write(str(a.thermalMasterArray[i]))
        d.debug_out(a.thermalMasterArray[i])
    for i in range(len(a.thermalMasterArray)):
        d.debug_out(len(a.thermalMasterArray[i]))
    '''

    #write the header to the file: 'time = ','CurDegreesC','Reported: ','Tachometer ','Temperature: ','mfgCtlNeedsAttnSummaryShow'
    outgoingFile.write('Time,')
    for i in range(
            devices
    ):  #devices array -- make this smarter, what if the very first entry has a deprecated number of drives??
        outgoingFile.write('Device {}: '.format(i) +
                           str(a.thermalMasterArray[1][i][0]) + ',')
    outgoingFile.write(
        'Power Temp Sensor 1,Power Temp Sensor 2,Common Controller Sensor 1,Intel CPU Sensor 1,'
        'Common Controller Temp Sensor 2,Intel CPU Sensor 2,Fan Tach. 1,Fan Tach. 2,Fan Tach. 1, Fan Tach. 2,Battery Temp,Status\n'
    )

    #begin writing the correct output data in delimited format
    #d.debug_out("length of array: {}".format(len(a.thermalMasterArray[0])-1))
    #pause(1)
    for i in range(
            len(a.thermalMasterArray[0]) - 1
    ):  # number of times that we have collected time stamps becomes the number of rows
        if (i % 1) == 0:
            # d.debug_out('Time array: {}'.format(a.thermalMasterArray[0]))
            # d.debug_out('Time data: {} counter'.format(i))
            outgoingFile.write(str(a.thermalMasterArray[0][i][1]) + ',')
            npos = i * devices
            mpos = i * systemTemps
            fpos = i * fanTachData
            #d.debug_out("Position: {}".format(npos))
            for device_temp in range(
                    devices):  # number of devices thermal points
                outgoingFile.write(str(a.thermalMasterArray[1][npos][1]) + ',')
                npos += 1
            #    if npos>80000:
            #        d.debug_out(npos)
            #        pause(.1)
            for system_temp in range(systemTemps):
                outgoingFile.write(str(a.thermalMasterArray[2][mpos][0]) + ',')
                mpos += 1
            for fan_tach in range(fanTachData):
                outgoingFile.write(str(a.thermalMasterArray[3][fpos][1]) + ',')
                fpos += 1
            outgoingFile.write(
                str(a.thermalMasterArray[4][i]) + ',' +
                str(a.thermalMasterArray[5][i]) + ',\n')

        #ConvergedPowerTempSensor
        #ConvergedPowerTempSensor
        #CommonCtlrTempSensor
        #IntelCPUTempSensor
        #CommonCtlrTempSensor
        #IntelCPUTempSensor

    os.startfile(outputFile)
 def on_mouse_press(self, x, y, button, modifiers) -> None:
     debug_out("{}, {}, {}".format(x, y, button))
class GraphicsInputHandler(pyglet.window.Window):
    """
    Creates graphics and input handler for a game instance.
    Handles graphics for game and translates user input into game commands.
    In order to function, the instance should be updated and monitored in a game loop.

    Pass positional and statistical updates to change the appearance of objects and displays in the game.
    Uses pyglet:
    https://pyglet.readthedocs.io/en/latest/programming_guide/quickstart.html#hello-world
    """
    debug_out("Graphics-Input handler created!")
    __game_commands = []
    __continue_to_update = True
    __shapes = []

    is_main_menu = True
    # Add vertexes to this batch for rendering in window
    batch = pyglet.graphics.Batch()
    # Used for processing key inputs
    keys = pyglet.window.key

    def update(self, time_delta: float) -> None:
        """
        Updates instance.
        :param time_delta: Change in time for this update in nanoseconds
        :return: Nothing
        """
        self.process_commands()
        self.on_draw()

    def game_cmd(self, command: str, args) -> None:
        self.__game_commands.append((command, args))

    def exec_command(self, msg: tuple) -> bool:
        """
        Executes command using message and arguments passed through the parameter
        :param msg: Tuple containing command and arguments
        :return: True if command was successfully executed
        """
        command, args = parse_command(msg)
        try:
            if command == "EXIT":
                self.exit()
                return True
            elif command == "DEBUG_DOT_SCREEN":
                self.debug_draw_dot(args[0], args[1], args[2])
                return True
            elif command == "DEBUG_TIME":
                graph_sent_time = args[0]
                game_sent_time = args[1]
                round_trip = round(time() - graph_sent_time, 4)
                graph_to_game = round(game_sent_time - graph_sent_time, 4)
                game_to_graph = round(time() - game_sent_time, 4)
                debug_out(
                    "Round trip: {}s, Graph->Game: {}s, Game->Graph: {}s".
                    format(round_trip, graph_to_game, game_to_graph))
                return True
        except IndexError:
            debug_out(
                "ERROR - Not enough arguments for the following command: " +
                "\nCommand: {}".format(command) + "\n{}".format(str(args)))
        return False

    def active(self) -> bool:
        """
        :return: True if this node is updating
        """
        return self.__continue_to_update

    def exit(self) -> bool:
        """
        Called when node is supposed to exit
        :return: True if this node successfully exits
        """
        debug_out("Graphics-input handler exiting...")
        self.__game_commands.append(("EXIT", None))
        self.process_commands()
        self.close()
        return True

    def get_game_commands(self) -> list:
        """
        Returns commands for outputting to game node and clears internal waiting list
        :return: List of commands
        """
        ret = self.__game_commands
        self.__game_commands = []
        return ret

    def __init__(self,
                 phys_in: Queue,
                 stats_in: Queue,
                 user_out: Queue,
                 process_rate=-1):
        """
        :param phys_in: Receives objects with positions to draw
        :param stats_in: Receives information to display on screen
        :param user_out: Outputs tracked user input
        :param process_rate: Rate at which to process incoming and outgoing data from queues (updates per second)
        """
        super(GraphicsInputHandler, self).__init__(vsync=False)
        self.phys_in = phys_in
        self.stats_in = stats_in
        self.user_out = user_out
        self.process_rate = float(process_rate)
        self.hello_world_debug_label = pyglet.text.Label('Hello, world')

    def process_commands(self) -> None:
        """
        Grabs messages from 'phys_in' and 'stats_in' queues and processes them
        :return: Nothing
        """
        # There might need to be a hard limit on how much data is pulled from the queue
        msgs = []
        while True:
            if not self.phys_in.empty():
                msgs.append(self.phys_in.get_nowait())
            else:
                break
        while True:
            if not self.stats_in.empty():
                msgs.append(self.stats_in.get_nowait())
            else:
                break
        # Execute commands
        for msg in msgs:
            self.exec_command(msg)

        for msg in self.get_game_commands():
            self.user_out.put(msg)

    def run(self) -> bool:
        """
        Called to start this node's update loop
        :return: True if this node successfully starts running
        """
        pyglet.clock.schedule_interval(self.update, self.process_rate)
        pyglet.app.run()
        return True

    def debug_draw_dot(self, x: float, y: float, radius: float):
        """
        Draws a dot on the screen by adding a circle shape to the list
        :param x: x coord for center
        :param y: y coord for center
        :param radius: radius of circle from center
        :return:
        """
        self.__shapes.append(
            pyglet.shapes.Circle(x=x,
                                 y=y,
                                 radius=radius,
                                 color=(50, 225, 30),
                                 batch=self.batch))

    def on_draw(self) -> None:
        """
        Called when redrawing the screen. Could be optimized to redraw only certain parts of the screen if necessary
        :return:
        """
        self.clear()
        self.hello_world_debug_label.draw()
        self.batch.draw()

    def on_close(self) -> None:
        """
        Called when the user closes the window
        :return:
        """
        self.exit()

    def on_mouse_motion(self, x, y, dx, dy) -> None:
        pass

    def on_mouse_press(self, x, y, button, modifiers) -> None:
        debug_out("{}, {}, {}".format(x, y, button))

    def on_mouse_release(self, x, y, button, modifiers) -> None:
        pass

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers) -> None:
        pass

    def on_key_press(self, symbol, modifiers) -> None:
        # This has an extra time() argument for debugging things. It should be removed from game.py as well
        self.game_cmd('USER_KEY_PRESS',
                      [self.keys.symbol_string(symbol), modifiers,
                       time()])

    def on_key_release(self, symbol, modifiers) -> None:
        self.game_cmd('USER_KEY_RELEASE',
                      [self.keys.symbol_string(symbol), modifiers])
        pass
Beispiel #14
0
class PhysicsHandler:
    """
    Creates physics handler for a game instance.
    Handles physical data corresponding to an object and the relationship it has with other physical objects.
    In order to function, the instance should be updated and monitored in a game loop.

    Pass state updates to change the states of objects in the game.
    """
    debug_out("Physics handler created!")
    __continue_to_update = True
    __graphics_io_commands = []

    def update(self, time_delta: float) -> None:
        """
        Updates instance.
        :param time_delta: Change in time for this update in nanoseconds
        :return:
        """
        pass

    def exec_command(self, msg: tuple) -> bool:
        """
        Executes command using message and arguments passed through the parameter
        :param msg: Tuple containing command and arguments
        :return: True if command was successfully executed
        """
        command, args = parse_command(msg)
        try:
            if command == "EXIT":
                self.exit()
                return True
        except IndexError:
            debug_out("ERROR - Not enough arguments for the following command: "
                      + "\nCommand: {}".format(command)
                      + "\n{}".format(str(args)))
        return False

    def run(self) -> None:
        old_time = get_time()
        while self.__continue_to_update:
            time_delta = old_time - get_time()

            self.process_commands()
            self.update(time_delta)

            for msg in self.get_graphics_io_commands():
                self.objects_out.put(msg)

            old_time = get_time()

    def process_commands(self) -> None:
        """
        Grabs messages from 'phys_in' and 'stats_in' queues and processes them
        :return: Nothing
        """
        # There might need to be a hard limit on how much data is pulled from the queue
        msgs = []
        while True:
            if not self.objects_in.empty():
                msgs.append(self.objects_in.get_nowait())
            else:
                break
        # Execute commands
        for msg in msgs:
            self.exec_command(msg)

    def active(self) -> bool:
        """
        :return: True if this node is updating
        """
        return self.__continue_to_update

    def exit(self) -> None:
        """
        Called when node is supposed to exit
        :return: True if this node successfully exits
        """
        debug_out("Physics handler exiting...")
        self.__graphics_io_commands.append(("EXIT", None))
        self.__continue_to_update = False

    def get_graphics_io_commands(self) -> list:
        ret = self.__graphics_io_commands
        self.__graphics_io_commands = []
        return ret

    def __init__(self, objects_in: Queue, objects_out: Queue):
        self.objects_in = objects_in
        self.objects_out = objects_out
Beispiel #15
0
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        self.defaultsDirectory = os.getcwd() + '\\defaults\\'

        self.dict = tests.test_dict
        self.dict1 = tests.enclosure_dict
        self.driveArray = []
        self.ssdArray = []

        if not os.path.exists(self.defaultsDirectory):
            try:
                os.makedirs(self.defaultsDirectory)
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    raise

        self.defaultDriveFile = 'availableDrives.txt'
        self.defaultSSDFile = 'availableSSDs.txt'

        #open the drive default configuration file
        try:
            driveFile = open(self.defaultsDirectory + self.defaultDriveFile,
                             'r')
            ssdFile = open(self.defaultsDirectory + self.defaultSSDFile, 'r')
            for line in driveFile:
                line = line.replace('\n', '')
                self.driveArray.append(line)
            for line in ssdFile:
                line = line.replace('\n', '')
                self.ssdArray.append(line)
        except IOError:
            tkMessageBox.showinfo(
                'IMPORT ERROR', ' Unable to import the default drive file: {}.'
                '\n\nPlease recheck the default file in the directory: {}'.
                format(self.defaultsDirectory + self.defaultDriveFile,
                       self.defaultsDirectory))
            exit()

        print self.driveArray

        self.label1 = tk.Label(master, text="File Name")
        self.label1.grid(row=0, column=0)

        self.importEntry = tk.Entry(master, bd=2)
        self.importEntry.grid(row=0,
                              column=1,
                              columnspan=2,
                              ipadx=175,
                              pady=5,
                              padx=15)

        self.browseButton1 = tk.Button(master,
                                       text="Browse for file",
                                       command=self.fileBrowser1)
        self.browseButton1.grid(row=0, column=3, columnspan=1, padx=5)

        self.appendButton = tk.Button(master,
                                      text="Parse",
                                      fg='black',
                                      bg='grey',
                                      command=self.onclick)
        self.appendButton.grid(row=1, column=5, ipadx=20, pady=5)

        self.quitButton = tk.Button(master,
                                    text="Quit",
                                    fg='black',
                                    bg='grey',
                                    command=master.quit)
        self.quitButton.grid(row=1, column=0, rowspan=1, ipadx=10)

        #LIST BUTTONS AND MENUS
        self.enclosureListInput = tk.StringVar(master)
        self.typeListInput = tk.StringVar(master)
        self.testListInput = tk.StringVar(master)
        self.driveListInput = tk.StringVar(master)

        self.testListInput.set(tests.test_type[0])  # sets the default to RV
        self.typeListInput.set(self.dict[tests.test_type[0]][0])
        self.driveListInput.set(self.driveArray[0])

        self.testMenu = tk.OptionMenu(master, self.testListInput,
                                      *self.dict.keys())

        d.debug_out(self.dict[self.testListInput.get()])

        self.typeMenu = tk.OptionMenu(master, self.typeListInput,
                                      *self.dict[self.testListInput.get()])
        #                                                               dict['RV'] -> 'Baseline'....

        self.driveListMenu = tk.OptionMenu(master, self.driveListInput,
                                           *self.driveArray)

        d.debug_out(self.dict[self.testListInput.get()])

        self.testListInput.trace('w', self.update_options)

        self.enclosureListInput.set(
            enclosure_types.enclosure_list[0])  # sets the default to Joshua
        self.enclosureMenu = tk.OptionMenu(
            master, self.enclosureListInput,
            *self.dict1[self.testListInput.get()])
        #                                                                dict1['RV'] -> 'Joshua...'
        self.testMenu.grid(row=1, column=1, ipadx=40)
        self.typeMenu.grid(row=1, column=2, ipadx=40)
        self.enclosureMenu.grid(row=1, column=3, ipadx=5)
        self.driveListMenu.grid(row=1, column=4, ipadx=5)
Beispiel #16
0
class GameInstance:
    """
    Creates game instance for handling server-sided information about the game
    Handles and stores game logic, creation, deletion, manipulation, and serialization
    (Examples: creating a unit, telling a unit to move, giving credits to the player)

    In order to function, the instance should be updated and monitored in a game loop.

    Pass commands to the game instance to affect things in the running game
    """
    debug_out("Game instance created!")
    __continue_to_update = True
    __phys_commands = []
    __stats_commands = []

    def update(self, time_delta: float) -> None:
        """
        Updates instance.
        :param time_delta: Change in time for this update in nanoseconds
        :return:
        """
        pass

    def run(self) -> bool:
        """
        Called to start this node's update loop
        :return: True if this node successfully starts running
        """
        old_time = get_time()
        while self.__continue_to_update:
            time_delta = old_time - get_time()

            self.process_commands()
            self.update(time_delta)

            for msg in self.get_physics_commands():
                self.objects_out.put(msg)
            for msg in self.get_stats_commands():
                self.stats_out.put(msg)

            old_time = get_time()
        return True

    def process_commands(self) -> None:
        """
        Grabs messages from 'user_in' queues and processes them
        :return: Nothing
        """
        # There might need to be a hard limit on how much data is pulled from the queue
        msgs = []
        while True:
            if not self.user_in.empty():
                msgs.append(self.user_in.get_nowait())
            else:
                break
        # Execute commands
        for msg in msgs:
            self.exec_command(msg)

    def phys_cmd(self, command: str, args):
        self.__phys_commands.append((command, args))

    def stats_cmd(self, command: str, args):
        self.__stats_commands.append((command, args))

    def get_physics_commands(self) -> list:
        # Returns queued up commands and clears internal list
        ret = self.__phys_commands
        self.__phys_commands = []
        return ret

    def get_stats_commands(self) -> list:
        # Returns queued up commands and clears internal list
        ret = self.__stats_commands
        self.__stats_commands = []
        return ret

    def active(self) -> bool:
        """
        :return: True if this node is updating
        """
        return self.__continue_to_update

    def exec_command(self, msg: tuple) -> bool:
        """
        Executes command using message and arguments passed through the parameter
        :param msg: Tuple containing command and arguments
        :return: True if command was successfully executed
        """
        command, args = parse_command(msg)
        try:
            if command == "EXIT":
                self.exit()
                return True
            elif command == 'USER_KEY_PRESS':
                self.process_key_input(args[0], args[1])
                self.stats_cmd("DEBUG_TIME", [args[2], get_time()])
                return True
        except IndexError:
            debug_out(
                "ERROR - Not enough arguments for the following command: " +
                "\nCommand: {}".format(command) + "\n{}".format(str(args)))
        return False

    def process_key_input(self, key, modifiers) -> None:
        """
        Called when the game node is notified that the user has pressed a key.
        :param key: Key pressed
        :param modifiers: Any modifiers used such as shift or ctl, indicated by an integer
        :return: None
        """
        if key == 'ESCAPE':
            self.exit()
        elif key == 'SPACE':
            self.stats_cmd("DEBUG_DOT_SCREEN", [10, 20, 15])

    def exit(self) -> None:
        """
        Called when node is supposed to exit
        :return: True if this node successfully exits
        """
        debug_out("Graphics-input handler exiting...")
        self.__phys_commands.append(("EXIT", None))
        self.__stats_commands.append(("EXIT", None))
        self.__continue_to_update = False

    def __init__(self, user_in: Queue, stats_out: Queue, objects_out: Queue):
        self.user_in = user_in
        self.stats_out = stats_out
        self.objects_out = objects_out
        pass
Beispiel #17
0
def parse_file(fileName,outputFileName,searchWord='SAS HDD',controllerName = '',driveName = ''):
    pos = a.siSelectionArray.index(searchWord)
    now = datetime.datetime.now()
    siDirectory = os.getcwd()+'\\SI\\{}'.format(now.strftime("%Y-%m-%d"))

    if not os.path.exists(siDirectory):
        try:
            os.makedirs(siDirectory)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise

    outputFileName = '{}'.format(controllerName) + " -{}- ".format(fileName) + now.strftime("%H-%M") + '.txt'
    fullOutputFileName = siDirectory + '\\' + outputFileName

    d.debug_out(fullOutputFileName)

    # make sure that the arrays are empty
    for i in range(len(a.siMasterArray[pos])):
        a.siMasterArray[pos][i] = []

    searchWordArray = tests.siSearchWordDict[searchWord] #brings in the array
    #example of searchWordArray = ['./smartctl','attached phy identifier = ','Invalid word count: ',
    #                              'Running disparity error count: ','Loss of dword synchronization count: ',
    #                              'Phy reset problem count: ']
    d.debug_out(searchWordArray)
    #
    incomingFile = open(fileName, "r")
    #
    for line in incomingFile:
        for i in range(len(a.siMasterArray[pos])):
            if searchWordArray[i] in line: #not defined in a.py! this is f'n specific
                if i==0:
                    newString = line[len(line)-11:len(line)-1]
                    newString = newString.replace('/','')
                    a.siMasterArray[pos][i].append(newString)
                else:
                    a.siMasterArray[pos][i].append(generate_data_string(line,searchWordArray,i))
    #
    #USED FOR DEBUGGING
    for i in range(5):
        print a.siMasterArray[pos][i]
    #
    outputFile = open(fullOutputFileName,"w+")
    #
    # file header
    c_header(searchWordArray,fileName,outputFile)
    #
    arraylen = len(a.siMasterArray[pos])
    testlen = (len(a.siMasterArray[pos][1]))
    #this is the length of the amount of data that is in the phy id array,
    #to match the length of the sas device array
    #come up with a better solution!
    #
    #d.debug_out(testlen)
    #
    for i in range(len(a.siMasterArray[pos])):
        d.debug_out(len(a.siMasterArray[pos][i]))
    #
    #time.sleep(5)
    #
    s = 0
    #
    for i in range(testlen):
        #
        if (i%2)==0 and i!=0: #0%2 will return 0
            s+=1
        #
        d.debug_out('iteration' + str(i))
        #
        outputString = '\n' + a.siMasterArray[pos][0][s] + ':phy:' + a.siMasterArray[pos][1][i]
        d.debug_out(outputString)
        #
        for x in range(2,arraylen):
            if len(outputString)<20:
                for space in range(20-len(outputString)):
                    outputString = outputString + ' '
                outputString = outputString + ' ['
            outputString = outputString + ' ' + a.siMasterArray[pos][x][i]
        outputString = outputString + ' ]'
        #
        #outputString = '\n' + a.siMasterArray[pos][0][i] + ':phy:' + a.dataArray[1][i] + ' [' + a.dataArray[2][i] + ' ' + \
        #                a.dataArray[3][i] + ' ' + a.dataArray[4][i] + ' ' + a.dataArray[5][i] +']'
        #
        #d.debug_out(outputString)
        #
        d.debug_out('Output String: ' + outputString)
        outputFile.write(outputString)
    os.startfile(fullOutputFileName)
Beispiel #18
0
    # Queue containing data on game statistics and information
    gameStats = Queue()
    # Queue containing data on drawing objects
    drawObjects = Queue()
    # Queue containing user input data
    userInput = Queue()

    # Create game and physics processes
    gameLoop = Process(target=game_loop,
                       args=(
                           gameObjects,
                           gameStats,
                           userInput,
                       ))
    physLoop = Process(target=phys_loop, args=(
        gameObjects,
        drawObjects,
    ))
    gameLoop.daemon = True
    physLoop.daemon = True

    gameLoop.start()
    physLoop.start()

    debug_out("Starting game!")
    graphics_input_loop(drawObjects, gameStats, userInput)

    debug_out("Game exiting!")
    gameLoop.join()
    physLoop.join()