aboutsummaryrefslogtreecommitdiff
path: root/rawjoystick.c
blob: 8a8c905b7cab69924c95de9d181459946be757bf (plain)
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/* (C) Guenter Geiger <geiger@epy.co.at> */


#include <m_imp.h>

#ifdef NT
#pragma warning( disable : 4244 )
#pragma warning( disable : 4305 )
#endif

#include <linux/input.h>

#include <sys/stat.h>

#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h>

#define DEBUG(x) 
/*#define DEBUG(x) x */


#define RAWJOYSTICK_DEVICE   "/dev/input/event0"

// scaling factor for output
#define DEF_SCALE         1
// delay/refresh time in milliseconds
#define DEF_DELTIME       5

#define RAWJOYSTICK_AXES     6
#define RAWJOYSTICK_BUTTONS  9

/* from <linux/input.h>
// button types
#define BTN_LEFT		0x110
#define BTN_RIGHT		0x111
#define BTN_MIDDLE		0x112
#define BTN_SIDE		0x113
#define BTN_EXTRA		0x114
#define BTN_FORWARD		0x115
#define BTN_BACK		0x116

// axes
#define REL_X			0x00
#define REL_Y			0x01
#define REL_WHEEL		0x08
*/


/*------------------------------------------------------------------------------
 * from evtest.c from the ff-utils package
 */

#define BITS_PER_LONG (sizeof(long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
#define OFF(x)  ((x)%BITS_PER_LONG)
#define BIT(x)  (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define test_bit(bit, array)	((array[LONG(bit)] >> OFF(bit)) & 1)


char *events[EV_MAX + 1] = { "Reset", "Key", "Relative", "Absolute", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, "LED", "Sound", NULL, "Repeat", "ForceFeedback", NULL, "ForceFeedbackStatus"};
char *keys[KEY_MAX + 1] = { "Reserved", "Esc", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Minus", "Equal", "Backspace",
"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "LeftBrace", "RightBrace", "Enter", "LeftControl", "A", "S", "D", "F", "G",
"H", "J", "K", "L", "Semicolon", "Apostrophe", "Grave", "LeftShift", "BackSlash", "Z", "X", "C", "V", "B", "N", "M", "Comma", "Dot",
"Slash", "RightShift", "KPAsterisk", "LeftAlt", "Space", "CapsLock", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
"NumLock", "ScrollLock", "KP7", "KP8", "KP9", "KPMinus", "KP4", "KP5", "KP6", "KPPlus", "KP1", "KP2", "KP3", "KP0", "KPDot", "103rd",
"F13", "102nd", "F11", "F12", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "KPEnter", "RightCtrl", "KPSlash", "SysRq",
"RightAlt", "LineFeed", "Home", "Up", "PageUp", "Left", "Right", "End", "Down", "PageDown", "Insert", "Delete", "Macro", "Mute",
"VolumeDown", "VolumeUp", "Power", "KPEqual", "KPPlusMinus", "Pause", "F21", "F22", "F23", "F24", "KPComma", "LeftMeta", "RightMeta",
"Compose", "Stop", "Again", "Props", "Undo", "Front", "Copy", "Open", "Paste", "Find", "Cut", "Help", "Menu", "Calc", "Setup",
"Sleep", "WakeUp", "File", "SendFile", "DeleteFile", "X-fer", "Prog1", "Prog2", "WWW", "MSDOS", "Coffee", "Direction",
"CycleWindows", "Mail", "Bookmarks", "Computer", "Back", "Forward", "CloseCD", "EjectCD", "EjectCloseCD", "NextSong", "PlayPause",
"PreviousSong", "StopCD", "Record", "Rewind", "Phone", "ISOKey", "Config", "HomePage", "Refresh", "Exit", "Move", "Edit", "ScrollUp",
"ScrollDown", "KPLeftParenthesis", "KPRightParenthesis",
"International1", "International2", "International3", "International4", "International5",
"International6", "International7", "International8", "International9",
"Language1", "Language2", "Language3", "Language4", "Language5", "Language6", "Language7", "Language8", "Language9",
NULL, 
"PlayCD", "PauseCD", "Prog3", "Prog4", "Suspend", "Close",
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
"Btn0", "Btn1", "Btn2", "Btn3", "Btn4", "Btn5", "Btn6", "Btn7", "Btn8", "Btn9",
NULL, NULL,  NULL, NULL, NULL, NULL,
"LeftBtn", "RightBtn", "MiddleBtn", "SideBtn", "ExtraBtn", "ForwardBtn", "BackBtn",
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
"Trigger", "ThumbBtn", "ThumbBtn2", "TopBtn", "TopBtn2", "PinkieBtn",
"BaseBtn", "BaseBtn2", "BaseBtn3", "BaseBtn4", "BaseBtn5", "BaseBtn6",
NULL, NULL, NULL, "BtnDead",
"BtnA", "BtnB", "BtnC", "BtnX", "BtnY", "BtnZ", "BtnTL", "BtnTR", "BtnTL2", "BtnTR2", "BtnSelect", "BtnStart", "BtnMode",
"BtnThumbL", "BtnThumbR", NULL,
"ToolPen", "ToolRubber", "ToolBrush", "ToolPencil", "ToolAirbrush", "ToolFinger", "ToolMouse", "ToolLens", NULL, NULL,
"Touch", "Stylus", "Stylus2" };

