a7f57d2d9fc3e6ef468968b85fc25de2eed3aec3
[megadrive.git] / host / main.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <sys/ioctl.h>
8 #include <sys/select.h>
9 #include <unistd.h>
10 #include <dirent.h>
11 #include <signal.h>
12 #include <termios.h>
13 #include <errno.h>
14 #include <linux/usbdevice_fs.h>
15 #include <linux/usb/ch9.h>
16 #include <linux/input.h>
17
18 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
19
20 struct teensy_dev {
21   int fd;
22   struct {
23     int ep_in;
24     int ep_out;
25   } ifaces[2];
26 };
27
28 /* return 1 if founf, 0 if not, < 0 on error */
29 static int find_device(struct teensy_dev *dev,
30   uint16_t vendor, uint16_t product)
31 {
32   const char path_root[] = "/dev/bus/usb";
33   union {
34     struct usb_descriptor_header hdr;
35     struct usb_device_descriptor d;
36     struct usb_config_descriptor c;
37     struct usb_interface_descriptor i;
38     struct usb_endpoint_descriptor e;
39     char space[0x100]; /* enough? */
40   } desc;
41   char path_bus[256], path_dev[256];
42   struct dirent *ent, *ent_bus;
43   DIR *dir = NULL, *dir_bus = NULL;
44   int num, fd = -1;
45   int iface = -1;
46   int retval = -1;
47   int ret;
48
49   memset(dev, 0xff, sizeof(*dev));
50
51   dir = opendir(path_root);
52   if (dir == NULL) {
53     perror("opendir");
54     return -1;
55   }
56
57   for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
58     /* should be a number like 000 */
59     if (sscanf(ent->d_name, "%03d", &num) != 1)
60       continue;
61
62     snprintf(path_bus, sizeof(path_bus), "%s/%s",
63         path_root, ent->d_name);
64
65     dir_bus = opendir(path_bus);
66     if (dir_bus == NULL)
67       continue;
68
69     ent_bus = readdir(dir_bus);
70     for (; ent_bus != NULL; ent_bus = readdir(dir_bus)) {
71       if (sscanf(ent->d_name, "%03d", &num) != 1)
72         continue;
73
74       snprintf(path_dev, sizeof(path_dev), "%s/%s/%s",
75           path_root, ent->d_name, ent_bus->d_name);
76
77       fd = open(path_dev, O_RDWR);
78       if (fd == -1)
79         continue;
80
81       ret = read(fd, &desc.d, sizeof(desc.d));
82       if (ret != sizeof(desc.d)) {
83         fprintf(stderr, "desc read: %d/%zd: ", ret, sizeof(desc.d));
84         perror("");
85         goto next;
86       }
87
88       if (desc.d.bDescriptorType != USB_DT_DEVICE) {
89         fprintf(stderr, "%s: bad DT: 0x%02x\n",
90             path_dev, desc.d.bDescriptorType);
91         goto next;
92       }
93
94       if (desc.d.idVendor == vendor && desc.d.idProduct == product)
95         goto found;
96
97 next:
98       close(fd);
99       fd = -1;
100     }
101
102     closedir(dir_bus);
103     dir_bus = NULL;
104   }
105
106   /* not found */
107   retval = 0;
108   goto out;
109
110 found:
111   if (desc.d.bNumConfigurations != 1) {
112     fprintf(stderr, "unexpected bNumConfigurations: %u\n",
113         desc.d.bNumConfigurations);
114     goto out;
115   }
116
117   /* walk through all descriptors */
118   while (1)
119   {
120     ret = read(fd, &desc.hdr, sizeof(desc.hdr));
121     if (ret == 0)
122       break;
123     if (ret != sizeof(desc.hdr)) {
124       fprintf(stderr, "desc.hdr read: %d/%zd: ", ret, sizeof(desc.hdr));
125       perror("");
126       break;
127     }
128
129     ret = (int)lseek(fd, -sizeof(desc.hdr), SEEK_CUR);
130     if (ret == -1) {
131       perror("lseek");
132       break;
133     }
134
135     ret = read(fd, &desc, desc.hdr.bLength);
136     if (ret != desc.hdr.bLength) {
137       fprintf(stderr, "desc read: %d/%u: ", ret, desc.hdr.bLength);
138       perror("");
139       break;
140     }
141
142     switch (desc.hdr.bDescriptorType) {
143       case USB_DT_CONFIG:
144         if (desc.c.bNumInterfaces != 2) {
145           fprintf(stderr, "unexpected bNumInterfaces: %u\n",
146               desc.c.bNumInterfaces);
147           goto out;
148         }
149         break;
150
151       case USB_DT_INTERFACE:
152         if (desc.i.bInterfaceClass != USB_CLASS_HID
153             || desc.i.bInterfaceSubClass != 0
154             || desc.i.bInterfaceProtocol != 0) {
155           fprintf(stderr, "unexpected interface %x:%x:%x\n",
156             desc.i.bInterfaceClass, desc.i.bInterfaceSubClass,
157             desc.i.bInterfaceProtocol);
158           goto out;
159         }
160         if (desc.i.bNumEndpoints != 2) {
161           fprintf(stderr, "unexpected bNumEndpoints: %u\n",
162             desc.i.bNumEndpoints);
163           goto out;
164         }
165         iface++;
166         break;
167
168       case USB_DT_ENDPOINT:
169         if (iface < 0 || iface >= ARRAY_SIZE(dev->ifaces)) {
170           fprintf(stderr, "bad iface: %d\n", iface);
171           goto out;
172         }
173         if (desc.e.wMaxPacketSize != 64 && desc.e.wMaxPacketSize != 32) {
174           fprintf(stderr, "iface %d, EP %02x: "
175             "unexpected wMaxPacketSize: %u\n",
176             iface, desc.e.bEndpointAddress, desc.e.wMaxPacketSize);
177           goto out;
178         }
179         if (desc.e.bEndpointAddress & 0x80)
180           dev->ifaces[iface].ep_in = desc.e.bEndpointAddress; // & 0x7F;
181         else
182           dev->ifaces[iface].ep_out = desc.e.bEndpointAddress;
183         break;
184
185       case 0x21:
186         /* ignore */
187         break;
188
189       default:
190         fprintf(stderr, "skipping desc 0x%02x\n",
191           desc.hdr.bDescriptorType);
192         break;
193     }
194   }
195
196   /* claim interfaces */
197   for (iface = 0; iface < ARRAY_SIZE(dev->ifaces); iface++) {
198     struct usbdevfs_ioctl usbio;
199
200     if (dev->ifaces[iface].ep_in == -1) {
201       fprintf(stderr, "missing ep_in, iface: %d\n", iface);
202       goto out;
203     }
204     if (dev->ifaces[iface].ep_out == -1) {
205       fprintf(stderr, "missing ep_out, iface: %d\n", iface);
206       goto out;
207     }
208
209     /* disconnect default driver */
210     memset(&usbio, 0, sizeof(usbio));
211     usbio.ifno = iface;
212     usbio.ioctl_code = USBDEVFS_DISCONNECT;
213     ret = ioctl(fd, USBDEVFS_IOCTL, &usbio);
214     if (ret != 0 && errno != ENODATA)
215       perror("USBDEVFS_DISCONNECT");
216
217     ret = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &iface);
218     if (ret != 0)
219       perror("USBDEVFS_CLAIMINTERFACE");
220   }
221
222   dev->fd = fd;
223   fd = -1;
224   retval = 1;
225
226 out:
227   if (fd != -1)
228     close(fd);
229   if (dir_bus != NULL)
230     closedir(dir_bus);
231   if (dir != NULL)
232     closedir(dir);
233
234   return retval;
235 }
236
237 static int enable_echo(int enable)
238 {
239   const char *portname = "/dev/tty";
240   struct termios tty;
241   int retval = -1;
242   int ret;
243   int fd;
244
245   memset(&tty, 0, sizeof(tty));
246
247   fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
248   if (fd < 0) {
249     fprintf(stderr, "open %s: ", portname);
250     perror("");
251     return 1;
252   }
253
254   ret = tcgetattr(fd, &tty);
255   if (ret != 0) {
256     perror("tcgetattr");
257     goto out;
258   }
259
260   // printf("lflag: 0%o\n", tty.c_lflag);
261   if (enable)
262     tty.c_lflag |= ECHO;
263   else
264     tty.c_lflag &= ~ECHO;
265
266   ret = tcsetattr(fd, TCSANOW, &tty);
267   if (ret != 0) {
268     perror("tcsetattr");
269     goto out;
270   }
271
272   retval = 0;
273 out:
274   close(fd);
275
276   return retval;
277 }
278
279 static void signal_handler(int sig)
280 {
281   enable_echo(1);
282   signal(sig, SIG_DFL);
283   raise(sig);
284 }
285
286 /* ?0SA 00DU, ?1CB RLDU */
287 #define STATE_BYTES 2
288
289 static uint8_t fixed_input_state[STATE_BYTES] = { 0x33, 0x3f };
290
291 enum mdbtn {
292   MDBTN_UP = 1,
293   MDBTN_DOWN,
294   MDBTN_LEFT,
295   MDBTN_RIGHT,
296   MDBTN_A,
297   MDBTN_B,
298   MDBTN_C,
299   MDBTN_START,
300 };
301
302 static const enum mdbtn evdev_md_map[KEY_CNT] = {
303   [KEY_UP]       = MDBTN_UP,
304   [KEY_DOWN]     = MDBTN_DOWN,
305   [KEY_LEFT]     = MDBTN_LEFT,
306   [KEY_RIGHT]    = MDBTN_RIGHT,
307   [KEY_HOME]     = MDBTN_A,
308   [KEY_PAGEDOWN] = MDBTN_B,
309   [KEY_END]      = MDBTN_C,
310   [KEY_LEFTALT]  = MDBTN_START,
311 };
312
313 int do_evdev_input(int fd)
314 {
315   uint8_t old_state[STATE_BYTES];
316   uint8_t changed_bits[STATE_BYTES] = { 0, };
317   struct input_event ev;
318   enum mdbtn mdbtn;
319   int i, ret;
320
321   ret = read(fd, &ev, sizeof(ev));
322   if (ret != sizeof(ev)) {
323     fprintf(stderr, "evdev read %d/%zd: ", ret, sizeof(ev));
324     perror("");
325     return 0;
326   }
327
328   if (ev.type != EV_KEY)
329     return 0;
330
331   if (ev.value != 0 && ev.value != 1)
332     return 0;
333
334   if ((uint32_t)ev.code >= ARRAY_SIZE(evdev_md_map)) {
335     fprintf(stderr, "evdev read bad key: %u\n", ev.code);
336     return 0;
337   }
338
339   mdbtn = evdev_md_map[ev.code];
340   if (mdbtn == 0)
341     return 0;
342
343   memcpy(old_state, fixed_input_state, STATE_BYTES);
344
345   /* ?0SA 00DU, ?1CB RLDU */
346   switch (mdbtn) {
347   case MDBTN_UP:
348     changed_bits[0] = 0x01;
349     changed_bits[1] = 0x01;
350     break;
351   case MDBTN_DOWN:
352     changed_bits[0] = 0x02;
353     changed_bits[1] = 0x02;
354     break;
355   case MDBTN_LEFT:
356     changed_bits[0] = 0x00;
357     changed_bits[1] = 0x04;
358     break;
359   case MDBTN_RIGHT:
360     changed_bits[0] = 0x00;
361     changed_bits[1] = 0x08;
362     break;
363   case MDBTN_A:
364     changed_bits[0] = 0x10;
365     changed_bits[1] = 0x00;
366     break;
367   case MDBTN_B:
368     changed_bits[0] = 0x00;
369     changed_bits[1] = 0x10;
370     break;
371   case MDBTN_C:
372     changed_bits[0] = 0x00;
373     changed_bits[1] = 0x20;
374     break;
375   case MDBTN_START:
376     changed_bits[0] = 0x20;
377     changed_bits[1] = 0x00;
378     break;
379   }
380
381   if (ev.value) {
382     // key press
383     for (i = 0; i < STATE_BYTES; i++)
384       fixed_input_state[i] &= ~changed_bits[i];
385   }
386   else {
387     // key release
388     for (i = 0; i < STATE_BYTES; i++)
389       fixed_input_state[i] |=  changed_bits[i];
390   }
391
392   return memcmp(old_state, fixed_input_state, STATE_BYTES) ? 1 : 0;
393 }
394
395 enum my_urbs {
396   URB_DATA_IN,
397   URB_DATA_OUT,
398   URB_DBG_IN,
399   URB_CNT
400 };
401
402 int main(int argc, char *argv[])
403 {
404   char buf_dbg[64 + 1], buf_in[64], buf_out[64];
405   struct teensy_dev dev;
406   struct usbdevfs_urb urb[URB_CNT];
407   struct usbdevfs_urb *reaped_urb;
408   int fixed_input_changed;
409   int evdev_fds[16];
410   int evdev_fd_cnt = 0;
411   int evdev_support;
412   int wait_device = 0;
413   int dbg_in_sent = 0;
414   int data_in_sent = 0;
415   fd_set rfds, wfds;
416   int i, ret;
417   int fd;
418
419   for (i = 1; i < argc; i++) {
420     if (evdev_fd_cnt >= ARRAY_SIZE(evdev_fds)) {
421       fprintf(stderr, "too many evdevs\n");
422       break;
423     }
424                 fd = open(argv[i], O_RDONLY);
425     if (fd == -1) {
426       fprintf(stderr, "open %s: ", argv[i]);
427       perror("");
428       continue;
429     }
430     evdev_support = 0;
431                 ret = ioctl(fd, EVIOCGBIT(0, sizeof(evdev_support)),
432                 &evdev_support);
433     if (ret < 0)
434       perror("EVIOCGBIT");
435     if (!(evdev_support & (1 << EV_KEY))) {
436       fprintf(stderr, "%s doesn't have keys\n", argv[i]);
437       close(fd);
438       continue;
439     }
440     evdev_fds[evdev_fd_cnt++] = fd;
441   }
442
443   enable_echo(0);
444   signal(SIGINT, signal_handler);
445
446   dev.fd = -1;
447
448   while (1)
449   {
450     if (dev.fd == -1) {
451       ret = find_device(&dev, 0x16C0, 0x0486);
452       if (ret < 0)
453         break;
454
455       if (ret == 0) {
456         if (!wait_device) {
457           printf("waiting for device..\n");
458           wait_device = 1;
459         }
460         usleep(250000);
461         continue;
462       }
463
464       wait_device = 0;
465       data_in_sent = 0;
466       dbg_in_sent = 0;
467     }
468
469     if (!data_in_sent) {
470       memset(&urb[URB_DATA_IN], 0, sizeof(urb[URB_DATA_IN]));
471       urb[URB_DATA_IN].type = USBDEVFS_URB_TYPE_INTERRUPT;
472       urb[URB_DATA_IN].endpoint = dev.ifaces[0].ep_in;
473       urb[URB_DATA_IN].buffer = buf_in;
474       urb[URB_DATA_IN].buffer_length = sizeof(buf_in);
475
476       ret = ioctl(dev.fd, USBDEVFS_SUBMITURB, &urb[URB_DATA_IN]);
477       if (ret != 0) {
478         perror("USBDEVFS_SUBMITURB URB_DATA_IN");
479         break;
480       }
481       data_in_sent = 1;
482     }
483     if (!dbg_in_sent) {
484       memset(&urb[URB_DBG_IN], 0, sizeof(urb[URB_DBG_IN]));
485       urb[URB_DBG_IN].type = USBDEVFS_URB_TYPE_INTERRUPT;
486       urb[URB_DBG_IN].endpoint = dev.ifaces[1].ep_in;
487       urb[URB_DBG_IN].buffer = buf_dbg;
488       urb[URB_DBG_IN].buffer_length = sizeof(buf_dbg) - 1;
489
490       ret = ioctl(dev.fd, USBDEVFS_SUBMITURB, &urb[URB_DBG_IN]);
491       if (ret != 0) {
492         perror("USBDEVFS_SUBMITURB URB_DBG_IN");
493         break;
494       }
495       dbg_in_sent = 1;
496     }
497
498     FD_ZERO(&rfds);
499     for (i = 0; i < evdev_fd_cnt; i++)
500       FD_SET(evdev_fds[i], &rfds);
501
502     FD_ZERO(&wfds);
503     FD_SET(dev.fd, &wfds);
504
505     ret = select(dev.fd + 1, &rfds, &wfds, NULL, NULL);
506     if (ret < 0) {
507       perror("select");
508       break;
509     }
510
511     /* something from input devices? */
512     fixed_input_changed = 0;
513     for (i = 0; i < evdev_fd_cnt; i++) {
514       if (FD_ISSET(evdev_fds[i], &rfds)) {
515         fixed_input_changed |=
516           do_evdev_input(evdev_fds[i]);
517       }
518     }
519
520     /* something from USB? */
521     if (FD_ISSET(dev.fd, &wfds)) {
522       reaped_urb = NULL;
523       ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
524       if (ret != 0) {
525         if (errno == ENODEV)
526           goto dev_close;
527         perror("USBDEVFS_REAPURB");
528         break;
529       }
530
531       if (reaped_urb != NULL && reaped_urb->status != 0) {
532         errno = -reaped_urb->status;
533         perror("urb status");
534         if (reaped_urb->status == -EILSEQ) {
535           /* this is usually a sign of disconnect.. */
536           usleep(250000);
537           goto dev_close;
538         }
539       }
540
541       if (reaped_urb == &urb[URB_DATA_IN]) {
542         printf("*data*\n");
543         data_in_sent = 0;
544       }
545       if (reaped_urb == &urb[URB_DATA_OUT]) {
546       }
547       else if (reaped_urb == &urb[URB_DBG_IN]) {
548         /* debug text */
549         buf_dbg[reaped_urb->actual_length] = 0;
550         printf("%s", buf_dbg);
551         dbg_in_sent = 0;
552       }
553       else {
554         fprintf(stderr, "reaped unknown urb? %p\n", reaped_urb);
555       }
556     }
557
558     /* something to send? */
559     if (fixed_input_changed) {
560       memset(buf_out, 0, sizeof(buf_out));
561       memcpy(buf_out, fixed_input_state, sizeof(fixed_input_state));
562
563       memset(&urb[URB_DATA_OUT], 0, sizeof(urb[URB_DATA_OUT]));
564       urb[URB_DATA_OUT].type = USBDEVFS_URB_TYPE_INTERRUPT;
565       urb[URB_DATA_OUT].endpoint = dev.ifaces[0].ep_out;
566       urb[URB_DATA_OUT].buffer = buf_out;
567       urb[URB_DATA_OUT].buffer_length = sizeof(buf_out);
568
569       ret = ioctl(dev.fd, USBDEVFS_SUBMITURB, &urb[URB_DATA_OUT]);
570       if (ret != 0) {
571         perror("USBDEVFS_SUBMITURB URB_DATA_OUT");
572         break;
573       }
574     }
575
576     continue;
577
578 dev_close:
579     close(dev.fd);
580     dev.fd = -1;
581   }
582
583   enable_echo(1);
584
585   return ret;
586 }
587
588 // vim: ts=2:sw=2:expandtab