Exemplo n.º 1
0
 def setUpClass(cls):
     _ui = UserInput()
     _ui.request('com4')
     flex = Flex(_ui)
     flex.open()
     cls.initial_state = flex.save_current_state()
     flex.close()
Exemplo n.º 2
0
 def tearDownClass(cls):
     _ui = UserInput()
     _ui.request('com4')
     flex = Flex(_ui)
     flex.open()
     flex.restore_state(cls.initial_state)
     flex.close()
Exemplo n.º 3
0
 def setUp(self):
     _ui = UserInput()
     _ui.request('com4')
     self.flex = Flex(_ui)
     self.flex.open()
     _ = self.flex.do_cmd_list(postproc.INITIALZE_FLEX)
     self.assertEqual(13, len(_))
Exemplo n.º 4
0
    def test_set_size_with_valid_size_should_set_grid_properties(self):
        user_input = UserInput()
        size = '3, 4'

        user_input.set_size(size)

        self.assertEquals(user_input.grid.x, 3)
        self.assertEquals(user_input.grid.y, 4)
    def setUp(self):
        """setUp()

        """
        _ui = UserInput()
        _ui.request('com4')
        self.flex = Flex(_ui)
        self.flex.open()
        self.flex.do_cmd_list(postproc.INITIALZE_FLEX)
Exemplo n.º 6
0
    def test_set_wanted_with_valid_input_should_set_userinput_properties(self):
        user_input = UserInput()
        user_input.set_size('4, 4')
        wanted = '2, 3, 30'

        user_input.set_wanted(wanted)

        self.assertEquals(user_input.wanted_x, 2)
        self.assertEquals(user_input.wanted_y, 3)
        self.assertEquals(user_input.turns, 30)
Exemplo n.º 7
0
    def __init__(self, configuration):
        pygame.init()
        self.display = Display(pygame, configuration)
        self.display.refresh()
        pygame.display.update()

        self.x_cell_number = configuration['x_cell_number']
        self.y_cell_number = configuration['y_cell_number']
        self.game_state = numpy.zeros((self.x_cell_number, self.y_cell_number))
        self.user_input = UserInput(self.x_cell_number, self.y_cell_number)
    def setUpClass(cls):
        """setUpClass()

        """
        _ui = UserInput()
        _ui.request('com4')
        flex = Flex(_ui)
        flex.open()
        cls.initial_state = flex.save_current_state()
        flex.close()
        postproc.enable_bands(['10', '20'])
Exemplo n.º 9
0
    def test_set_size_with_invalid_size_should_raise_value_error(self):
        user_input = UserInput()
        exc = None
        size = '3,3'

        try:
            user_input.set_size(size)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(str(exc), "Invalid input! Size must be like 'x, y'.")
Exemplo n.º 10
0
def main(argv):

    print("init")
    qs.init()

    myIP = (get_ip_address())  #get the ip address of the current device
    argv.pop(
        0
    )  #remove first item from argv list which is the file name of this program
    argvString = ' '.join(
        argv
    )  #convert to string & remove brackets from string, sets argv to be same format as typed inputs during runtime
    uInput = UserInput(argvString, myIP)

    #Start threads
    #TODO manage threads in list
    #threads = []

    # thread for listening for incoming udp messages, then adding those messages to the message Queue
    listendThread = threading.Thread(target=listenUDP, args=(myIP, ))
    listendThread.setDaemon(True)
    listendThread.start()

    # thread for checking user keyboard input
    inputThread = threading.Thread(target=inputListener)
    inputThread.setDaemon(True)
    inputThread.start()

    # thread for sending outgoing messages
    sendThread = threading.Thread(target=sendThreadfnc)
    sendThread.setDaemon(True)
    sendThread.start()

    # thread for processing all the recieved messages
    udpProcessthread = threading.Thread(target=processUDPQueue)
    udpProcessthread.setDaemon(True)
    udpProcessthread.start()

    while (True):

        #TODO re-evaluate how to properly kill threads
        if (not qs.qLocalCmdEmpty()):
            cmd = qs.qLocalCmdGet()
            if ('quit' == cmd.messageType):
                print("breaking")
                break

        #this checks if a new user input has been added to input Queue
        #then runs the uInput.newInput function which parses the input and preps the message to be sent to the cameras / quits the program
        if (not qs.qInputEmpty()):
            input = qs.qInput.get()
            uInput.newInput(input)