char *absval[5] = { "Value", "Min  ", "Max  ", "Fuzz ", "Flat " };
char *relatives[REL_MAX + 1] = { "X", "Y", "Z", NULL, NULL, NULL, "HWheel", "Dial", "Wheel" };
char *absolutes[ABS_MAX + 1] = { "X", "Y", "Z", "Rx", "Ry", "Rz", "Throttle", "Rudder", "Wheel", "Gas", "Brake",
NULL, NULL, NULL, NULL, NULL,
"Hat0X", "Hat0Y", "Hat1X", "Hat1Y", "Hat2X", "Hat2Y", "Hat3X", "Hat 3Y", "Pressure", "Distance", "XTilt", "YTilt"};
char *leds[LED_MAX + 1] = { "NumLock", "CapsLock", "ScrollLock", "Compose", "Kana", "Sleep", "Suspend", "Mute" };
char *repeats[REP_MAX + 1] = { "Delay", "Period" };
char *sounds[SND_MAX + 1] = { "Bell", "Click" };

char **names[EV_MAX + 1] = { events, keys, relatives, absolutes, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, leds, sounds, NULL, repeats, NULL, NULL, NULL };

/*------------------------------------------------------------------------------
 */

/*------------------------------------------------------------------------------
 *  CLASS DEF
 */
static t_class *rawjoystick_class;

typedef struct _rawjoystick {
  t_object            x_obj;
  t_int               x_fd;
  t_symbol*           x_devname;
  int                 read_ok;
  int                 started;
  struct input_event  x_input_event; 
  float               x_scale;
  float               x_translation;
  t_outlet            *x_axis_out[RAWJOYSTICK_AXES];
  t_outlet            *x_button_num_out;
  t_outlet            *x_button_val_out;
  t_clock             *x_clock;
  double              x_delaytime;
  unsigned char       x_buttons;
  unsigned char       x_axes;
}t_rawjoystick;

/*------------------------------------------------------------------------------
 * IMPLEMENTATION                    
 */

//DONE
static int rawjoystick_close(t_rawjoystick *x)
{
    DEBUG(post("rawjoystick_close");)

     if (x->x_fd <0) return 0;

     close (x->x_fd);

     return 1;
}

