Beispiel #1
0
        def __init__(self):
            self.duration = None  # duration in ms
            self.amplitude = None
            self.table = None  # numpy array of samples
            self.chunks = None  # table split into a list of chunks
            self.trigger = None
            self.nsamples = None
            self.padded = False  # whether or not the sound was padded with zeros when chunked
            self.continuous = False

            self.fs = jackclient.FS
            self.blocksize = jackclient.BLOCKSIZE
            self.server = jackclient.SERVER
            self.q = jackclient.QUEUE
            self.q_lock = jackclient.Q_LOCK
            self.play_evt = jackclient.PLAY
            self.stop_evt = jackclient.STOP
            self.continuous_flag = jackclient.CONTINUOUS
            self.continuous_q = jackclient.CONTINUOUS_QUEUE
            self.continuous_loop = jackclient.CONTINUOUS_LOOP
            self.quitting = threading.Event()

            self.initialized = False
            self.buffered = False
            self.buffered_continuous = False

            self.logger = init_logger(self)
Beispiel #2
0
    def __init__(self):
        # type: () -> None
        QtWidgets.QWidget.__init__(self)

        self.logger = init_logger(self)

        # We should get passed a list of pilots to keep ourselves in order after initing
        self.pilots = None

        # Dict to store handles to plot windows by pilot
        self.plots = {}

        # Main Layout
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        # Plot Selection Buttons
        # TODO: Each plot bar should have an option panel, because different tasks have different plots
        #self.plot_select = self.create_plot_buttons()

        # Create empty plot container
        self.plot_layout = QtWidgets.QVBoxLayout()

        # Assemble buttons and plots
        #self.layout.addWidget(self.plot_select)
        self.layout.addLayout(self.plot_layout)

        self.setLayout(self.layout)

        self.setContentsMargins(0, 0, 0, 0)
Beispiel #3
0
    def __init__(self, pilot, x_width=50, parent=None):
        """
        Args:
            pilot (str): The name of our pilot
            x_width (int): How many trials in the past should we plot?
        """
        #super(Plot, self).__init__(QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers), parent)
        super(Plot, self).__init__()

        self.logger = init_logger(self)

        self.parent = parent
        self.layout = None
        self.infobox = None
        self.n_trials = None
        self.session_trials = 0
        self.info = {}
        self.plot = None
        self.xrange = None
        self.plot_params = {}
        self.data = {
        }  # Keep a dict of the data we are keeping track of, will be instantiated on start
        self.plots = {}
        self.state = "IDLE"
        self.continuous = False
        self.last_time = 0
        self.video = None
        self.videos = []

        self.invoker = get_invoker()

        # The name of our pilot, used to listen for events
        self.pilot = pilot

        # Set initial x-value, will update when data starts coming in
        self.x_width = x_width
        self.last_trial = self.x_width

        # Inits the basic widget settings
        self.init_plots()

        ## Station
        # Start the listener, subscribes to terminal_networking that will broadcast data
        self.listens = {
            'START': self.l_start,  # Receiving a new task
            'DATA': self.l_data,  # Receiving a new datapoint
            'CONTINUOUS': self.l_data,
            'STOP': self.l_stop,
            'PARAM': self.l_param,  # changing some param
            'STATE': self.l_state
        }

        self.node = Net_Node(id='P_{}'.format(self.pilot),
                             upstream="T",
                             port=prefs.get('MSGPORT'),
                             listens=self.listens,
                             instance=True)
Beispiel #4
0
    def __init__(self, name=None, **kwargs):
        if name:
            self.name = name
        else:
            try:
                self.name = self.get_name()
            except:
                Warning('wasnt passed name and couldnt find from prefs for object: {}'.format(self.__str__))
                self.name = None

        self.logger = init_logger(self)
        self.listens = {}
        self.node = None