Exemplo n.º 11
0
    def test01_instantiate(self):
        """test_instantiate()

        check if Flex instiantiates and has expected str and repr without flex being opened

        """
        _ui = UserInput()
        _ui.request('com4')
        flex = Flex(_ui)

        self.assertEqual('Flex cat: com4, opened: False', str(flex))
        self.assertEqual('[Flex] Flex cat: com4, opened: False', repr(flex))
        flex.close()
Exemplo n.º 12
0
    def test_set_wanted_with_invalid_wanted_should_raise_value_error(self):
        user_input = UserInput()
        exc = None
        wanted = '3,3,50'

        try:
            user_input.set_wanted(wanted)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(
            str(exc),
            "Invalid expected input it should be like: 'x, y, turns'.")
Exemplo n.º 13
0
def main():
    """main()

    """

    ui = UserInput()
    ui.request(port='com4')
    flex = None
    try:
        flex = Flex(ui)
        flex.open()
    finally:
        if flex:
            flex.close()
Exemplo n.º 14
0
def main():
    """main()

    """
    # bandrd = Bandreadings(
    # ['14000000', '14073400', '14100000', '14200000'], None)
    #bd = bandrd.bandid
    ui: UserInput = UserInput()
    ui.request(port='com4')
    flexr: Flex = Flex(ui)
    initial_state = None
    try:
        if not flexr.open():
            raise (RuntimeError('Flex not connected to serial serial port'))

        print('saving current flex state')
        initial_state = flexr.save_current_state()
        print('initializing dbg flex state')
        flexr.do_cmd_list(postproc.INITIALZE_FLEX)
        bandr = Bandreadings('20', flexr)
        print('start scanning for noise')
        bss: SMeterAvg = bandr.doit()
        if False:

            with open('banddata.json', 'w') as jso:  # jsonpickle.encode
                _ = jsonpickle.encode(bss)
                jso.write(_)

            with open('banddata.json', 'r') as jsi:
                aa = jsi.readline()
                cpybss = jsonpickle.decode(aa)

            if str(bss) != str(cpybss):
                print('bss <> cpybss')

        print('end scanning for noise')
        print(f'band noise is {bandr.band_signal_strength}')

    except RuntimeError as re:
        raise
    except Exception as e:
        #a = 0
        print(e)
        raise e

    finally:
        print('restore flex prior state')
        flexr.restore_state(initial_state)
        flexr.close()
Exemplo n.º 15
0
    def test_set_wanted_with_out_of_bounds_should_raise_value_error(self):
        user_input = UserInput()
        user_input.grid.x = 2
        user_input.grid.y = 2
        wanted = '2, 2, 50'
        exc = None

        try:
            user_input.set_wanted(wanted)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(
            str(exc),
            "Invalid expected input it should be like: 'x, y, turns'.")
            def doita(
            ):  # the program to be run by _thread_template the return 0 says that no work need be done when stopping
                try:

                    UI: UserInput = UserInput()
                    UI.request(port='com4')
                    flexr: Flex = Flex(UI)
                    nf: Noisefloor = Noisefloor(flexr,
                                                arg.qs[QK.dQ],
                                                arg.stope,
                                                run_till_stopped=True)
                    nf.open()
                    nf.doit(loops=0, runtime=0, interval=100, dups=True)
                except StopEventException as see:
                    nf.close()
                    raise see
Exemplo n.º 17
0
def main():
    """main()

    Identifies the avilable ports, gets user input, sends the specified file (if exists) to
    the controller on a port.

    Prints the command list and processes the user selected command(s)

    """

    _available_ports = GetPorts().get()
    print(f"Available serial ports are: {_available_ports}")

    _ui: UserInput = UserInput()
    _ui.request()
    try:
        _ui.open()
        _send_specified_file(_ui)

        def _nodop(ignore: Any) -> bool:
            # pylint: disable=W0613
            return False

        def _errmsg(ignore: Any) -> bool:
            # pylint: disable=W0613
            print("only type one of Q, M, U, or F")
            return True

        cmddisptch = {
            'q': _nodop,
            'm': send_users_cmds,
            'u': do_utility_cmds,
            'f': send_file,
        }

        _loop_ctl: bool = True
        while _loop_ctl:
            _response = input("Type 'Q' to quit\n"
                              "Type 'M' for manual commands\n"
                              "type 'U' for Utility operations\n"
                              "Type 'F' for file transfer (Q/F/M/U)?>").strip().lower()[0:1]
            _loop_ctl = cmddisptch.get(_response, _errmsg)(_ui)
    finally:
        _ui.close()
