Beispiel #1
0
 def clearEvents(self):
     try:
         self._non_touch_events.clear()
         self._flushSerialInput()
         TouchDevice.clearEvents(self)
     except Exception, e:
         print2err("Exception During Touch.clearEvents: ",str(e))
Beispiel #2
0
 def initCalibration(self):
     try:
         # set flag indicating raw touch coords should be used in touch events, as 
         # data is not calibrated
         self.clearEvents()
         self._raw_positions=True
         
         # To acquire calibration points, controller must be in raw coordinate
         # mode. We use the point of untouch as our calibration point. */
 
         # Get current Mode settings
         pkt=self._query('m')
         reply_packets=self._poll()
         
         # Set Mode to utouch events only
         pkt=self._command('M',*(132,))
         reply_packets=self._poll()
 
         # Get current swap-axis state
         pkt=self._query('c',*(0,True))
         reply_packets=self._poll()
 
         # Disable swap-axis
         pkt=self._command('C',*(0,0,0,0,0,0,False))
         reply_packets=self._poll()
         
         # Get current mode settings
         pkt=self._query('m')
         reply_packets=self._poll()
     except Exception, e:
         print2err("Exception During Touch.initCalibration: ",str(e))
Beispiel #3
0
def addDirectoryToPythonPath(path_from_iohub_root,leaf_folder=''):
    dir_path=os.path.join(IO_HUB_DIRECTORY,path_from_iohub_root,sys.platform,"python{0}{1}".format(*sys.version_info[0:2]),leaf_folder)
    if os.path.isdir(dir_path) and dir_path not in sys.path:
        sys.path.append(dir_path)  
    else:
        print2err("Could not add path: ",dir_path)
        dir_path=None
    return dir_path
Beispiel #4
0
def addDirectoryToPythonPath(path_from_iohub_root, leaf_folder=''):
    dir_path = os.path.join(IO_HUB_DIRECTORY, path_from_iohub_root,
                            sys.platform,
                            "python{0}{1}".format(*sys.version_info[0:2]),
                            leaf_folder)
    if os.path.isdir(dir_path) and dir_path not in sys.path:
        sys.path.append(dir_path)
    else:
        print2err("Could not add path: ", dir_path)
        dir_path = None
    return dir_path
Beispiel #5
0
 def _pixelToDisplayCoords(self,px,py):
     """
     Converts 0,0,pix_width,pix_height coord space to display device coord space.  
     """
     try:
         dw,dh=self._display_device.getPixelResolution()
         rx=px/float(dw)
         ry=py/float(dh)
         left,top,right,bottom=self._display_device.getCoordBounds()
         w,h=right-left,top-bottom            
         x,y=left+w*rx,bottom+h*(1.0-ry) 
         return x,y
     except:
         print2err("Error During EloDevice._pixelToDisplayCoords:") 
         printExceptionDetailsToStdErr()
         return px,py
Beispiel #6
0
    def _pixelToDisplayCoords(self,px,py):
        """
        Converts 0,0,pix_width,pix_height coord space to display device coord space.  
        """
        try:
            #print '------'
            '''
            dw,dh=self._display_device.getPixelResolution()
            # Relative display positions
            rx=px/float(dw)
            ry=py/float(dh)
            print 'rx = ', px, '/', float(dw), '=', rx
            print 'ry = ', py, '/', float(dh), '=', ry

            # Touch coordinate width and height
            left,top,right,bottom=self._display_device.getCoordBounds()
            print 'left', left, 'top', top, 'right', right, 'bottom', bottom
            w,h=right-left,top-bottom
            print 'w', w, 'h', h

            # Calculate touch coordinates in display pixel coordinates
            x, y = left+w*rx, bottom+h*(1.0-ry) 
            print left, '+', w, '*', rx, '=', x
            print bottom, '+', h, '* (1.0-', ry, ') =', y
            return x,y
            '''


            dw,dh=self._display_device.getPixelResolution()
            left,top,right,bottom=self._display_device.getCoordBounds()
            w, h = right-left, top-bottom
            rx, ry = (px-left)/float(w), (py-bottom)/float(h)  # Relative touch positions
            rx = abs(1-rx)  # Flip X axis
            def _crop(v):
                return min(max(v, 0.0), 1.0)
            rx = _crop(rx)
            ry = _crop(ry)
            #print 'rx', rx, 'ry', ry

            #print dw*rx, dh*ry
            x, y = dw*rx, dh*ry
            #print 'x', x, 'y', y
            return x, y
        except:
            print2err("Error During EloDevice._pixelToDisplayCoords:") 
            printExceptionDetailsToStdErr()
            return px,py