Beispiel #5
0
    def __init__(self, name='jack_client'):
        """
        Args:
            name:
        """
        super(JackClient, self).__init__()

        # TODO: If global client variable is set, just return that one.

        self.name = name
        #self.pipe = pipe
        self.q = mp.Queue()
        self.q_lock = mp.Lock()

        self.play_evt = mp.Event()
        self.stop_evt = mp.Event()
        self.quit_evt = mp.Event()

        # we make a client that dies now so we can stash the fs and etc.
        self.client = jack.Client(self.name)
        self.blocksize = self.client.blocksize
        self.fs = self.client.samplerate
        self.zero_arr = np.zeros((self.blocksize, 1), dtype='float32')

        # a few objects that control continuous/background sound.
        # see descriptions in module variables
        self.continuous = mp.Event()
        self.continuous_q = mp.Queue(maxsize=1024)
        self.continuous_loop = mp.Event()
        self.continuous.clear()
        self.continuous_loop.clear()
        self.continuous_started = False

        # store the frames of the continuous sound and cycle through them if set in continous mode
        self.continuous_cycle = None

        # store a reference to us and our values in the module
        globals()['SERVER'] = self
        globals()['FS'] = copy(self.fs)
        globals()['BLOCKSIZE'] = copy(self.blocksize)
        globals()['QUEUE'] = self.q
        globals()['Q_LOCK'] = self.q_lock
        globals()['PLAY'] = self.play_evt
        globals()['STOP'] = self.stop_evt
        globals()['CONTINUOUS'] = self.continuous
        globals()['CONTINUOUS_QUEUE'] = self.continuous_q
        globals()['CONTINUOUS_LOOP'] = self.continuous_loop

        self.logger = init_logger(self)
Beispiel #6
0
    def __init__(self,
                 transform,
                 operation: str = "trigger",
                 return_id='T',
                 return_key=None,
                 stage_block=None,
                 value_subset=None,
                 **kwargs):
        """

        Args:
            transform:
            operation (str): either

                * "trigger", where the last transform is a :class:`~autopilot.transform.transforms.Condition`
                and a trigger is returned to sender only when the return value of the transformation changes, or
                * "stream", where each result of the transformation is returned to sender

            return_id:
            stage_block:
            value_subset (str): Optional - subset a value from from a dict/list sent to :meth:`.l_process`
            **kwargs:
        """
        assert operation in ('trigger', 'stream', 'debug')
        self.operation = operation
        self._last_result = None

        if return_key is None:
            self.return_key = self.operation.upper()
        else:
            self.return_key = return_key

        self.return_id = return_id
        self.stage_block = stage_block
        self.stages = cycle([self.noop])
        # self.input_q = LifoQueue()
        self.input_q = deque(maxlen=1)
        self.value_subset = value_subset

        self.logger = init_logger(self)

        self.process_thread = threading.Thread(target=self._process,
                                               args=(transform, ))
        self.process_thread.daemon = True
        self.process_thread.start()
Beispiel #7
0
    def __init__(self, *args, **kwargs):

        # Task management
        self.stage_block = None  # a threading.Event used by the pilot to manage stage transitions
        self.punish_stim = False
        #self.running = None  # Event used to exit the run thread
        self.stages = None  # Some generator that continuously returns the next stage of the trial
        self.triggers = {}
        self.stim_manager = None

        self.trial_counter = None  # will be init'd by the subtask because will use the current trial

        # Hardware
        self.hardware = {}  # dict to store references to hardware
        self.pin_id = {}  # pin numbers back to pin lettering

        self.punish_block = threading.Event()
        self.punish_block.set()
        #self.running = threading.Event()

        # try to get logger
        self.logger = init_logger(self)
    def __init__(self):
        # type: () -> None
        super(Terminal, self).__init__()

        # store instance
        globals()['_TERMINAL'] = self

        # networking
        self.node = None
        self.networking = None
        self.heartbeat_dur = 10  # check every n seconds whether our pis are around still

        # data
        self.subjects = {}  # Dict of our open subject objects

        # gui
        self.layout = None
        self.widget = None
        self.file_menu = None
        self.tool_menu = None
        self.control_panel = None
        self.data_panel = None
        self.logo = None

        # property private attributes
        self._pilots = None

        # logging
        self.logger = init_logger(self)

        # Listen dictionary - which methods to call for different messages
        # Methods are spawned in new threads using handle_message
        self.listens = {
            'STATE': self.l_state,  # A Pi has changed state
            'PING': self.l_ping,  # Someone wants to know if we're alive
            'DATA': self.l_data,
            'CONTINUOUS':
            self.l_data,  # handle continuous data same way as other data
            'STREAM': self.l_data,
            'HANDSHAKE':
            self.l_handshake  # a pi is making first contact, telling us its IP
        }

        # Make invoker object to send GUI events back to the main thread
        # self.invoker = Invoker()
        self.invoker = get_invoker()
        # prefs.add('INVOKER', self.invoker)

        self.initUI()

        # Start Networking
        # Networking is in two parts,
        # "internal" networking for messages sent to and from the Terminal object itself
        # "external" networking for messages to and from all the other components,
        # The split is so the external networking can run in another process, do potentially time-consuming tasks
        # like resending & confirming message delivery without blocking or missing messages

        self.node = Net_Node(id="_T",
                             upstream='T',
                             port=prefs.get('MSGPORT'),
                             listens=self.listens)
        self.logger.info("Net Node Initialized")

        # Start external communications in own process
        # Has to be after init_network so it makes a new context
        self.networking = Terminal_Station(self.pilots)
        self.networking.start()
        self.logger.info("Station object Initialized")

        # send an initial ping looking for our pilots
        self.node.send('T', 'INIT')

        # start beating ur heart
        # self.heartbeat_timer = threading.Timer(self.heartbeat_dur, self.heartbeat)
        # self.heartbeat_timer.daemon = True
        # self.heartbeat_timer.start()
        #self.heartbeat(once=True)
        self.logger.info('Terminal Initialized')