Exemplo n.º 18
0
def __main():
    """__main()

    gets user input, opens port to the repeater, sends the contents of the specified file
    to the repeater controller, closes down
    """
    if not os.path.isdir(LOG_DIR):
        os.mkdir(LOG_DIR)
    _LF_HANDLER = logging.handlers.RotatingFileHandler(
        ''.join([LOG_DIR, LOG_FILE, ]),
        maxBytes=10000,
        backupCount=5,
    )
    _LF_HANDLER.setLevel(logging.DEBUG)
    _LC_HANDLER = logging.StreamHandler()
    _LC_HANDLER.setLevel(logging.DEBUG)  # (logging.ERROR)
    _LF_FORMATTER = logging.Formatter(
        '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
    _LC_FORMATTER = logging.Formatter(
        '%(name)s: %(levelname)s - %(message)s')
    _LC_HANDLER.setFormatter(_LC_FORMATTER)
    _LF_HANDLER.setFormatter(_LF_FORMATTER)
    _THE_LOGGER = logging.getLogger()
    _THE_LOGGER.setLevel(logging.DEBUG)
    _THE_LOGGER.addHandler(_LF_HANDLER)
    _THE_LOGGER.addHandler(_LC_HANDLER)
    _THE_LOGGER.info('commandreader executed as main')
    # LOGGER.setLevel(logging.DEBUG)
    _ui: UserInput = UserInput()
    _ui.request()
    _ui.open(detect_br=False)
    _cr = CommandReader(_ui)
    try:
        _cr.open()
        while True:
            _line = _cr.get()
            if not _line:
                break
            _jj = _line.split('\n')
            print(_jj[0])
    finally:
        _cr.close()
        _ui.close()
Exemplo n.º 19
0
# import usersettings
import usersettings

# create settings object
session_folder = os.getcwd()
settings_folder = currentdir  #os.path.join(currentdir.split('experiments')[0],"tasks","confidentiality_task_training_simple")
global settings_obj
settings_obj = TrialParameterHandler(usersettings, settings_folder,
                                     session_folder)

# create bpod object 'COM6' '/dev/cu.usbmodem62917601'
bpod = Bpod()
#bpod= Bpod('/dev/cu.usbmodem62917601') #TODO:
#create tkinter userinput dialoge window
window = UserInput(settings_obj)
window.draw_window_bevore_conf(stage="habituation_complex")
window.show_window()

# create multiprocessing variabls
# flags
display_stim_event = threading.Event()
still_show_event = threading.Event()
display_stim_event.clear()
still_show_event.clear()

#settings_obj.run_session = True #TODO:

# run session
if settings_obj.run_session:
    settings_obj.update_userinput_file_conf()
Exemplo n.º 20
0
        maxBytes=10000,
        backupCount=5,
    )
    LF_HANDLER.setLevel(logging.DEBUG)
    LC_HANDLER = logging.StreamHandler()
    LC_HANDLER.setLevel(logging.DEBUG)  # (logging.ERROR)
    LF_FORMATTER = logging.Formatter(
        '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
    LC_FORMATTER = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
    LC_HANDLER.setFormatter(LC_FORMATTER)
    LF_HANDLER.setFormatter(LF_FORMATTER)
    THE_LOGGER = logging.getLogger()
    THE_LOGGER.setLevel(logging.DEBUG)
    THE_LOGGER.addHandler(LF_HANDLER)
    THE_LOGGER.addHandler(LC_HANDLER)
    THE_LOGGER.info('userinput executed as main')
    # LOGGER.setLevel(logging.DEBUG)
    MS = MySerial()
    MS.open()
    from userinput import UserInput
    _UI = UserInput()
    try:
        _UI.request()
        _UI.open()
        print("Requested Port can be opened")
        _UI.close()

    except(Exception, KeyboardInterrupt) as exc:
        _UI.close()
        sys.exit(str(exc))
Exemplo n.º 21
0
from card import Card
from carddeck import CardDeck
from cardset import CardSet
from discardpile import DiscardPile
from player import Player
from table import Table
from typing import List, Tuple
import userinput
from userinput import UserInput
import logo
# TODO: add the player method .swap_card() to the game
# TODO: make move invalid if player empties their hand -- they must have at least one card remaining

ui = UserInput()


class Rummi:
    def __init__(self, player_names):
        print("Let's start the game!\n")
        self.deck = CardDeck()
        self.discard_pile = DiscardPile(self.deck)
        self.table = Table()
        self.players = [Player(name, self.deck) for name in player_names]
        self.turn_counter = 0

    def print_score_board(self):
        print('Here is the scoreboard:\n')
        for player in self.players:
            print('{}: {} points'.format(player.name, player.points))

    def draw(self, player: object):
Exemplo n.º 22
0
import argparse

from stocks import Stock
from userinput import CSVInput, UserInput

parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('csv_file', nargs='?', default=None, help="CSV file path")
args = parser.parse_args()

csv_file = args.csv_file

if __name__ == "__main__":
    all_stock_data = CSVInput().read(csv_file)
    user_input = UserInput(list(all_stock_data.keys()))()
    stock_records = all_stock_data[user_input['name']]
    stock = Stock(stock_records, user_input['start_date'],
                  user_input['end_date'])
    stock.print_all_data()
Exemplo n.º 23
0
def main(stop_events: Mapping[str, CTX.Event], queues: Mapping[str, CTX.JoinableQueue]):
    from smeteravg import SMeterAvg
    UI = UserInput()
    NOISE = None

    UI.request(port='com4')
    flexr = Flex(UI)
    initial_state = None
    try:
        if not flexr.open():
            raise (RuntimeError('Flex not connected to serial serial port'))
        print('saving current flex state')
        initial_state = flexr.save_current_state()
        print('initializing dbg flex state')
        flexr.do_cmd_list(INITIALZE_FLEX)
        flexr.close()
        resultQ = queues.get(QK.dQ)
        stop_event = stop_events.get(SEK.da)

        NOISE = Noisefloor(flexr, resultQ, stop_event)
        NOISE.open()
        # loops must be less than 100 as that is the queue size and I am not emptying it here
        NOISE.doit(loops=90, interval=90, dups=True)
        # NOISE.doit(runtime=1, interval=60)
        try:
            stop_event.set()
        except StopEventException:
            pass

        if NOISE and NOISE.is_open:
            flexr.restore_state(initial_state)
            NOISE.close()

        indata: List[NFQ] = []
        deck: Deck = Deck(1000)
        deck.q2deck(resultQ, mark_done=True)
        indata = deck.deck2lst()

        # try:

        # while True:
        #indata.append(resultQ.get(True, 1))
        # resultQ.task_done()
        # except QEmpty:
        # pass  # q is empty
        # except Exception as ex:
        # print(ex)
        #raise ex

        with open('nfqlistdata.pickle', 'wb') as jso:
            pickle.dump(indata, jso)

        unpacked: List[NFResult] = [npq.get() for npq in indata]
        with open('nfrlistdata.pickle', 'wb') as jso:
            pickle.dump(unpacked, jso)

        reads: List[SMeterAvg] = []
        for nfr in unpacked:
            reads.extend(nfr.readings)

        with open('smavflistdata.pickle', 'wb') as jso:
            pickle.dump(reads, jso)

        up0: NFResult = unpacked[0]
        outdata = []
        with open('nfqlistdata.pickle', 'rb') as jsi:
            outdata = pickle.load(jsi)

        brlst: List[Bandreadings] = []
        for nfq in outdata:
            br: Bandreadings = nfq.get()
            brlst.append(br)

        a = indata[0]
        b = outdata[0]

    except(Exception, KeyboardInterrupt) as exc:
        if NOISE and NOISE.is_open:
            flexr.restore_state(initial_state)
            NOISE.close()
        UI.close()
        raise exc

    finally:
        print('restore flex prior state')

        if NOISE and NOISE.is_open:
            flexr.restore_state(initial_state)
            NOISE.close()
        UI.close()