Beispiel #7
0
    def getPositionAndDelta(self):
        """
        Returns a tuple of tuples, being the current position of the 
        ioHub Touch Device as an (x,y) tuple, and the amount the touch position 
        changed the last time it was updated (dx,dy).
        Touch Position and Delta are in display coordinate units.

        Args: 
            None
		
        Returns: 
            tuple: ( (x,y), (dx,dy) ) position of the touch event, change in touch position, both in Display coordinate space.
        """
        try:
            cpos=self._position
            lpos=self._lastPosition
            change_x=cpos[0]-lpos[0]
            change_y=cpos[1]-lpos[1]
            return cpos, (change_x,change_y)

        except Exception, e:
            print2err(">>ERROR getPositionAndDelta: "+str(e))
            printExceptionDetailsToStdErr()
            return (0.0,0.0),(0.0,0.0)
Beispiel #8
0
def _localFunc():
    return None

global IO_HUB_DIRECTORY
IO_HUB_DIRECTORY=module_directory(_localFunc)

import devices
from devices import Computer, import_device, DeviceEvent, Device

_DATA_STORE_AVAILABLE=False
try:
    import datastore
    _DATA_STORE_AVAILABLE=True
except Exception, e:
    print2err("WARNING: ioHub DataStore could not be loaded. DataStore functionality will be disabled. Error: ")
    printExceptionDetailsToStdErr()

import client
from client import ioHubConnection, launchHubServer, ioHubExperimentRuntime


from util import Trigger, TimeTrigger, DeviceEventTrigger
from util import ScreenState, ClearScreen, InstructionScreen, ImageScreen
from util import ExperimentVariableProvider, SinusoidalMotion, to_numeric
from util.targetpositionsequence import TargetStim, PositionGrid, TargetPosSequenceStim, ValidationProcedure

def _start(**kwargs):
    """
    Do not use this method. Incomplete. May go away.
Beispiel #9
0
    return None


global IO_HUB_DIRECTORY
IO_HUB_DIRECTORY = module_directory(_localFunc)

import devices
from devices import Computer, import_device, DeviceEvent, Device

_DATA_STORE_AVAILABLE = False
try:
    import datastore
    _DATA_STORE_AVAILABLE = True
except Exception, e:
    print2err(
        "WARNING: ioHub DataStore could not be loaded. DataStore functionality will be disabled. Error: "
    )
    printExceptionDetailsToStdErr()

import client
from client import ioHubConnection, launchHubServer, ioHubExperimentRuntime

from util import Trigger, TimeTrigger, DeviceEventTrigger
from util import ScreenState, ClearScreen, InstructionScreen, ImageScreen
from util import ExperimentVariableProvider, SinusoidalMotion, to_numeric
from util.targetpositionsequence import TargetStim, PositionGrid, TargetPosSequenceStim, ValidationProcedure


def _start(**kwargs):
    """
    Do not use this method. Incomplete. May go away.
