Example #1
0
def run(rootScriptPathDir,configFilePath):
    psychopy.iohub.EXP_SCRIPT_DIRECTORY = rootScriptPathDir

    import tempfile
    tdir=tempfile.gettempdir()
    cdir,cfile=os.path.split(configFilePath)
    if tdir==cdir:
        tf=open(configFilePath)
        ioHubConfig=json.loads(tf.read())
        tf.close()
        os.remove(configFilePath)
    else:
        ioHubConfig=load(file(configFilePath,'r'), Loader=Loader)

    hub_defaults_config=load(file(os.path.join(psychopy.iohub.IO_HUB_DIRECTORY,'default_config.yaml'),'r'), Loader=Loader)
    updateDict(ioHubConfig,hub_defaults_config)
    try:
        s = ioServer(rootScriptPathDir, ioHubConfig)
    except Exception,e:
        printExceptionDetailsToStdErr()
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except:
            pass
        
        return -1
Example #2
0
def run(rootScriptPathDir,configFilePath):
    import tempfile
    tdir=tempfile.gettempdir()
    cdir,cfile=os.path.split(configFilePath)

    if tdir==cdir:
        tf=open(configFilePath)
        ioHubConfig=json.loads(tf.read())
        tf.close()
        os.remove(configFilePath)
    else:
        ioHubConfig=load(file(configFilePath,'r'), Loader=Loader)

    hub_defaults_config=load(file(os.path.join(iohub.IO_HUB_DIRECTORY,'default_config.yaml'),'r'), Loader=Loader)
    updateDict(ioHubConfig,hub_defaults_config)
    try:
        s = ioServer(rootScriptPathDir, ioHubConfig)
    except Exception,e:
        printExceptionDetailsToStdErr()
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except:
            pass
        
        return -1
Example #3
0
    def __init__(self, win, io_config="eyelink1000.yaml", enabled=True):
        """Initialization of class with address required

		:param str msg: Marker/message to be sent to tracker
		"""
        #Populate defaults
        self.enabled = enabled
        self.io_config = io_config
        self.win = win
        self.eyetracker = False
        self.io = False

        #Initialize eyetracker if enabled (via enabled)
        if self.enabled == True:
            from psychopy.iohub import EventConstants, ioHubConnection, load, Loader

            #Load the specified iohub configuration file converting it to a python dict.
            io_config_data = load(file(self.io_config, 'r'), Loader=Loader)

            #Create an ioHubConnection instance, which starts the ioHubProcess, and informs it of the requested devices and their configurations.
            self.io = ioHubConnection(io_config_data)

            #Create a link to the tracker via iohub
            if self.io.getDevice('tracker'):
                self.eyetracker = self.io.getDevice('tracker')
Example #4
0
    def __init__(self, rootScriptPathDir, config=None):
        self._session_id=None
        self._experiment_id=None

        self.log("Server Time Offset: {0}".format(Computer.globalClock.getLastResetTime()))

        self._hookManager=None
        self.emrt_file=None
        self.config=config
        self.devices=[]
        self.deviceMonitors=[]
        self.sessionInfoDict=None
        self.experimentInfoList=None
        self.filterLookupByInput={}
        self.filterLookupByOutput={}
        self.filterLookupByName={}  
        self._hookDevice=None
        ioServer.eventBuffer=deque(maxlen=config.get('global_event_buffer',2048))

        self._running=True
        
        # start UDP service
        self.udpService=udpServer(self,':%d'%config.get('udp_port',9000))

        try:
            # initial dataStore setup
            if 'data_store' in config and psychopy.iohub._DATA_STORE_AVAILABLE:
                experiment_datastore_config=config.get('data_store')
                default_datastore_config_path=os.path.join(IO_HUB_DIRECTORY,'datastore','default_datastore.yaml')
                #print2err('default_datastore_config_path: ',default_datastore_config_path)
                _dslabel,default_datastore_config=load(file(default_datastore_config_path,'r'), Loader=Loader).popitem()

                for default_key,default_value in default_datastore_config.iteritems():
                    if default_key not in experiment_datastore_config:
                        experiment_datastore_config[default_key]=default_value
                                
                if experiment_datastore_config.get('enable', True):
                    #print2err("Creating ioDataStore....")

                    resultsFilePath=rootScriptPathDir
                    self.createDataStoreFile(experiment_datastore_config.get('filename','events')+'.hdf5',resultsFilePath,'a',experiment_datastore_config)

                    #print2err("Created ioDataStore.")
        except:
            print2err("Error during ioDataStore creation....")
            printExceptionDetailsToStdErr()


        #built device list and config from initial yaml config settings
        try:
            for iodevice in config.get('monitor_devices',()):
                for device_class_name,deviceConfig in iodevice.iteritems():
                    #print2err("======================================================")
                    #print2err("Started load process for: {0}".format(device_class_name))
                    self.createNewMonitoredDevice(device_class_name,deviceConfig)
        except:
            print2err("Error during device creation ....")
            printExceptionDetailsToStdErr()
            raise ioHubError("Error during device creation ....")