//DONE
static int rawjoystick_open(t_rawjoystick *x,t_symbol* s)
{
  int eventType, eventCode;
  unsigned long bitmask[EV_MAX][NBITS(KEY_MAX)];
  char devicename[256] = "Unknown";
  DEBUG(post("rawjoystick_open");)

  rawjoystick_close(x);

  /* set obj device name to parameter 
   * otherwise set to default
   */  
  if (s != &s_)
    x->x_devname = s;
  else {
    post("You need to set a input device (i.e /dev/input/event0)");
  }
  
  /* open device */
  if (x->x_devname) {
    post("opening ...");
    /* open the rawjoystick device read-only, non-exclusive */
    x->x_fd = open (x->x_devname->s_name, O_RDONLY | O_NONBLOCK);
    if (x->x_fd >= 0 ) post("done");
    else post("failed");
  }
  else {
    return 1;
  }
  
  /* test if device open */
  if (x->x_fd >= 0)
    post("%s opened",x->x_devname->s_name);
  else {
    post("unable to open %s",x->x_devname->s_name);
    x->x_fd = -1;
    return 0;
  }
  
  /* read input_events from the RAWJOYSTICK_DEVICE stream 
   * It seems that is just there to flush the event input buffer?
   */
  while (read (x->x_fd, &(x->x_input_event), sizeof(struct input_event)) > -1);
  
  /* get name of device */
  ioctl(x->x_fd, EVIOCGNAME(sizeof(devicename)), devicename);
  post ("configuring %s",devicename);

  /* get bitmask representing supported events (axes, buttons, etc.) */
  memset(bitmask, 0, sizeof(bitmask));
  ioctl(x->x_fd, EVIOCGBIT(0, EV_MAX), bitmask[0]);
  post("Supported events:");
    
  x->x_axes = 0;
  x->x_buttons = 0;
    
  /* cycle through all possible event types */
  for (eventType = 0; eventType < EV_MAX; eventType++) {
    if (test_bit(eventType, bitmask[0])) {
      post(" %s (type %d) ", events[eventType] ? events[eventType] : "?", eventType);
      //	post("Event type %d",eventType);

      /* get bitmask representing supported button types */
      ioctl(x->x_fd, EVIOCGBIT(eventType, KEY_MAX), bitmask[eventType]);

      /* cycle through all possible event codes (axes, keys, etc.) 
       * testing to see which are supported  
       */
      for (eventCode = 0; eventCode < KEY_MAX; eventCode++) 
	if (test_bit(eventCode, bitmask[eventType])) {
	  post("    Event code %d (%s)", eventCode, names[eventType] ? (names[eventType][eventCode] ? names[eventType][eventCode] : "?") : "?");

	  if ( eventType == EV_KEY ) 
	    x->x_buttons++;
	  else if  ( eventType == EV_ABS ) 
	    x->x_axes++;
	}
    }        
  }
    
  post ("\nUsing %d axes and %d buttons.", x->x_axes, x->x_buttons);
  post ("WARNING * WARNING * WARNING * WARNING * WARNING * WARNING * WARNING");
  post ("This object is under development!  The interface could change at anytime!");
  post ("As I write cross-platform versions, the interface might have to change.");
  post ("WARNING * WARNING * WARNING * WARNING * WARNING * WARNING * WARNING");
    
  return 1;
}



static int rawjoystick_read(t_rawjoystick *x,int fd)
{
  int readBytes;
  int axis_num = 0;
  t_float button_num = 0;
    
  if (x->x_fd < 0) return 0;
  if (x->read_ok) {
    readBytes = read(x->x_fd, &(x->x_input_event), sizeof(struct input_event));
    DEBUG(post("reading %d",readBytes);)
    if ( readBytes < 0 ) {
      post("rawjoystick: read failed");
      x->read_ok = 0;
      return 0;
    }
  }
  if ( x->x_input_event.type == EV_KEY ) {
    /* key/button event type */
    switch ( x->x_input_event.code ) {
    case BTN_0:
      button_num = 0;
      break;
    case BTN_1:
      button_num = 1;
      break;
    case BTN_2:
      button_num = 2;
      break;
    case BTN_3:
      button_num = 3;
      break;
    case BTN_4:
      button_num = 4;
      break;
    case BTN_5:
      button_num = 5;
      break;
    case BTN_6:
      button_num = 6;
      break;
    case BTN_7:
      button_num = 7;
      break;
    case BTN_8:
      button_num = 8;
      break;
    case BTN_9:
      button_num = 9;
      break;
    case BTN_TRIGGER:
      button_num = 10;
      break;
    case BTN_THUMB:
      button_num = 11;
      break;
    case BTN_THUMB2:
      button_num = 12;
      break;
    case BTN_TOP:
      button_num = 13;
      break;
    case BTN_TOP2:
      button_num = 14;
      break;
    case BTN_PINKIE:
      button_num = 15;
      break;
    case BTN_BASE:
      button_num = 16;
      break;
    case BTN_BASE2:
      button_num = 17;
      break;
    case BTN_BASE3:
      button_num = 18;
      break;
    case BTN_BASE4:
      button_num = 19;
      break;
    case BTN_BASE5:
      button_num = 20;
      break;
    case BTN_BASE6:
      button_num = 21;
      break;
    }
    outlet_float (x->x_button_val_out, x->x_input_event.value);
    outlet_float (x->x_button_num_out, button_num);
  }
  else if  ( x->x_input_event.type == EV_ABS ) {
    /* Relative Axes Event Type */
    switch ( x->x_input_event.code ) {
    case ABS_X:
      axis_num = 0;
      break;
    case ABS_Y:
      axis_num = 1;
      break;
    case ABS_Z:
      axis_num = 2;
      break;
    case ABS_HAT0X:
      axis_num = 3;
      break;
    case ABS_HAT0Y:
      axis_num = 4;
      break;
    case ABS_THROTTLE:
      axis_num = 5;
      break;
    }
    outlet_float (x->x_axis_out[axis_num], (int)x->x_input_event.value);	
  }

  return 1;    
}