Beispiel #10
0
    def _poll(self):
        """
        Checks for any new Touch Response Packets...
        """
        try:
            poll_time=currentSec()
            self._rx()
            while self._rx_data or self._serial_port_hw.inWaiting():
                self._rx(num_bytes=self._serial_port_hw.inWaiting())
                while self._rx_data:
                    while self._rx_data and self._rx_data[0]!=self.LEAD_IN_BYTE:
                        #print2err('Non LEAD_IN_BYTE: ',ord(self._rx_data[0]))
                        self._rx_data=self._rx_data[1:]
                    rx_size=len(self._rx_data)
                    
                    if rx_size<10:
                        self._rx(num_bytes=10-len(self._rx_data))
                        if len(self._rx_data)<10:
                            self._last_poll_time=poll_time
                            #print2err('Poll < 10 bytes: ',currentSec()-poll_time)
                            return self._non_touch_events
                            
                    if self._rx_data[0]=='U' and self._rx_data[1] == 'T':
                        response_class=RESPONSE_PACKET_TYPES.get('T')
                        touch_event=response_class(poll_time,bytearray(self._rx_data[:10]))
                        #print2err('packet_bytes: ',[b for b in touch_event._packet_bytes])
                        self._rx_data=self._rx_data[10:]
                        if touch_event._valid_response is True:
                            etype=EventConstants.TOUCH_MOVE
                            if touch_event.touch_type==touch_event.TOUCH_PRESS:                    
                                etype=EventConstants.TOUCH_PRESS
                            elif touch_event.touch_type==touch_event.TOUCH_RELEASE:
                                etype=EventConstants.TOUCH_RELEASE
                            confidence_interval=poll_time-self._last_poll_time # confidence interval                    
                            # TODO: Calculate Delay more accurately if possible                    
                            delay=poll_time-touch_event.time # delay   
                            # TODO: Set Display ID correctly                    
                            display_id=0
        
                            self._lastPosition=self._position
                            if self._raw_positions is True or self.force_uncalibrated:
                                self._position=touch_event.x,touch_event.y
                            else:
                                self._position=self._pixelToDisplayCoords(touch_event.x,touch_event.y)
                            
                            event =[            
                                    0, # exp id
                                    0, # session id
                                    0, #device id (not currently used)
                                    0, # event id
                                    etype, # event type
                                    touch_event.time, # device time
                                    poll_time, # logged time
                                    touch_event.time, # hub time
                                    confidence_interval, # confidence interval
                                    delay, # delay
                                    0, # filter_id
                                    display_id,
                                    self._position[0],
                                    self._position[1],
                                    touch_event.z
                                    ]
        
                            #print2err('Poll TouchEvent: ',currentSec()-poll_time)
                            self._addNativeEventToBuffer(event)
                    elif self._rx_data[0]=='U': 
                        response_class=RESPONSE_PACKET_TYPES.get(self._rx_data[1])
                        # TODO: Checksum validation should be done here.
                        if response_class:
                            rc=response_class(poll_time,bytearray(self._rx_data[:10]))
                            self._rx_data=self._rx_data[10:]
                            if rc._valid_response is True:
                                self._non_touch_events.append(rc)
                            else:
                                print2err("Invalid Response:",rc.asdict())
                        else:
                            print2err('Warning: UNHANDLED RX PACKET TYPE: %d %s'%(poll_time,str([c for c in self._rx_data[:10]])))
                            self._rx_data=self._rx_data[10:]
                        #print2err('Poll Non TouchEvent: ',currentSec()-poll_time)

#            if self._non_touch_events or touch_event_received:
#                print2err('Poll end: %.6f %.6f'%(currentSec()-poll_time,poll_time-self._last_poll_time))
            self._last_poll_time=poll_time
            return self._non_touch_events
        except:
            print2err("Exception During Touch._poll: ")
            printExceptionDetailsToStdErr()            
Beispiel #11
0
 def applyCalibrationData(self,xmin,xmax,ymin,ymax,x1,y1,x2,y2,sx,sy,leftx,uppery,rightx,lowery):
     # set calibration and scaling params on controller */
     try:
         # compute number of touch points per screen coordinate */
         xunit = (x2-x1) / (rightx-leftx)
         yunit = (y2-y1) / (lowery-uppery)
 
         #/* extrapolate the calibration points to corner points of screen image */
         xhigh = x2 + (xunit * (xmax-rightx))
         xlow = x1 - (xunit * (leftx-xmin))
         if xlow < 1:
             xlow = 1
         if xhigh < 1:
             xhigh = 1 # in case axis inverted */
         yhigh = y2 + (yunit * (ymax - lowery))
         ylow = y1 - (yunit * (uppery - ymin))
         if ylow < 1: 
             ylow = 1
         if yhigh < 1: 
             yhigh = 1
 
         # detect touchscreen orientation corrections */
         xyswap = math.fabs(sx-x1) < math.fabs(sy-y1)
 
         #xinv = xhigh < xlow
         #yinv = yhigh < ylow
 
         # set calibration x, y data        
         pkt=self._command('C',*('X',xlow,xhigh,0,0,0,False))
         reply_packets=self._poll()
 
         pkt=self._command('C',*('Y',ylow,yhigh,0,0,0,False))
         reply_packets=self._poll()
         
         # set swap_axis flag       
         pkt=self._command('C',*(0,0,0,0,0,0,xyswap))
         reply_packets=self._poll()
     
         # set scaling .....
         pkt=self._command('S',*('X',xmin,xmax))
         reply_packets=self._poll()
 
         # set scaling .....
         pkt=self._command('S',*('Y',ymin,ymax))
         reply_packets=self._poll()       
         
         # Change mode to send touch, untouch, and touch movement events
         pkt=self._command('M',*( 199,14))
         reply_packets=self._poll()
 
         # Get current Mode settings
         pkt=self._query('m')
         reply_packets=self._poll()
 
         # set flag indicating calibrated touch coords should be 
         # used in touch events, as data is not calibrated
         self.clearEvents()
         self._raw_positions=False
         
     except Exception, e:
         print2err("Exception During Touch.applyCalibrationData: ",str(e))