Example #5
0
def loadYamlFile(yaml_file_path,print_file=False):
    yaml_file_contents=load(file(yaml_file_path,'r'), Loader=Loader)    
#    if print_file:
#        print 'yaml_file_contents:'
#        print 'file: ',yaml_file_path
#        print 'contents:'    
#        pprint(yaml_file_contents)    
    return yaml_file_contents
def loadYamlFile(yaml_file_path, print_file=False):
    yaml_file_contents = load(file(yaml_file_path, 'r'), Loader=Loader)
    #    if print_file:
    #        print 'yaml_file_contents:'
    #        print 'file: ',yaml_file_path
    #        print 'contents:'
    #        pprint(yaml_file_contents)
    return yaml_file_contents
Example #7
0
def readAppSettingParameters(session_folder):
    #recording_period:
    #    start_msg: RECORDING_STARTED
    #    event_period:
    #        start_msg: START_EVENT_PERIOD
    #        end_msg: END_EVENT_PERIOD
    #    end_msg: RECORDING_STOPPED
    return load(file(os.path.join(session_folder,
                                      'last_app_config.yaml'), u'r'),
                                                        Loader=Loader)
Example #8
0
def main(configurationDirectory):
    pjoin = os.path.join
    abspath = os.path.abspath
    psplit = os.path.split
    pexists = os.path.exists
    pisdir = os.path.isdir

    app_conf = load(file(os.path.join(configurationDirectory,
                                    "..\\settings\\app_config.yaml"), u'r'),
                                    Loader=Loader)

    view_server_info={}

    print
    print "Confero Track Started. "

    if app_conf.get('view_server',{}).get('address').lower() in [None, 'auto', 'bonjour']:
        view_server_info = findConferoViewServer()
        print "Found Confero Server via Bonjour:", view_server_info['ip'], view_server_info['port']
        print
        app_conf.get('view_server')['address'] = view_server_info['ip']
        app_conf.get('view_server')['port'] = view_server_info['port']
    else:
        view_server_info['ip'] = app_conf.get('view_server')['address']
        view_server_info['port'] = app_conf.get('view_server')['port']
        print "Using app_config settings for Confero Server connection:", view_server_info['ip'], view_server_info['port']
        print

    DataCollectionRuntime.view_server_ip = view_server_info['ip']

    DataCollectionRuntime.results_root_folder = \
                                    app_conf.get('results_root_folder')
    if not (pexists(DataCollectionRuntime.results_root_folder)
            and pisdir(DataCollectionRuntime.results_root_folder)):
        DataCollectionRuntime.results_root_folder = abspath(pjoin(
            DataCollectionRuntime.script_dir,
            DataCollectionRuntime.results_root_folder))
    util.createPath(DataCollectionRuntime.results_root_folder)

    try:
        ws = createWebsocketInterface(app_conf)
    except socket.error, e:
        if e.errno == 10035:
            pass
        elif e.errno in [10054,10061]:
            print('WebSocket could not be connected to feedback server. '
                  'Is the server program running?')
            return 'EXIT_PROGRAM'
        else:
            raise e
Example #9
0
    wrapWidth=None,
    ori=0,
    color='black',
    colorSpace='rgb',
    opacity=1,
    languageStyle='LTR',
    depth=-1.0)

eyetracker = False  #will change if we get one!

from psychopy.iohub.constants import (EventConstants, EyeTrackerConstants)
from psychopy.iohub import ioHubConnection, load, Loader
from psychopy.data import getDateStr

# Load the specified iohub configuration file converting it to a python dict.
io_config = load(file('SMI_iview.yaml', 'r'), Loader=Loader)

# Add / Update the session code to be unique. Here we use the psychopy getDateStr() function for session code generation
session_info = io_config.get('data_store').get('session_info')
session_info.update(code="S_%s" % (getDateStr()))

#u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# Rename file we are writing to
datastore = io_config.get('data_store')
datastore.update(filename='data/%s_%s_%s' %
                 (expInfo['participant'], expName, expInfo['date']))

# Create an ioHubConnection instance, which starts the ioHubProcess, and informs it of the requested devices and their configurations.

io = ioHubConnection(io_config)
Example #10
0
                           ori=0,
                           name='stimulus',
                           text='default text',
                           font='Arial',
                           pos=[0, 0],
                           height=100,
                           wrapWidth=None,
                           color=1.0,
                           colorSpace='rgb',
                           opacity=1,
                           depth=0.0)
