File: PsychHIDKbQueueCheck.c

package info (click to toggle)
psychtoolbox-3 3.0.9%2Bsvn2579.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 63,408 kB
  • sloc: ansic: 73,310; cpp: 11,139; objc: 3,129; sh: 1,669; python: 382; php: 272; makefile: 172; java: 113
file content (233 lines) | stat: -rw-r--r-- 9,894 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
	PsychtoolboxGL/Source/Common/PsychHID/PsychHIDKbQueueCheck.c		
  
	PROJECTS: 
	
		PsychHID only.
  
	PLATFORMS:  
	
		All.  
  
	AUTHORS:
	
		rwoods@ucla.edu		rpw 
        mario.kleiner@tuebingen.mpg.de      mk
      
	HISTORY:
		8/19/07  rpw		Created.
		8/23/07  rpw        Added PsychHIDQueueFlush to documentation; removed call to PsychHIDVerifyInit()
  
	NOTES:
	
		The routines PsychHIDKbQueueCreate, PsychHIDKbQueueStart, PsychHIDKbQueueCheck, PsychHIDKbQueueStop
		and PsychHIDKbQueueRelease comprise a replacement for PsychHIDKbCheck, providing the following
		advantages:
		
			1) Brief key presses that would be missed by PsychHIDKbCheck are reliably detected
			2) The times of key presses are recorded more accurately
			3) Key releases are also recorded
		
		Requires Mac OS X 10.3 or later. The Matlab wrapper functions (KbQueueCreate, KbQueueStart,
		KbQueueCheck, KbQueueStop and KbQueueRelease screen away Mac OS X 10.2 and earlier, and the C code 
		does nothing to verify the Mac OS X version.
		
		Only a single device can be monitored at any given time. The deviceNumber can be specified only
		in the call to PsychHIDKbQueueCreate. The other routines then relate to that specified device. If
		deviceNumber is not specified, the first device is the default (like PyschHIDKbCheck). If
		PsychHIDKbQueueCreate has not been called first, the other routines will generate an error 
		message. Likewise, if PsychHIDKbQueueRelease has been called more recently than PsychHIDKbQueueCreate,
		the other routines will generate error messages.
		
		It is acceptable to cal PsychHIDKbQueueCreate at any time (e.g., to switch to a new device) without
		calling PsychKbQueueRelease.
		
		PsychHIDKbQueueCreate:
			Creates the queue for the specified (or default) device number
			No events are delivered to the queue until PsychHIDKbQueueStart is called
			Can be called again at any time
			
		PsychHIDKbQueueStart:
			Starts delivering keyboard events from the specified device to the queue
			
		PsychHIDKbQueueStop:
			Stops delivery of new keyboard events from the specified device to the queue.
			Data regarding events already queued is not cleared and can be recovered by PsychHIDKbQueueCheck
			
		PsychHIDKbQueueCheck:
			Obtains data about keypresses on the specified device since the most recent call to
			this routine or to PsychHIDKbQueueStart
			
			Clears all currently scored events (unscored events may still be in the queue)
			
		PsychHIDKbQueueFlush:
			Flushes unscored events from the queue and zeros all previously scored events
			
		PsychHIDKbQueueRelease:
			Releases queue-associated resources; once called, PsychHIDKbQueueCreate must be invoked
			before using any of the other routines
			
			This routine is called automatically at clean-up and can be omitted at the potential expense of
			keeping memory allocated unnecesarily
				

		---

*/

#include "PsychHID.h"
 
PsychError PSYCHHIDKbQueueCheck(void) 
{
	static char useString[]= "[keyIsDown, firstKeyPressTimes, firstKeyReleaseTimes, lastKeyPressTimes, lastKeyReleaseTimes]=PsychHID('KbQueueCheck' [, deviceIndex])";
	static char synopsisString[] = 
		"Checks a queue for keyboard or button events generated by a device.\n"
        "PsychHID('KbQueueCreate') must be called before this routine "
        "and PsychHID('KbQueueStart') must then be called for any events "
		"to be returned.\n"
        "On Linux and Windows, the optional 'deviceIndex' is the index of the device whose queue should be checked. "
        "If omitted, the default devices queue will be checked. On other systems, the last queue will be checked.\n";        

	static char seeAlsoString[] = "KbQueueCreate, KbQueueStart, KbQueueStop, KbQueueFlush, KbQueueRelease";

    int deviceIndex;
    
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};

    PsychErrorExit(PsychCapNumOutputArgs(5));
    PsychErrorExit(PsychCapNumInputArgs(1));

    deviceIndex = -1;
    PsychCopyInIntegerArg(1, kPsychArgOptional, &deviceIndex);

    PsychHIDOSKbQueueCheck(deviceIndex);
    
    return(PsychError_none);
}

