Esempio n. 1
0
 def start(self):
     """
     The start method should be called by the main prtion of your experiment script. This method simply wraps a call
     to the run method in an exception handler that tries to ensure any error that occurs is printed out in detail,
     and that the ioHub server process is terminates even in the case of an expection have may not been handled
     explicitedly in your scipt.
     """
     try:
         self.run()
     except ioHub.ioHubError("Error running experimeniment."):
         self.printExceptionDetails()
     finally:
         # _close ioHub, shut down ioHub process, clean-up.....
         self._close()
Esempio n. 2
0
 def start(self):
     """
     The start method should be called by the main prtion of your experiment script. This method simply wraps a call
     to the run method in an exception handler that tries to ensure any error that occurs is printed out in detail,
     and that the ioHub server process is terminates even in the case of an expection have may not been handled
     explicitedly in your scipt.
     """
     try:
         self.run()
     except ioHub.ioHubError("Error running experimeniment."):
         self.printExceptionDetails()
     finally:
         # _close ioHub, shut down ioHub process, clean-up.....
         self._close()
Esempio n. 3
0
 def addEventTrigger(self,trigger):
     if isinstance(trigger,Trigger):
         self.event_triggers.append(trigger)
     else:
         raise ioHub.ioHubError("Triggers added to a screen state object must be of type DeviceEventTrigger.")
Esempio n. 4
0
    def __init__(self, initial_time_offset, rootScriptPathDir, config=None):
        import ioHub
        Computer.isIoHubProcess=True
        Computer.globalClock=ioHub.ioClock(None,initial_time_offset)
        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={}        
        ioServer.eventBuffer=deque(maxlen=config.get('global_event_buffer',2048))
        ioServer._logMessageBuffer=deque(maxlen=128)

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

        # read temp paths file
        ioHub.data_paths=None
        try:
            expJsonPath=os.path.join(rootScriptPathDir,'exp.paths')
            f=open(expJsonPath,'r')
            ioHub.data_paths=msgpack.loads(f.read())
            f.flush()
            f.close()
            os.remove(expJsonPath)
        except:
            pass

        #ioHub.print2err("#### ioHub.data_paths: ",ioHub.data_paths)
        self._all_device_config_errors=dict()
        device_instance_list=[]
        try:
            #built device list and config from yaml config settings
            for iodevice in config.get('monitor_devices',()):
                for device_class_name,deviceConfig in iodevice.iteritems():
                    #ioHub.print2err("======================================================")
                    #ioHub.print2err("Started load process for: {0}".format(device_class_name))
                    device_instance_and_config=self.addDeviceToMonitor(device_class_name,deviceConfig)
                    if device_instance_and_config:
                        device_instance_list.append(device_instance_and_config)
                    else:
                        ioHub.print2err('## Device was not started by the ioHub Server: ',device_class_name)
                        raise ioHub.ioHubError("Device config validation failed")
            DeviceConstants.addClassMappings()
            EventConstants.addClassMappings()
        except:
            ioHub.print2err("Error during device creation ....")
            ioHub.printExceptionDetailsToStdErr()
            raise ioHub.ioHubError("Error during device creation ....")

        try:
            # dataStore setup
            if 'data_store' in config:
                experiment_datastore_config=config.get('data_store')

                default_datastore_config_path=os.path.join(ioHub.IO_HUB_DIRECTORY,'ioDataStore','default_iodatastore.yaml')
                _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
                
                #ioHub.print2err("Merged ioDataStoreConfig: {0}".format(experiment_datastore_config))
                
                if experiment_datastore_config.get('enable', True):
                    #ioHub.print2err("Creating ioDataStore....")

                    if ioHub.data_paths is None:
                        resultsFilePath=rootScriptPathDir
                    else:
                        resultsFilePath=ioHub.data_paths[u'IOHUB_DATA']
                    self.createDataStoreFile(experiment_datastore_config.get('filename','events')+'.hdf5',resultsFilePath,'a',experiment_datastore_config)

                    #ioHub.print2err("Created ioDataStore.")

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


        self.log("Adding ioServer and DataStore event listeners......")

        # add event listeners for saving events
        if self.emrt_file is not None:
            for device_instance,device_instance_config,eventIDs in device_instance_list:
                if device_instance_config['save_events']:
                    device_instance._addEventListener(self.emrt_file,eventIDs)
                    self.log("DataStore listener for device added: device: %s eventIDs: %s"%(device_instance.__class__.__name__,eventIDs))
                    #ioHub.print2err("DataStore listener for device added: device: %s eventIDs: %s"%(device_instance.__class__.__name__,eventIDs))
                else:
                    #ioHub.print2err("DataStore saving disabled for device: %s"%(device_instance.__class__.__name__,))
                    self.log("DataStore saving disabled for device: %s"%(device_instance.__class__.__name__,))
        else:
            #ioHub.print2err("DataStore Not Evabled. No events will be saved.")
            self.log("DataStore Not Enabled. No events will be saved.")
    