try:
    from psychopy.iohub import EventConstants, KeyboardConstants, ioHubConnection, load, Loader
    from psychopy.data import getDateStr
    # Load the iohub device config, file converting it to a python dict.
    io_config = load(file('iohub_config.yaml', 'r'), Loader=Loader)

    # Add / Update the session code to be unique. Here we use the psychopy getDateStr() function for session code generation
    session_info = io_config.get('data_store').get('session_info')
    session_info.update(code="S_%s" % (getDateStr()))

    # Create an ioHubConnection instance, which starts the ioHubProcess, and informs it of the requested devices and their configurations.
    io = ioHubConnection(io_config)
    iokeyboard = io.devices.keyboard
    iomouse = io.devices.mouse
except Exception, e:
    import sys
    print "!! Error starting ioHub: ", e, " Exiting..."
    sys.exit(1)

# Initialize components for Routine "thanks"
Example #11
0
    D) Print Last Received Eye Event every 0.25 sec.
    E) Stop Recording Eye Data when the SPACE key is pressed.
    F) Close the Eye Tracker Device.
    G) End the Demo
    
For a more complete example of how to code a more realistic experiment structure
using CODER, please see the gc_window example in this directory.
"""

from psychopy.iohub import EventConstants, ioHubConnection, load, Loader
from psychopy.data import getDateStr

# Load the specified iohub configuration file
# converting it to a python dict.
#
io_config = load(file("./SMI_iview_std.yaml", "r"), Loader=Loader)

# Add / Update the session code to be unique. Here we use the psychopy
# getDateStr() function for session code generation
#
session_info = io_config.get("data_store").get("session_info")
session_info.update(code="S_%s" % (getDateStr()))

# Create an ioHubConnection instance, which starts the ioHubProcess, and
# informs it of the requested devices and their configurations.
#
io = ioHubConnection(io_config)

keyboard = io.devices.keyboard
eyetracker = io.devices.tracker
Example #12
0
                           color=1.0,
                           colorSpace='rgb',
                           opacity=1,
                           depth=0.0)
import csv

#Lets have a flag to say our header has not been written to gaze data file
header_written = False

eyetracker = False  #will change if we get one!

if expInfo['Eye Tracker']:
    from psychopy.iohub import EventConstants, ioHubConnection, load, Loader
    from psychopy.data import getDateStr
    # Load the specified iohub configuration file converting it to a python dict.
    io_config = load(file(expInfo['Eye Tracker'], 'r'), Loader=Loader)

    # Add / Update the session code to be unique. Here we use the psychopy getDateStr() function for session code generation
    session_info = io_config.get('data_store').get('session_info')
    session_info.update(code="S_%s" % (getDateStr()))

    # Create an ioHubConnection instance, which starts the ioHubProcess, and informs it of the requested devices and their configurations.
    io = ioHubConnection(io_config)

    iokeyboard = io.devices.keyboard
    mouse = io.devices.mouse
    if io.getDevice('tracker'):
        eyetracker = io.getDevice('tracker')

        win.winHandle.minimize()
        eyetracker.runSetupProcedure()
Example #13
0
def run(rootScriptPathDir,configFilePath):
    psychopy.iohub.EXP_SCRIPT_DIRECTORY = rootScriptPathDir

    import tempfile
    tdir=tempfile.gettempdir()
    cdir,cfile=os.path.split(configFilePath)
    if tdir==cdir:
        tf=open(configFilePath)
        ioHubConfig=json.loads(tf.read())
        tf.close()
        os.remove(configFilePath)
    else:
        ioHubConfig=load(file(configFilePath,'r'), Loader=Loader)

    hub_defaults_config=load(file(os.path.join(psychopy.iohub.IO_HUB_DIRECTORY,'default_config.yaml'),'r'), Loader=Loader)
    updateDict(ioHubConfig,hub_defaults_config)
    try:
        s = ioServer(rootScriptPathDir, ioHubConfig)
    except Exception as e:
        printExceptionDetailsToStdErr()
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except Exception:
            pass
        
        return -1
    
    try:
        s.log('Receiving datagrams on :9000')
        s.udpService.start()


        if Computer.system == 'win32':
            gevent.spawn(s.pumpMsgTasklet, s.config.get('windows_msgpump_interval', 0.00375))

        if hasattr(gevent,'run'):
            for m in s.deviceMonitors:
                m.start()
    
            gevent.spawn(s.processEventsTasklet, 0.01)

            sys.stdout.write("IOHUB_READY\n\r\n\r")

            #print2err("Computer.psychopy_process: ", Computer.psychopy_process)
            if Computer.psychopy_process:
                gevent.spawn(s.checkForPsychopyProcess, 0.5)

            sys.stdout.flush()
            
            gevent.run()
        else:
            glets=[]
            if Computer.system == 'win32':
                glets.append(gevent.spawn(s.pumpMsgTasklet, s.config.get('windows_msgpump_interval', 0.00375)))

            for m in s.deviceMonitors:
                m.start()
                glets.append(m)
            glets.append(gevent.spawn(s.processEventsTasklet,0.01))
    
            sys.stdout.write("IOHUB_READY\n\r\n\r")
            sys.stdout.flush()

            #print2err("Computer.psychopy_process: ", Computer.psychopy_process)
            if Computer.psychopy_process:
                 glets.append(gevent.spawn(s.checkForPsychopyProcess, 0.5))

            gevent.joinall(glets)
            

        s.log("Server END Time Offset: {0}".format(Computer.global_clock.getLastResetTime()),'DEBUG')

    except Exception as e:
        print2err("Error occurred during ioServer.start(): ",str(e))
        printExceptionDetailsToStdErr()
        print2err("------------------------------")

        sys.stdout.write("IOHUB_FAILED\n\r\n\r")
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except Exception:
            pass
    
    return -1
Example #14
0
#from psychopy import iohub
import pandas as pd
allScrs = pyglet.window.get_platform().get_default_display().get_screens()
print allScrs

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# ====================================================================================
# EyeLink
et = 1 # eye-tracking on or off
if et:
    from psychopy.iohub import EventConstants,ioHubConnection,load,Loader
    # Load the specified iohub configuration file converting it to a python dict.
    io_config = load(file('SRR_eyelink_std.yaml','r'), Loader=Loader)
    #eyeLink = ("100.1.1.1")
    session_info = io_config.get('data_store').get('session_info')
    session_info.update(code="S_%s"%(getDateStr()))
    io = ioHubConnection(io_config)
else:
    from psychopy.iohub import launchHubServer
    io = launchHubServer()
kb_device = io.devices.keyboard

if et:
    el = io.devices.tracker
    el.runSetupProcedure()

# Store info about the experiment session
expName = 'mcbsf'  # from the Builder filename that created this script
    opacity=1.0,
    texRes=128,
    interpolate=True,
    depth=-2.0,
)
maintain_fix_pix_boundary = 66.0
eyetracker = False  # will change if we get one!

if expInfo["Eye Tracker"]:
    try:
        from psychopy.iohub import EventConstants, ioHubConnection, load, Loader
        from psychopy.iohub.util import NumPyRingBuffer
        from psychopy.data import getDateStr

        # Load the specified iohub configuration file converting it to a python dict.
        io_config = load(file(expInfo["Eye Tracker"], "r"), Loader=Loader)

        # Add / Update the session code to be unique. Here we use the psychopy getDateStr() function for session code generation
        session_info = io_config.get("data_store").get("session_info")
        session_info.update(code="S_%s" % (getDateStr()))

        # Create an ioHubConnection instance, which starts the ioHubProcess, and informs it of the requested devices and their configurations.
        io = ioHubConnection(io_config)

        iokeyboard = io.devices.keyboard
        mouse = io.devices.mouse
        if io.getDevice("tracker"):
            eyetracker = io.getDevice("tracker")

            win.winHandle.minimize()
            eyetracker.runSetupProcedure()
Example #16
0
    D) Print Last Received Eye Event every 0.25 sec.
    E) Stop Recording Eye Data when the SPACE key is pressed.
    F) Close the Eye Tracker Device.
    G) End the Demo
    
For a more complete example of how to code a more realistic experiment structure
using CODER, please see the gc_window example in this directory.
"""