Beispiel #9
0
    def __init__(self, splash=True):

        if splash:
            with open(
                    os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                 'setup', 'welcome_msg.txt'),
                    'r') as welcome_f:
                welcome = welcome_f.read()
                print('')
                for line in welcome.split('\n'):
                    print(line)
                print('')
                sys.stdout.flush()

        self.name = prefs.get('NAME')
        if prefs.get('LINEAGE') == "CHILD":
            self.child = True
            self.parentid = prefs.get('PARENTID')
        else:
            self.child = False
            self.parentid = 'T'

        self.logger = init_logger(self)
        self.logger.debug('pilot logger initialized')

        # Locks, etc. for threading
        self.running = threading.Event()  # Are we running a task?
        self.stage_block = threading.Event(
        )  # Are we waiting on stage triggers?
        self.file_block = threading.Event()  # Are we waiting on file transfer?
        self.quitting = threading.Event()
        self.quitting.clear()

        # init pigpiod process
        self.init_pigpio()

        # Init audio server
        if prefs.get('AUDIOSERVER') or 'AUDIO' in prefs.get('CONFIG'):
            self.init_audio()

        # Init Station
        # Listen dictionary - what do we do when we receive different messages?
        self.listens = {
            'START':
            self.l_start,  # We are being passed a task and asked to start it
            'STOP': self.l_stop,  # We are being asked to stop running our task
            'PARAM': self.l_param,  # A parameter is being changed
            'CALIBRATE_PORT': self.l_cal_port,  # Calibrate a water port
            'CALIBRATE_RESULT':
            self.l_cal_result,  # Compute curve and store result
            'BANDWIDTH': self.l_bandwidth  # test our bandwidth
        }

        # spawn_network gives us the independent message-handling process
        self.networking = Pilot_Station()
        self.networking.start()
        self.node = Net_Node(id="_{}".format(self.name),
                             upstream=self.name,
                             port=prefs.get('MSGPORT'),
                             listens=self.listens,
                             instance=False)
        self.logger.debug('pilot networking initialized')

        # if we need to set pins pulled up or down, do that now
        self.pulls = []
        if prefs.get('PULLUPS'):
            for pin in prefs.get('PULLUPS'):
                self.pulls.append(
                    gpio.Digital_Out(int(pin), pull='U', polarity=0))
        if prefs.get('PULLDOWNS'):
            for pin in prefs.get('PULLDOWNS'):
                self.pulls.append(
                    gpio.Digital_Out(int(pin), pull='D', polarity=1))

        self.logger.debug('pullups and pulldowns set')
        # check if the calibration file needs to be updated

        # Set and update state
        self.state = 'IDLE'  # or 'Running'
        self.update_state()

        # Since we're starting up, handshake to introduce ourselves
        self.ip = self.get_ip()
        self.handshake()
        self.logger.debug('handshake sent')