#        try:
#            #built filter graph and config from yaml config settings
#            for iofilters in config.get('filters',()):
#                for filter_class,filterConfig in iofilters.iteritems():
#                    self.addFilterToMonitor(filter_class,filterConfig)
#        except:
#            ioHub.print2err("Error during filter creation ....")
#            ioHub.printExceptionDetailsToStdErr()

        deviceDict=ioServer.deviceDict
        iohub=self
        if ('Mouse' in deviceDict or 'Keyboard' in deviceDict):
            if Computer.system == 'win32':           
                iohub.log("Creating pyHook Monitors....")
                #ioHub.print2err("Creating pyHook Monitors....")

                class pyHookDevice(object):
                    def __init__(self):
                        import pyHook
                        self._hookManager=pyHook.HookManager()
                        
                        if 'Mouse' in deviceDict:
                            #ioHub.print2err("Hooking Mouse.....")
                            self._hookManager.MouseAll = deviceDict['Mouse']._nativeEventCallback
                            self._hookManager.HookMouse()    
                        if 'Keyboard' in deviceDict:
                            #ioHub.print2err("Hooking Keyboard.....")
                            self._hookManager.KeyAll = deviceDict['Keyboard']._nativeEventCallback
                            self._hookManager.HookKeyboard()

                        iohub.log("WindowsHook PumpEvents Periodic Timer Created.")
            
                    def _poll(self):
                        import pythoncom
                        # PumpWaitingMessages returns 1 if a WM_QUIT message was received, else 0
                        if pythoncom.PumpWaitingMessages() == 1:
                            raise KeyboardInterrupt()               
    
                #ioHub.print2err("Creating pyHook Monitor......")

                hookMonitor=DeviceMonitor(pyHookDevice(),0.00375)
                self.deviceMonitors.append(hookMonitor)
                
                #ioHub.print2err("Created pyHook Monitor.")
                
            elif Computer.system == 'linux2':
                # TODO: consider switching to xlib-ctypes implementation of xlib
                # https://github.com/garrybodsworth/pyxlib-ctypes
                iohub.log("Creating pyXHook Monitors....")
                import ioHub.devices.pyXHook
                
                self._hookManager = ioHub.devices.pyXHook.HookManager()
                if 'Keyboard' in deviceDict:
                    ioHub.print2err("Hooking Keyboard.....")
                    self._hookManager.HookKeyboard()
                    self._hookManager.KeyDown = deviceDict['Keyboard']._nativeEventCallback
                    self._hookManager.KeyUp = deviceDict['Keyboard']._nativeEventCallback
                if 'Mouse' in deviceDict:                
                    ioHub.print2err("Hooking Mouse.....")
                    self._hookManager.HookMouse()
                    self._hookManager.MouseAllButtonsDown = deviceDict['Mouse']._nativeEventCallback
                    self._hookManager.MouseAllButtonsUp = deviceDict['Mouse']._nativeEventCallback
                    self._hookManager.MouseAllMotion = deviceDict['Mouse']._nativeEventCallback

                #ioHub.print2err("Starting pyXHook.HookManager.....")
                self._hookManager.start()
                iohub.log("pyXHook Thread Created.")
                #ioHub.print2err("pyXHook.HookManager thread created.")

            else: # OSX
                if 'Mouse' in deviceDict:
                    mouseHookMonitor=DeviceMonitor(deviceDict['Mouse'],0.004)
                    self.deviceMonitors.append(mouseHookMonitor)
                    deviceDict['Mouse']._CGEventTapEnable(deviceDict['Mouse']._tap, True)

                if 'Keyboard' in deviceDict:
                    kbHookMonitor=DeviceMonitor(deviceDict['Keyboard'],0.004)
                    self.deviceMonitors.append(kbHookMonitor)
                    deviceDict['Keyboard']._CGEventTapEnable(deviceDict['Keyboard']._tap, True)

#                import ioHub.devices.pyXHook
#                
#                self._hookManager = ioHub.devices.pyXHook.HookManager()
#                if 'Keyboard' in deviceDict:
#                    ioHub.print2err("Hooking Keyboard.....")
#                    self._hookManager.HookKeyboard()
#                    self._hookManager.KeyDown = deviceDict['Keyboard']._nativeEventCallback
#                    self._hookManager.KeyUp = deviceDict['Keyboard']._nativeEventCallback
#                if 'Mouse' in deviceDict:                
#                    ioHub.print2err("Hooking Mouse.....")
#                    self._hookManager.HookMouse()
#                    self._hookManager.MouseAllButtonsDown = deviceDict['Mouse']._nativeEventCallback
#                    self._hookManager.MouseAllButtonsUp = deviceDict['Mouse']._nativeEventCallback
#                    self._hookManager.MouseAllMotion = deviceDict['Mouse']._nativeEventCallback
#
#                #ioHub.print2err("Starting pyXHook.HookManager.....")
#                self._hookManager.start()
#                iohub.log("pyXHook Thread Created.")
                #ioHub.print2err("pyXHook.HookManager thread created.")
                  
        self.log("Time Offset: {0}".format(initial_time_offset))