from psychopy.iohub import EventConstants, ioHubConnection, load, Loader
from psychopy.data import getDateStr

# Load the specified iohub configuration file
# converting it to a python dict.
#
io_config = load(file('./SMI_iview_std.yaml', 'r'), Loader=Loader)

# Add / Update the session code to be unique. Here we use the psychopy
# getDateStr() function for session code generation
#
session_info = io_config.get('data_store').get('session_info')
session_info.update(code="S_%s" % (getDateStr()))

# Create an ioHubConnection instance, which starts the ioHubProcess, and
# informs it of the requested devices and their configurations.
#
io = ioHubConnection(io_config)

keyboard = io.devices.keyboard
eyetracker = io.devices.tracker
Example #17
0
    def __init__(self, rootScriptPathDir, config=None):
        self._session_id = None
        self._experiment_id = None

        self.log("Server Time Offset: {0}".format(
            Computer.globalClock.getLastResetTime()))

        self._hookManager = None
        self.emrt_file = None
        self.config = config
        self.devices = []
        self.deviceMonitors = []
        self.sessionInfoDict = None
        self.experimentInfoList = None
        self.filterLookupByInput = {}
        self.filterLookupByOutput = {}
        self.filterLookupByName = {}
        self._hookDevice = None
        ioServer.eventBuffer = deque(
            maxlen=config.get('global_event_buffer', 2048))

        self._running = True

        # start UDP service
        self.udpService = udpServer(self, ':%d' % config.get('udp_port', 9000))

        try:
            # initial dataStore setup
            if 'data_store' in config and psychopy.iohub._DATA_STORE_AVAILABLE:
                experiment_datastore_config = config.get('data_store')
                default_datastore_config_path = os.path.join(
                    IO_HUB_DIRECTORY, 'datastore', 'default_datastore.yaml')
                #print2err('default_datastore_config_path: ',default_datastore_config_path)
                _dslabel, default_datastore_config = load(
                    file(default_datastore_config_path,
                         'r'), Loader=Loader).popitem()

                for default_key, default_value in default_datastore_config.iteritems(
                ):
                    if default_key not in experiment_datastore_config:
                        experiment_datastore_config[
                            default_key] = default_value

                if experiment_datastore_config.get('enable', True):
                    #print2err("Creating ioDataStore....")

                    resultsFilePath = rootScriptPathDir
                    self.createDataStoreFile(
                        experiment_datastore_config.get('filename', 'events') +
                        '.hdf5', resultsFilePath, 'a',
                        experiment_datastore_config)

                    #print2err("Created ioDataStore.")
        except:
            print2err("Error during ioDataStore creation....")
            printExceptionDetailsToStdErr()

        #built device list and config from initial yaml config settings
        try:
            for iodevice in config.get('monitor_devices', ()):
                for device_class_name, deviceConfig in iodevice.iteritems():
                    #print2err("======================================================")
                    #print2err("Started load process for: {0}".format(device_class_name))
                    self.createNewMonitoredDevice(device_class_name,
                                                  deviceConfig)
        except:
            print2err("Error during device creation ....")
            printExceptionDetailsToStdErr()
            raise ioHubError("Error during device creation ....")

        # Add PubSub device listeners to other event types
        try:
            for d in self.devices:
                if d.__class__.__name__ == "EventPublisher":
                    monitored_event_ids = d._event_listeners.keys()
                    for eid in monitored_event_ids:
                        event_device_class = EventConstants.getClass(
                            eid).PARENT_DEVICE
                        for ed in self.devices:
                            if ed.__class__ == event_device_class:
                                ed._addEventListener(d, [
                                    eid,
                                ])
                                break

        except Exception, e:
            print2err("Error PubSub Device listener association ....")
            printExceptionDetailsToStdErr()
            raise e
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 23:43:45 2014