/* Actions */

static void rawjoystick_bang(t_rawjoystick* x)
{
    DEBUG(post("rawjoystick_bang");)
   
}

static void rawjoystick_float(t_rawjoystick* x)
{
    DEBUG(post("rawjoystick_float");)
   
}

// DONE
void rawjoystick_start(t_rawjoystick* x)
{
  DEBUG(post("rawjoystick_start");)

    if (x->x_fd >= 0 && !x->started) {
       sys_addpollfn(x->x_fd, (t_fdpollfn)rawjoystick_read, x);
       post("rawjoystick: start");
       x->started = 1;
    }
}


// DONE
void rawjoystick_stop(t_rawjoystick* x)
{
  DEBUG(post("rawjoystick_stop");)

    if (x->x_fd >= 0 && x->started) { 
        sys_rmpollfn(x->x_fd);
        post("rawjoystick: stop");
        x->started = 0;
    }
}

/* Misc setup functions */


static void rawjoystick_free(t_rawjoystick* x)
{
  DEBUG(post("rawjoystick_free");)
    
    if (x->x_fd < 0) return;
  
  rawjoystick_stop(x);
  
  close (x->x_fd);
}

static void *rawjoystick_new(t_symbol *s)
{
  int i;
  t_rawjoystick *x = (t_rawjoystick *)pd_new(rawjoystick_class);

  DEBUG(post("rawjoystick_new");)
  
  /* init vars */
  x->x_fd = -1;
  x->read_ok = 1;
  x->started = 0;
  
  /* create outlets for each axis */
  for (i = 0; i < RAWJOYSTICK_AXES; i++) 
    x->x_axis_out[i] = outlet_new(&x->x_obj, &s_float);
  
  /* create outlets for buttons */
  x->x_button_num_out = outlet_new(&x->x_obj, &s_float);
  x->x_button_val_out = outlet_new(&x->x_obj, &s_float);
  
  if (s != &s_)
    x->x_devname = s;
  
  /* Open the device and save settings */
  
  if (!rawjoystick_open(x,s)) return x;
  
  return (x);
}


void rawjoystick_setup(void)
{
  DEBUG(post("rawjoystick_setup");)
  rawjoystick_class = class_new(gensym("rawjoystick"), 
			     (t_newmethod)rawjoystick_new, 
			     (t_method)rawjoystick_free,
			     sizeof(t_rawjoystick),0,A_DEFSYM,0);

  /* add inlet datatype methods */
  class_addfloat(rawjoystick_class,(t_method) rawjoystick_float);
  class_addbang(rawjoystick_class,(t_method) rawjoystick_bang);

  /* add inlet message methods */
  class_addmethod(rawjoystick_class, (t_method) rawjoystick_open,gensym("open"),A_DEFSYM);
  class_addmethod(rawjoystick_class,(t_method) rawjoystick_close,gensym("close"),0);
  class_addmethod(rawjoystick_class,(t_method) rawjoystick_start,gensym("start"),0);
  class_addmethod(rawjoystick_class,(t_method) rawjoystick_stop,gensym("stop"),0);
  
}