magellan motion packets didn't need swapping on big endian
[sball] / src / sball.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include <time.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <termios.h>
10 #include <sys/select.h>
11 #include <sys/time.h>
12 #include <sys/ioctl.h>
13
14 #if  defined(__i386__) || defined(__ia64__) || defined(WIN32) || \
15     (defined(__alpha__) || defined(__alpha)) || \
16      defined(__arm__) || \
17     (defined(__mips__) && defined(__MIPSEL__)) || \
18      defined(__SYMBIAN32__) || \
19      defined(__x86_64__) || \
20      defined(__LITTLE_ENDIAN__)
21 #define SBALL_LITTLE_ENDIAN
22 #else
23 #define SBALL_BIG_ENDIAN
24 #endif
25
26 #define INP_BUF_SZ      256
27
28 enum {
29         SB4000  = 1,
30         FLIPXY  = 2
31 };
32
33 struct sball {
34         int fd;
35         unsigned int flags;
36         int nbuttons;
37
38         char buf[INP_BUF_SZ];
39         int len;
40
41         short mot[6];
42         unsigned int keystate;
43
44         struct termios saved_term;
45         int saved_mstat;
46
47         int (*parse)(struct sball*, int, char*, int);
48 };
49
50 static int stty_sball(struct sball *sb);
51 static int stty_mag(struct sball *sb);
52 static void stty_save(struct sball *sb);
53 static void stty_restore(struct sball *sb);
54
55 static int proc_input(struct sball *sb);
56
57 static int mag_parsepkt(struct sball *sb, int id, char *data, int len);
58 static int sball_parsepkt(struct sball *sb, int id, char *data, int len);
59
60 static int guess_num_buttons(const char *verstr);
61
62 static void make_printable(char *buf, int len);
63 static int read_timeout(int fd, char *buf, int bufsz, long tm_usec);
64
65 static void print_state(struct sball *sb);
66
67
68 struct sball *sball_open(const char *dev)
69 {
70         int fd, sz;
71         char buf[128];
72         struct sball *sb = 0;
73
74         if((fd = open(dev, O_RDWR | O_NOCTTY | O_NONBLOCK)) == -1) {
75                 fprintf(stderr, "sball_open: failed to open device: %s: %s\n", dev, strerror(errno));
76                 return 0;
77         }
78
79         if(!(sb = calloc(1, sizeof *sb))) {
80                 fprintf(stderr, "sball_open: failed to allocate sball object\n");
81                 goto err;
82         }
83         sb->fd = fd;
84
85         stty_save(sb);
86
87         if(stty_sball(sb) == -1) {
88                 goto err;
89         }
90         write(fd, "\r@RESET\r", 8);
91
92         if((sz = read_timeout(fd, buf, sizeof buf - 1, 2000000)) > 0 && strstr(buf, "\r@1")) {
93                 /* we got a response, so it's a spaceball */
94                 make_printable(buf, sz);
95                 printf("Spaceball detected: %s\n", buf);
96
97                 sb->nbuttons = guess_num_buttons(buf);
98                 printf("%d buttons\n", sb->nbuttons);
99
100                 /* set binary mode and enable automatic data packet sending */
101                 write(fd, "\rCB\rMSSV\r", 9);
102
103                 sb->parse = sball_parsepkt;
104                 return sb;
105         }
106
107         /* try as a magellan spacemouse */
108         if(stty_mag(sb) == -1) {
109                 goto err;
110         }
111         write(fd, "vQ\r", 3);
112
113         if((sz = read_timeout(fd, buf, sizeof buf - 1, 250000)) > 0 && buf[0] == 'v') {
114                 make_printable(buf, sz);
115                 printf("Magellan SpaceMouse detected:\n%s\n", buf);
116
117                 sb->nbuttons = guess_num_buttons(buf);
118                 printf("%d buttons\n", sb->nbuttons);
119
120                 /* set 3D mode, not-dominant-axis, pass through motion and button packets */
121                 write(fd, "m3\r", 3);
122
123                 sb->parse = mag_parsepkt;
124                 return sb;
125         }
126
127 err:
128         stty_restore(sb);
129         close(fd);
130         free(sb);
131         return 0;
132 }
133
134 void sball_close(struct sball *sb)
135 {
136         if(!sb) return;
137
138         stty_restore(sb);
139         close(sb->fd);
140 }
141
142 int sball_fd(struct sball *sb)
143 {
144         return sb->fd;
145 }
146
147 int sball_read(struct sball *sb)
148 {
149         int sz;
150
151         while((sz = read(sb->fd, sb->buf + sb->len,  INP_BUF_SZ - sb->len - 1)) > 0) {
152                 sb->len += sz;
153                 proc_input(sb);
154         }
155
156         /* if we fill the input buffer, make a last attempt to parse it, and discard
157          * it so we can receive more
158          */
159         if(sb->len >= INP_BUF_SZ) {
160                 proc_input(sb);
161                 sb->len = 0;
162         }
163
164         return 0;
165 }
166
167 int sball_axis(struct sball *sb, int axis)
168 {
169         return sb->mot[axis];
170 }
171
172 unsigned int sball_buttons(struct sball *sb)
173 {
174         return sb->keystate;
175 }
176
177 int sball_num_buttons(struct sball *sb)
178 {
179         return sb->nbuttons;
180 }
181
182 /* Labtec spaceball: 9600 8n1 XON/XOFF
183  * Can't use canonical mode to assemble input into lines for the spaceball,
184  * because binary data received for motion events can include newlines which
185  * would be eaten up by the line discipline. Therefore we'll rely on VTIME=1 to
186  * hopefully get more than 1 byte at a time. Alternatively we could request
187  * printable reports, but I don't feel like implementing that.
188  */
189 static int stty_sball(struct sball *sb)
190 {
191         int mstat;
192         struct termios term;
193
194         term = sb->saved_term;
195         term.c_oflag = 0;
196         term.c_lflag = 0;
197         term.c_cc[VMIN] = 0;
198         term.c_cc[VTIME] = 1;
199
200         term.c_cflag = CLOCAL | CREAD | CS8 | HUPCL;
201         term.c_iflag = IGNBRK | IGNPAR | IXON | IXOFF;
202
203         cfsetispeed(&term, B9600);
204         cfsetospeed(&term, B9600);
205
206         if(tcsetattr(sb->fd, TCSAFLUSH, &term) == -1) {
207                 perror("sball_open: tcsetattr");
208                 return -1;
209         }
210         tcflush(sb->fd, TCIOFLUSH);
211
212         mstat = sb->saved_mstat | TIOCM_DTR | TIOCM_RTS;
213         ioctl(sb->fd, TIOCMGET, &mstat);
214         return 0;
215 }
216
217 /* Logicad magellan spacemouse: 9600 8n2 CTS/RTS
218  * Since the magellan devices don't seem to send any newlines, we can rely on
219  * canonical mode to feed us nice whole lines at a time.
220  */
221 static int stty_mag(struct sball *sb)
222 {
223         int mstat;
224         struct termios term;
225
226         term = sb->saved_term;
227         term.c_oflag = 0;
228         term.c_lflag = ICANON;
229         term.c_cc[VMIN] = 0;
230         term.c_cc[VTIME] = 0;
231         term.c_cc[VEOF] = 0;
232         term.c_cc[VEOL] = '\r';
233         term.c_cc[VEOL2] = 0;
234         term.c_cc[VERASE] = 0;
235         term.c_cc[VKILL] = 0;
236
237         term.c_cflag = CLOCAL | CREAD | CS8 | CSTOPB | HUPCL;
238 #ifdef CCTS_OFLOW
239         term.c_cflag |= CCTS_OFLOW;
240 #elif defined(CRTSCTS)
241         term.c_cflag |= CRTSCTS;
242 #endif
243         term.c_iflag = IGNBRK | IGNPAR;
244
245         cfsetispeed(&term, B9600);
246         cfsetospeed(&term, B9600);
247
248         if(tcsetattr(sb->fd, TCSAFLUSH, &term) == -1) {
249                 perror("sball_open: tcsetattr");
250                 return -1;
251         }
252         tcflush(sb->fd, TCIOFLUSH);
253
254         mstat = sb->saved_mstat | TIOCM_DTR | TIOCM_RTS;
255         ioctl(sb->fd, TIOCMGET, &mstat);
256         return 0;
257 }
258
259 static void stty_save(struct sball *sb)
260 {
261         tcgetattr(sb->fd, &sb->saved_term);
262         ioctl(sb->fd, TIOCMGET, &sb->saved_mstat);
263 }
264
265 static void stty_restore(struct sball *sb)
266 {
267         tcsetattr(sb->fd, TCSAFLUSH, &sb->saved_term);
268         tcflush(sb->fd, TCIOFLUSH);
269         ioctl(sb->fd, TIOCMSET, &sb->saved_mstat);
270 }
271
272
273 static int proc_input(struct sball *sb)
274 {
275         int sz;
276         char *bptr = sb->buf;
277         char *start = sb->buf;
278         char *end = sb->buf + sb->len;
279
280         /* see if we have a CR in the buffer */
281         while(bptr < end) {
282                 if(*bptr == '\r') {
283                         *bptr = 0;
284                         sb->parse(sb, *start, start + 1, bptr - start - 1);
285                         start = ++bptr;
286                 } else {
287                         bptr++;
288                 }
289         }
290
291         sz = start - sb->buf;
292         if(sz > 0) {
293                 memmove(sb->buf, start, sz);
294                 sb->len -= sz;
295         }
296         return 0;
297 }
298
299 static int mag_parsepkt(struct sball *sb, int id, char *data, int len)
300 {
301         int i;
302
303         /*printf("magellan packet: %c - %s (%d bytes)\n", (char)id, data, len);*/
304
305         switch(id) {
306         case 'd':
307                 if(len != 24) {
308                         fprintf(stderr, "magellan: invalid data packet, expected 24 bytes, got: %d\n", len);
309                         return -1;
310                 }
311                 for(i=0; i<6; i++) {
312                         sb->mot[i] = ((((int)data[0] & 0xf) << 12) | (((int)data[1] & 0xf) << 8) |
313                                         (((int)data[2] & 0xf) << 4) | (data[3] & 0xf)) - 0x8000;
314                         data += 4;
315                 }
316                 print_state(sb);
317                 break;
318
319         case 'k':
320                 if(len != 3) {
321                         fprintf(stderr, "magellan: invalid keyboard pakcet, expected 3 bytes, got: %d\n", len);
322                         return -1;
323                 }
324                 sb->keystate = (data[0] & 0xf) | ((data[1] & 0xf) << 4) | (((unsigned int)data[2] & 0xf) << 8);
325                 print_state(sb);
326                 break;
327
328         case 'e':
329                 if(data[0] == 1) {
330                         fprintf(stderr, "magellan error: illegal command: %c%c\n", data[1], data[2]);
331                 } else if(data[0] == 2) {
332                         fprintf(stderr, "magellan error: framing error\n");
333                 } else {
334                         fprintf(stderr, "magellan error: unknown device error\n");
335                 }
336                 return -1;
337
338         default:
339                 break;
340         }
341         return 0;
342 }
343
344 static int sball_parsepkt(struct sball *sb, int id, char *data, int len)
345 {
346         int i;
347         char c, *rd, *wr;
348
349         /* decode data packet, replacing escaped values with the correct ones */
350         rd = wr = data;
351         while(rd < data + len) {
352                 if((c = *rd++) == '^') {
353                         switch(*rd++) {
354                         case 'Q':
355                                 *wr++ = 0x11;   /* XON */
356                                 break;
357                         case 'S':
358                                 *wr++ = 0x13;   /* XOFF */
359                                 break;
360                         case 'M':
361                                 *wr++ = 13;             /* CR */
362                                 break;
363                         case '^':
364                                 *wr++ = '^';
365                                 break;
366                         default:
367                                 fprintf(stderr, "sball decode: ignoring invalid escape code: %xh\n", (unsigned int)c);
368                         }
369                 } else {
370                         *wr++ = c;
371                 }
372         }
373         len = wr - data;        /* update the decoded length */
374
375         switch(id) {
376         case 'D':
377                 if(len != 14) {
378                         fprintf(stderr, "sball: invalid data packet, expected 14 bytes, got: %d\n", len);
379                         return -1;
380                 }
381
382 #ifndef SBALL_BIG_ENDIAN
383                 rd = data;
384                 for(i=0; i<6; i++) {
385                         rd += 2;
386                         c = rd[0];
387                         rd[0] = rd[1];
388                         rd[1] = c;
389                 }
390 #endif
391                 memcpy(sb->mot, data + 2, 12);
392                 print_state(sb);
393                 break;
394
395         case 'K':
396                 if(len != 2) {
397                         fprintf(stderr, "sball: invalid key packet, expected 2 bytes, got: %d\n", len);
398                         return -1;
399                 }
400                 if(sb->flags & SB4000) break;   /* ignore K packets from spaceball 4000 devices */
401
402                 /* data[1] bits 0-3 -> buttons 0,1,2,3
403                  * data[1] bits 4,5 (3003 L/R) -> buttons 0, 1
404                  * data[0] bits 0-2 -> buttons 4,5,6
405                  * data[0] bit 4 is (2003 pick) -> button 7
406                  */
407                 sb->keystate = (data[1] & 0xf) | ((data[1] >> 4) & 3) | ((data[0] & 7) << 4) |
408                         ((data[0] & 0x10) >> 1);
409                 print_state(sb);
410                 break;
411
412         case '.':
413                 if(len != 2) {
414                         fprintf(stderr, "sball: invalid sb4k key packet, expected 2 bytes, got: %d\n", len);
415                         return -1;
416                 }
417                 /* spaceball 4000 key packet */
418                 sb->flags |= SB4000;
419                 /* update orientation flag (actually don't bother) */
420                 /*
421                 if(data[0] & 0x20) {
422                         sb->flags |= FLIPXY;
423                 } else {
424                         sb->flags &= ~FLIPXY;
425                 }
426                 */
427
428                 /* data[1] bits 0-5 -> buttons 0,1,2,3,4,5
429                  * data[1] bit 7 -> button 6
430                  * data[0] bits 0-4 -> buttons 7,8,9,10,11
431                  */
432                 sb->keystate = (data[1] & 0x3f) | ((data[1] & 0x80) >> 1) | ((data[0] & 0x1f) << 7);
433                 print_state(sb);
434                 break;
435
436         case 'E':
437                 fprintf(stderr, "sball: error:");
438                 for(i=0; i<len; i++) {
439                         if(isprint((int)data[i])) {
440                                 fprintf(stderr, " %c", data[i]);
441                         } else {
442                                 fprintf(stderr, " %02xh", (unsigned int)data[i]);
443                         }
444                 }
445                 break;
446
447         case 'M':       /* ignore MSS responses */
448                 break;
449
450         default:
451                 /* DEBUG */
452                 fprintf(stderr, "sball: got '%c' packet:", (char)id);
453                 for(i=0; i<len; i++) {
454                         fprintf(stderr, " %02x", (unsigned int)data[i]);
455                 }
456                 fputc('\n', stderr);
457         }
458         return 0;
459 }
460
461 static int guess_num_buttons(const char *verstr)
462 {
463         int major, minor;
464         const char *s, *model;
465
466         if((s = strstr(verstr, "Firmware version"))) {  /* spaceball */
467
468                 /* if we got a model number, guess based on that */
469                 if((model = strchr(s, '('))) {
470                         if(memcmp(model, "(Model ", 7) == 0) {
471                                 model += 7;
472                         } else {
473                                 model++;
474                         }
475                         switch(atoi(model)) {
476                         case 2003:
477                                 return 8;
478                         case 3003:
479                                 return 2;
480                         case 5000:
481                                 return 12;
482                         default:
483                                 break;
484                         }
485                 }
486                 /* try to guess based on firmware number */
487                 if(sscanf(s + 17, "%d.%d", &major, &minor) == 2 && major == 2) {
488                         if(minor == 35 || minor == 62 || minor == 63) {
489                                 return 2;       /* spaceball 3003/3003C */
490                         }
491                         if(minor == 42 || minor == 43 || minor == 45) {
492                                 /* 2.42 is also used by spaceball 2003C, but this should be
493                                  * caught before we get here by the model number guess
494                                  */
495                                 return 12;      /* spaceball 4000flx/5000flx-a */
496                         }
497                         if(minor == 2 || minor == 13 || minor == 15) {
498                                 return 8;       /* spaceball 1003/2003/2003c */
499                         }
500                 }
501         }
502
503         if(strstr(verstr, "MAGELLAN")) {
504                 return 9; /* magellan spacemouse */
505         }
506
507         if(strstr(verstr, "SPACEBALL")) {
508                 return 12; /* spaceball 5000 */
509         }
510
511         if(strstr(verstr, "CadMan")) {
512                 return 2;
513         }
514
515         fprintf(stderr, "Can't guess number of buttons, default to 8, report this as a bug!\n");
516         return 8;
517 }
518
519 static void make_printable(char *buf, int len)
520 {
521         int i, c;
522         char *wr = buf;
523
524         for(i=0; i<len; i++) {
525                 c = *buf++;
526                 if(c == '\r') {
527                         *wr++ = '\n';
528                         while(*buf == '\n' || *buf == '\r') buf++;
529                 } else {
530                         *wr++ = c;
531                 }
532         }
533         *wr = 0;
534 }
535
536 static int read_timeout(int fd, char *buf, int bufsz, long tm_usec)
537 {
538         int res;
539         long usec, sz = 0;
540         struct timeval tv0, tv;
541         fd_set rdset;
542
543         if(!buf || bufsz <= 0) return -1;
544
545         usec = tm_usec;
546         gettimeofday(&tv0, 0);
547
548         while(sz < bufsz && usec > 0) {
549                 tv.tv_sec = usec / 1000000;
550                 tv.tv_usec = usec % 1000000;
551
552                 FD_ZERO(&rdset);
553                 FD_SET(fd, &rdset);
554                 if((res = select(fd + 1, &rdset, 0, 0, &tv)) > 0 && FD_ISSET(fd, &rdset)) {
555                         sz += read(fd, buf + sz, bufsz - sz);
556                         buf[sz] = 0;
557                         tm_usec = usec = 128000;        /* wait 128ms for the rest of the message to appear */
558                         gettimeofday(&tv0, 0);
559                         continue;
560                 }
561                 if(res == -1 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
562                         break;
563                 }
564                 gettimeofday(&tv, 0);
565                 usec = tm_usec - ((tv.tv_sec - tv0.tv_sec) * 1000000 + (tv.tv_usec - tv0.tv_usec));
566         }
567
568         return sz > 0 ? sz : -1;
569 }
570
571 static void print_motion(short *mot)
572 {
573         printf(" T[%+6d %+6d %+6d]  R[%+6d %+6d %+6d]", mot[0], mot[1],
574                         mot[2], mot[3], mot[4], mot[5]);
575 }
576
577 static void print_keystate(unsigned int keystate)
578 {
579         int i;
580
581         for(i=0; i<12; i++) {
582                 int b = 11 - i;
583                 int hex = b < 10 ? b + '0' : b - 10 + 'a';
584                 putchar(keystate & (1 << b) ? hex : '-');
585         }
586 }
587
588 static void print_state(struct sball *sb)
589 {
590         print_motion(sb->mot);
591         printf("  B[");
592         print_keystate(sb->keystate);
593         printf("]\r");
594         fflush(stdout);
595 }