PsychError PSYCHHIDKbQueueGetEvent(void)
{
	static char useString[]= "[event, navail] = PsychHID('KbQueueGetEvent' [, deviceIndex][, maxWaitTimeSecs=0])";
	static char synopsisString[] = 
		"Checks a queue for keyboard or button events generated by a device.\n"
		"If there are any events queued, the oldest one is returned in the struct "
		"'event', otherwise an empty matrix is returned. The number of queued events "
		"remaining in the queue after fetching is returned in 'navail'.\n"
		"'maxWaitTimeSecs' is an optional maximum wait time for a new event in seconds. "
		"It defaults to zero, which means to just poll for a pending event. A positive value "
		"will wait until either at least one event arrived or the given amount of time elapses, "
		"whatever comes first.\n"
		"The returned event struct, if any, currently contains the following fields:\n"
		"'Keycode' = The KbCheck / KbName style keycode of the key or button that triggered this event.\n"
		"'Time' = The GetSecs time of when the event was received.\n"
		"'Pressed' = 1 for a key press event, 0 for a key release event.\n"
		"'CookedKey' = Keycode translated into a GetChar() style ASCII character code. Or zero if key "
		"does not have a corresponding character. Or -1 if mapping is unsupported for given event.\n\n"
        "PsychHID('KbQueueCreate') must be called before this routine and PsychHID('KbQueueStart') "
        "must then be called for any events to get recorded into the event buffer.\n"
        "On Linux and Windows, the optional 'deviceIndex' is the index of the device whose queue should be checked. "
        "If omitted, the default devices queue will be checked. On other systems, the last queue will be checked.\n";        

	static char seeAlsoString[] = "KbQueueCreate, KbQueueStart, KbQueueStop, KbQueueFlush, KbQueueRelease";

    int deviceIndex;
	unsigned int navail;
	double maxWaitTimeSecs;
	
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};

    PsychErrorExit(PsychCapNumOutputArgs(2));
    PsychErrorExit(PsychCapNumInputArgs(2));

    deviceIndex = -1;
    PsychCopyInIntegerArg(1, kPsychArgOptional, &deviceIndex);

	maxWaitTimeSecs = 0;
	PsychCopyInDoubleArg(2, kPsychArgOptional, &maxWaitTimeSecs);
	
	// Get next event from buffer, return it as 1st return argument:
    navail = PsychHIDReturnEventFromEventBuffer((PSYCH_SYSTEM != PSYCH_OSX) ? deviceIndex : 0, 1, maxWaitTimeSecs);
    PsychCopyOutDoubleArg(2, FALSE, (double) navail);

    return(PsychError_none);
}

#if PSYCH_SYSTEM == PSYCH_OSX
#include "PsychHIDKbQueue.h"

extern AbsoluteTime *psychHIDKbQueueFirstPress;
extern AbsoluteTime *psychHIDKbQueueFirstRelease;
extern AbsoluteTime *psychHIDKbQueueLastPress;
extern AbsoluteTime *psychHIDKbQueueLastRelease;
extern pthread_mutex_t psychHIDKbQueueMutex;