@author: Sol
"""
from register_server import ConferoBonjourService
from webserver import ControlFeedbackServer
from psychopy.iohub import Loader, load
from findserver import findConferoViewServer
import os
if __name__ == "__main__":
    app_config = load(file(os.path.abspath(r'..\settings\app_config.yaml'), 'r'),
                        Loader=Loader)

    print
    print "Confero Server Starting... "
    bonsvc = None
    server_ip = app_config.get('http_address',None)
    if server_ip.lower() in [None, 'default', 'auto', 'bonjour']:
        bonsvc = ConferoBonjourService()
        view_server_info = findConferoViewServer()

        app_config['http_address'] = view_server_info['ip']
        app_config['http_port'] = view_server_info['port']

        print "Registered Confero Server with Bonjour for ip", app_config['http_address'],' : ',app_config['http_port']
        print
    else:
        print " Confero Server being started with app_config IP settings:", app_config['http_address'],' : ',app_config['http_port']
        print
Example #19
0
    def addDeviceToMonitor(self, device_class_name, device_config):
        device_class_name = str(device_class_name)

        self.log("Handling Device: %s" % (device_class_name, ))
        #print2err("addDeviceToMonitor:\n\tdevice_class: {0}\n\texperiment_device_config:{1}\n".format(device_class_name,device_config))

        DeviceClass = None
        class_name_start = device_class_name.rfind('.')
        iohub_sub_mod = 'psychopy.iohub.'
        iohub_submod_path_length = len(iohub_sub_mod)
        device_module_path = iohub_sub_mod + 'devices.'
        if class_name_start > 0:
            device_module_path = "{0}{1}".format(
                device_module_path,
                device_class_name[:class_name_start].lower())
            device_class_name = device_class_name[class_name_start + 1:]
        else:
            device_module_path = "{0}{1}".format(device_module_path,
                                                 device_class_name.lower())

        #print2err("Processing device, device_class_name: {0}, device_module_path: {1}".format(device_class_name, device_module_path))

        dconfigPath = os.path.join(
            IO_HUB_DIRECTORY,
            device_module_path[iohub_submod_path_length:].replace(
                '.',
                os.path.sep), "default_%s.yaml" % (device_class_name.lower()))

        #print2err("dconfigPath: {0}, device_module_path: {1}\n".format(dconfigPath,device_module_path))
        #print2err("Loading Device Defaults file:\n\tdevice_class: {0}\n\tdeviceConfigFile:{1}\n".format(device_class_name,dconfigPath))
        self.log("Loading Device Defaults file: %s" % (device_class_name, ))

        _dclass, default_device_config = load(file(dconfigPath, 'r'),
                                              Loader=Loader).popitem()

        #print2err("Device Defaults:\n\tdevice_class: {0}\n\tdefault_device_config:{1}\n".format(device_class_name,default_device_config))

        self.processDeviceConfigDictionary(device_module_path,
                                           device_class_name, device_config,
                                           default_device_config)

        if device_module_path in self._all_device_config_errors:
            # Complete device config verification.
            print2err(
                "**** ERROR: DEVICE CONFIG ERRORS FOUND ! NOT LOADING DEVICE: ",
                device_module_path)
            device_config_errors = self._all_device_config_errors[
                device_module_path]
            for error_type, errors in device_config_errors.iteritems():
                print2err("%s count %d:" % (error_type, len(errors)))
                for error in errors:
                    print2err("\t{0}".format(error))
                print2err("\n")
            return None

        DeviceClass, device_class_name, event_classes = import_device(
            device_module_path, device_class_name)
        #print2err("Updated Experiment Device Config:\n\tdevice_class: {0}\n\tdevice_config:{1}\n".format(device_class_name,default_device_config))

        if device_config.get('enable', True):
            self.log("Searching Device Path: %s" % (device_class_name, ))
            self.log("Creating Device: %s" % (device_class_name, ))
            #print2err("Creating Device: %s"%(device_class_name,))

            if DeviceClass._iohub_server is None:
                DeviceClass._iohub_server = self

            if device_class_name != 'Display' and DeviceClass._display_device is None:
                DeviceClass._display_device = ioServer.deviceDict['Display']

            deviceInstance = DeviceClass(dconfig=device_config)

            self.log("Device Instance Created: %s" % (device_class_name, ))
            #print2err("Device Instance Created: %s"%(device_class_name,))

            self.devices.append(deviceInstance)
            ioServer.deviceDict[device_class_name] = deviceInstance

            if 'device_timer' in device_config:
                interval = device_config['device_timer']['interval']
                self.log("%s has requested a timer with period %.5f" %
                         (device_class_name, interval))
                dPoller = DeviceMonitor(deviceInstance, interval)
                self.deviceMonitors.append(dPoller)

            monitoringEventIDs = []
            monitor_events_list = device_config.get('monitor_event_types', [])
            if isinstance(monitor_events_list, (list, tuple)):
                for event_class_name in monitor_events_list:
                    event_id = getattr(
                        EventConstants,
                        convertCamelToSnake(event_class_name[:-5], False))
                    monitoringEventIDs.append(event_id)
            self.log("{0} Instance Event IDs To Monitor: {1}".format(
                device_class_name, monitoringEventIDs))
            #ioHub.print2err("{0} Instance Event IDs To Monitor: {1}".format(device_class_name,eventIDs))

            # add event listeners for streaming events
            if device_config.get('stream_events') is True:
                self.log("Online event access is being enabled for: %s" %
                         device_class_name)
                # add listener for global event queue
                deviceInstance._addEventListener(self, monitoringEventIDs)
                #ioHub.print2err("ioServer event stream listener added: device=%s eventIDs=%s"%(device_class_name,eventIDs))
                self.log(
                    "Standard event stream listener added for ioServer for event ids %s"
                    % (str(monitoringEventIDs), ))
                # add listener for device event queue
                deviceInstance._addEventListener(deviceInstance,
                                                 monitoringEventIDs)
                #  ioHub.print2err("%s event stream listener added: eventIDs=%s"%(device_class_name,eventIDs))
                self.log(
                    "Standard event stream listener added for class %s for event ids %s"
                    % (device_class_name, str(monitoringEventIDs)))

            return deviceInstance, device_config, monitoringEventIDs, event_classes
Example #20
0
    def addDeviceToMonitor(self,device_class_name,device_config):
        device_class_name=str(device_class_name)
        
        self.log("Handling Device: %s"%(device_class_name,))
        #print2err("addDeviceToMonitor:\n\tdevice_class: {0}\n\texperiment_device_config:{1}\n".format(device_class_name,device_config))

        DeviceClass=None
        class_name_start=device_class_name.rfind('.')
        iohub_sub_mod='psychopy.iohub.'
        iohub_submod_path_length=len(iohub_sub_mod)
        device_module_path=iohub_sub_mod+'devices.'
        if class_name_start>0:
            device_module_path="{0}{1}".format(device_module_path,device_class_name[:class_name_start].lower())   
            device_class_name=device_class_name[class_name_start+1:]
        else:
            device_module_path="{0}{1}".format(device_module_path,device_class_name.lower())

        #print2err("Processing device, device_class_name: {0}, device_module_path: {1}".format(device_class_name, device_module_path))
         
        dconfigPath=os.path.join(IO_HUB_DIRECTORY,device_module_path[iohub_submod_path_length:].replace('.',os.path.sep),"default_%s.yaml"%(device_class_name.lower()))

        #print2err("dconfigPath: {0}, device_module_path: {1}\n".format(dconfigPath,device_module_path))
        #print2err("Loading Device Defaults file:\n\tdevice_class: {0}\n\tdeviceConfigFile:{1}\n".format(device_class_name,dconfigPath))
        self.log("Loading Device Defaults file: %s"%(device_class_name,))

        _dclass,default_device_config=load(file(dconfigPath,'r'), Loader=Loader).popitem()

        #print2err("Device Defaults:\n\tdevice_class: {0}\n\tdefault_device_config:{1}\n".format(device_class_name,default_device_config))
        
        self.processDeviceConfigDictionary(device_module_path, device_class_name, device_config,default_device_config)

        if device_module_path in self._all_device_config_errors:
            # Complete device config verification.
            print2err("**** ERROR: DEVICE CONFIG ERRORS FOUND ! NOT LOADING DEVICE: ",device_module_path)
            device_config_errors=self._all_device_config_errors[device_module_path]
            for error_type,errors in device_config_errors.iteritems():
                print2err("%s count %d:"%(error_type,len(errors)))
                for error in errors:
                    print2err("\t{0}".format(error))
                print2err("\n")
            return None
        
        DeviceClass,device_class_name,event_classes=import_device(device_module_path,device_class_name)
        #print2err("Updated Experiment Device Config:\n\tdevice_class: {0}\n\tdevice_config:{1}\n".format(device_class_name,default_device_config))
            
        if device_config.get('enable',True):
            self.log("Searching Device Path: %s"%(device_class_name,))
            self.log("Creating Device: %s"%(device_class_name,))
            #print2err("Creating Device: %s"%(device_class_name,))
            
            if DeviceClass._iohub_server is None:
                DeviceClass._iohub_server=self
            
            if device_class_name != 'Display' and DeviceClass._display_device is None:
                DeviceClass._display_device=ioServer.deviceDict['Display']  
                
            deviceInstance=DeviceClass(dconfig=device_config)

            self.log("Device Instance Created: %s"%(device_class_name,))
            #print2err("Device Instance Created: %s"%(device_class_name,))

            self.devices.append(deviceInstance)
            ioServer.deviceDict[device_class_name]=deviceInstance

            if 'device_timer' in device_config:
                interval = device_config['device_timer']['interval']
                self.log("%s has requested a timer with period %.5f"%(device_class_name, interval))
                dPoller=DeviceMonitor(deviceInstance,interval)
                self.deviceMonitors.append(dPoller)

            monitoringEventIDs=[]
            monitor_events_list=device_config.get('monitor_event_types',[])
            if isinstance(monitor_events_list,(list,tuple)):
                for event_class_name in monitor_events_list:
                    event_id = getattr(EventConstants,convertCamelToSnake(event_class_name[:-5],False))
                    monitoringEventIDs.append(event_id)
            self.log("{0} Instance Event IDs To Monitor: {1}".format(device_class_name,monitoringEventIDs))
            #ioHub.print2err("{0} Instance Event IDs To Monitor: {1}".format(device_class_name,eventIDs))

            # add event listeners for streaming events
            if device_config.get('stream_events') is True:
                self.log("Online event access is being enabled for: %s"%device_class_name)
                # add listener for global event queue
                deviceInstance._addEventListener(self,monitoringEventIDs)
                #ioHub.print2err("ioServer event stream listener added: device=%s eventIDs=%s"%(device_class_name,eventIDs))
                self.log("Standard event stream listener added for ioServer for event ids %s"%(str(monitoringEventIDs),))
                # add listener for device event queue
                deviceInstance._addEventListener(deviceInstance,monitoringEventIDs)
                #  ioHub.print2err("%s event stream listener added: eventIDs=%s"%(device_class_name,eventIDs))
                self.log("Standard event stream listener added for class %s for event ids %s"%(device_class_name,str(monitoringEventIDs)))

            return deviceInstance,device_config,monitoringEventIDs,event_classes
Example #21
0
        print ("Error creating websocket connection to feedback server.")
        return

    runtime = None
    cmd = None
    while 1:
        if cmd is None:
            cmd, data = handleMsgRx(ws)

        if cmd == 'EXPERIMENT_SELECTED':
            active_exp_name = data
            # Create Root Results Folder for all Experiments; if needed
            DataCollectionRuntime.active_exp_name = active_exp_name

            app_conf = load(file(pjoin(configurationDirectory,
                                            "..\\settings\\app_config.yaml"), u'r'),
                                            Loader=Loader)

            app_conf.get('view_server')['address'] = view_server_info['ip']
            app_conf.get('view_server')['port'] = view_server_info['port']

            DataCollectionRuntime.results_root_folder = \
                                            app_conf.get('results_root_folder')
            if not (pexists(DataCollectionRuntime.results_root_folder)
                    and pisdir(DataCollectionRuntime.results_root_folder)):
                DataCollectionRuntime.results_root_folder = abspath(pjoin(
                    DataCollectionRuntime.script_dir,
                    DataCollectionRuntime.results_root_folder))
            util.createPath(DataCollectionRuntime.results_root_folder)

            cmd = None
Example #22
0
from numpy import (sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad,
                   rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding
import pylink  # Still waiting on account activation, which is weird that I need it but whatever

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(
    sys.getfilesystemencoding())
os.chdir(_thisDir)

# Load the specified iohub configuration file
# converting it to a python dict.
#
io_config = load(file('./SRR_eyelink_std.yaml', 'r'), Loader=Loader)

# Add / Update the session code to be unique. Here we use the psychopy
# getDateStr() function for session code generation
#
session_info = io_config.get('data_store').get('session_info')
session_info.update(code="S_%s" % (getDateStr()))

# Create an ioHubConnection instance, which starts the ioHubProcess, and
# informs it of the requested devices and their configurations.
#
io = ioHubConnection(io_config)

keyboard = io.devices.keyboard
eyetracker = io.devices.tracker
Example #23
0
def run(rootScriptPathDir,configFilePath):
    psychopy.iohub.EXP_SCRIPT_DIRECTORY = rootScriptPathDir

    import tempfile
    tdir=tempfile.gettempdir()
    cdir,cfile=os.path.split(configFilePath)
    if tdir==cdir:
        tf=open(configFilePath)
        ioHubConfig=json.loads(tf.read())
        tf.close()
        os.remove(configFilePath)
    else:
        ioHubConfig=load(open(configFilePath,'r'), Loader=Loader)

    hub_defaults_config=load(open(os.path.join(psychopy.iohub.IO_HUB_DIRECTORY,'default_config.yaml'),'r'), Loader=Loader)
    updateDict(ioHubConfig,hub_defaults_config)
    try:
        s = ioServer(rootScriptPathDir, ioHubConfig)
    except Exception as e:
        printExceptionDetailsToStdErr()
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except Exception:
            pass
        
        return -1
    
    try:
        s.log('Receiving datagrams on :9000')
        s.udpService.start()


        if Computer.system == 'win32':
            gevent.spawn(s.pumpMsgTasklet, s.config.get('windows_msgpump_interval', 0.00375))

        if hasattr(gevent,'run'):
            for m in s.deviceMonitors:
                m.start()
    
            gevent.spawn(s.processEventsTasklet, 0.01)

            sys.stdout.write("IOHUB_READY\n\r\n\r")

            #print2err("Computer.psychopy_process: ", Computer.psychopy_process)
            if Computer.psychopy_process:
                gevent.spawn(s.checkForPsychopyProcess, 0.5)

            sys.stdout.flush()
            
            gevent.run()
        else:
            glets=[]
            if Computer.system == 'win32':
                glets.append(gevent.spawn(s.pumpMsgTasklet, s.config.get('windows_msgpump_interval', 0.00375)))

            for m in s.deviceMonitors:
                m.start()
                glets.append(m)
            glets.append(gevent.spawn(s.processEventsTasklet,0.01))
    
            sys.stdout.write("IOHUB_READY\n\r\n\r")
            sys.stdout.flush()

            #print2err("Computer.psychopy_process: ", Computer.psychopy_process)
            if Computer.psychopy_process:
                 glets.append(gevent.spawn(s.checkForPsychopyProcess, 0.5))

            gevent.joinall(glets)
            

        s.log("Server END Time Offset: {0}".format(Computer.global_clock.getLastResetTime()),'DEBUG')

    except Exception as e:
        print2err("Error occurred during ioServer.start(): ",str(e))
        printExceptionDetailsToStdErr()
        print2err("------------------------------")

        sys.stdout.write("IOHUB_FAILED\n\r\n\r")
        sys.stdout.flush()
        
        try:
            s.shutdown()
        except Exception:
            pass
    
    return -1