static double convertTime(AbsoluteTime at){
	Nanoseconds timeNanoseconds=AbsoluteToNanoseconds(at);
	UInt64 timeUInt64=UnsignedWideToUInt64(timeNanoseconds);
	double timeDouble=(double)timeUInt64;
	return timeDouble / 1000000000;
}

void PsychHIDOSKbQueueCheck(int deviceIndex)
{
	double *hasKeyBeenDownOutput, *firstPressTimeOutput, *firstReleaseTimeOutput, *lastPressTimeOutput, *lastReleaseTimeOutput;
	psych_bool isFirstPressSpecified, isFirstReleaseSpecified, isLastPressSpecified, isLastReleaseSpecified;

	if(!psychHIDKbQueueFirstPress || !psychHIDKbQueueFirstRelease || !psychHIDKbQueueLastPress || !psychHIDKbQueueLastRelease){
		PsychErrorExitMsg(PsychError_user, "Queue has not been created.");
	}
	
	// Allocate output
    PsychAllocOutDoubleArg(1, FALSE, &hasKeyBeenDownOutput);
	isFirstPressSpecified = PsychAllocOutDoubleMatArg(2, FALSE, 1, 256, 1, &firstPressTimeOutput);
	isFirstReleaseSpecified = PsychAllocOutDoubleMatArg(3, FALSE, 1, 256, 1, &firstReleaseTimeOutput);
	isLastPressSpecified = PsychAllocOutDoubleMatArg(4, FALSE, 1, 256, 1, &lastPressTimeOutput);
	isLastReleaseSpecified = PsychAllocOutDoubleMatArg(5, FALSE, 1, 256, 1, &lastReleaseTimeOutput);

	// Initialize output
	if(isFirstPressSpecified) memset((void*) firstPressTimeOutput, 0, sizeof(double) * 256);
	if(isFirstReleaseSpecified) memset((void*) firstReleaseTimeOutput, 0, sizeof(double) * 256);
	if(isLastPressSpecified) memset((void*) lastPressTimeOutput, 0, sizeof(double) * 256);
	if(isLastReleaseSpecified) memset((void*) lastReleaseTimeOutput, 0, sizeof(double) * 256);
	
	*hasKeyBeenDownOutput=0;
	pthread_mutex_lock(&psychHIDKbQueueMutex);

	// Compute output
	{
		int i;
		for(i=0; i<256; i++){
			AbsoluteTime lastRelease=psychHIDKbQueueLastRelease[i];
			AbsoluteTime lastPress=psychHIDKbQueueLastPress[i];
			AbsoluteTime firstRelease=psychHIDKbQueueFirstRelease[i];
			AbsoluteTime firstPress=psychHIDKbQueueFirstPress[i];
			
			if(firstPress.hi!=0 || firstPress.lo!=0){
				*hasKeyBeenDownOutput=1;
				if(isFirstPressSpecified) firstPressTimeOutput[i]=convertTime(firstPress);
				psychHIDKbQueueFirstPress[i].hi=0;
				psychHIDKbQueueFirstPress[i].lo=0;
			}
			if(firstRelease.hi!=0 || firstRelease.lo!=0){
				if(isFirstReleaseSpecified) firstReleaseTimeOutput[i]=convertTime(firstRelease);
				psychHIDKbQueueFirstRelease[i].hi=0;
				psychHIDKbQueueFirstRelease[i].lo=0;
			}
			if(lastPress.hi!=0 || lastPress.lo!=0){
				if(isLastPressSpecified) lastPressTimeOutput[i]=convertTime(lastPress);
				psychHIDKbQueueLastPress[i].hi=0;
				psychHIDKbQueueLastPress[i].lo=0;
			}
			if(lastRelease.hi!=0 || lastRelease.lo!=0){
				if(isLastReleaseSpecified) lastReleaseTimeOutput[i]=convertTime(lastRelease);
				psychHIDKbQueueLastRelease[i].hi=0;
				psychHIDKbQueueLastRelease[i].lo=0;
			}
		}
	}
	pthread_mutex_unlock(&psychHIDKbQueueMutex);
}

#endif