2 * TeensyTP, Team Player/4-Player Adaptor implementation for Teensy3
4 * Copyright (c) 2015 notaz
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/select.h>
41 #include <linux/usbdevice_fs.h>
42 #include <linux/usb/ch9.h>
43 #include <linux/input.h>
46 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
56 /* return 1 if found, 0 if not, < 0 on error */
57 static int find_device(struct teensy_dev *dev,
58 uint16_t vendor, uint16_t product)
60 const char path_root[] = "/dev/bus/usb";
62 struct usb_descriptor_header hdr;
63 struct usb_device_descriptor d;
64 struct usb_config_descriptor c;
65 struct usb_interface_descriptor i;
66 struct usb_endpoint_descriptor e;
67 char space[0x100]; /* enough? */
69 char path_bus[256], path_dev[256];
70 struct dirent *ent, *ent_bus;
71 DIR *dir = NULL, *dir_bus = NULL;
77 memset(dev, 0xff, sizeof(*dev));
79 dir = opendir(path_root);
85 for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
86 /* should be a number like 000 */
87 if (sscanf(ent->d_name, "%03d", &num) != 1)
90 snprintf(path_bus, sizeof(path_bus), "%s/%s",
91 path_root, ent->d_name);
93 dir_bus = opendir(path_bus);
97 ent_bus = readdir(dir_bus);
98 for (; ent_bus != NULL; ent_bus = readdir(dir_bus)) {
99 if (sscanf(ent->d_name, "%03d", &num) != 1)
102 snprintf(path_dev, sizeof(path_dev), "%s/%s/%s",
103 path_root, ent->d_name, ent_bus->d_name);
105 fd = open(path_dev, O_RDWR);
109 ret = read(fd, &desc.d, sizeof(desc.d));
110 if (ret != sizeof(desc.d)) {
111 fprintf(stderr, "desc read: %d/%zd: ", ret, sizeof(desc.d));
116 if (desc.d.bDescriptorType != USB_DT_DEVICE) {
117 fprintf(stderr, "%s: bad DT: 0x%02x\n",
118 path_dev, desc.d.bDescriptorType);
122 if (desc.d.idVendor == vendor && desc.d.idProduct == product)
139 if (desc.d.bNumConfigurations != 1) {
140 fprintf(stderr, "unexpected bNumConfigurations: %u\n",
141 desc.d.bNumConfigurations);
145 /* walk through all descriptors */
148 ret = read(fd, &desc.hdr, sizeof(desc.hdr));
151 if (ret != sizeof(desc.hdr)) {
152 fprintf(stderr, "desc.hdr read: %d/%zd: ", ret, sizeof(desc.hdr));
157 ret = (int)lseek(fd, -sizeof(desc.hdr), SEEK_CUR);
163 ret = read(fd, &desc, desc.hdr.bLength);
164 if (ret != desc.hdr.bLength) {
165 fprintf(stderr, "desc read: %d/%u: ", ret, desc.hdr.bLength);
170 switch (desc.hdr.bDescriptorType) {
172 if (desc.c.bNumInterfaces != 2) {
173 fprintf(stderr, "unexpected bNumInterfaces: %u\n",
174 desc.c.bNumInterfaces);
179 case USB_DT_INTERFACE:
180 if (desc.i.bInterfaceClass != USB_CLASS_HID
181 || desc.i.bInterfaceSubClass != 0
182 || desc.i.bInterfaceProtocol != 0) {
183 fprintf(stderr, "unexpected interface %x:%x:%x\n",
184 desc.i.bInterfaceClass, desc.i.bInterfaceSubClass,
185 desc.i.bInterfaceProtocol);
188 if (desc.i.bNumEndpoints != 2) {
189 fprintf(stderr, "unexpected bNumEndpoints: %u\n",
190 desc.i.bNumEndpoints);
196 case USB_DT_ENDPOINT:
197 if (iface < 0 || iface >= ARRAY_SIZE(dev->ifaces)) {
198 fprintf(stderr, "bad iface: %d\n", iface);
201 if (desc.e.wMaxPacketSize != 64 && desc.e.wMaxPacketSize != 32) {
202 fprintf(stderr, "iface %d, EP %02x: "
203 "unexpected wMaxPacketSize: %u\n",
204 iface, desc.e.bEndpointAddress, desc.e.wMaxPacketSize);
207 if (desc.e.bEndpointAddress & 0x80)
208 dev->ifaces[iface].ep_in = desc.e.bEndpointAddress; // & 0x7F;
210 dev->ifaces[iface].ep_out = desc.e.bEndpointAddress;
218 fprintf(stderr, "skipping desc 0x%02x\n",
219 desc.hdr.bDescriptorType);
224 /* claim interfaces */
225 for (iface = 0; iface < ARRAY_SIZE(dev->ifaces); iface++) {
226 struct usbdevfs_ioctl usbio;
228 if (dev->ifaces[iface].ep_in == -1) {
229 fprintf(stderr, "missing ep_in, iface: %d\n", iface);
232 if (dev->ifaces[iface].ep_out == -1) {
233 fprintf(stderr, "missing ep_out, iface: %d\n", iface);
237 /* disconnect default driver */
238 memset(&usbio, 0, sizeof(usbio));
240 usbio.ioctl_code = USBDEVFS_DISCONNECT;
241 ret = ioctl(fd, USBDEVFS_IOCTL, &usbio);
242 if (ret != 0 && errno != ENODATA)
243 perror("USBDEVFS_DISCONNECT");
245 ret = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &iface);
247 perror("USBDEVFS_CLAIMINTERFACE");
265 static int enable_echo(int enable)
267 const char *portname = "/dev/tty";
273 memset(&tty, 0, sizeof(tty));
275 fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
277 fprintf(stderr, "open %s: ", portname);
282 ret = tcgetattr(fd, &tty);
288 // printf("lflag: 0%o\n", tty.c_lflag);
290 tty.c_lflag |= ECHO | ICANON;
292 tty.c_lflag &= ~(ECHO | ICANON);
293 tty.c_cc[VMIN] = tty.c_cc[VTIME] = 0;
296 ret = tcsetattr(fd, TCSANOW, &tty);
311 static void signal_handler(int sig)
314 signal(sig, SIG_DFL);
320 MDBTN_DOWN = (1 << 1),
321 MDBTN_LEFT = (1 << 2),
322 MDBTN_RIGHT = (1 << 3),
326 MDBTN_START = (1 << 7),
330 MDBTN_MODE = (1 << 11),
333 #define BTN_JOY BTN_JOYSTICK
334 #define BTN_GP BTN_GAMEPAD
336 static const uint32_t evdev_md_default_map[KEY_CNT] = {
338 [KEY_DOWN] = MDBTN_DOWN,
339 [KEY_LEFT] = MDBTN_LEFT,
340 [KEY_RIGHT] = MDBTN_RIGHT,
347 [KEY_F] = MDBTN_MODE,
348 [KEY_ENTER] = MDBTN_START,
349 // joystick, assume diamond face button layout 1
352 [BTN_JOY + 0] = MDBTN_X,
353 [BTN_JOY + 1] = MDBTN_C,
354 [BTN_JOY + 2] = MDBTN_B,
355 [BTN_JOY + 3] = MDBTN_A,
356 [BTN_JOY + 4] = MDBTN_Y,
357 [BTN_JOY + 5] = MDBTN_Z,
358 [BTN_JOY + 6] = MDBTN_START,
359 [BTN_JOY + 7] = MDBTN_MODE,
360 [BTN_JOY + 9] = MDBTN_START,
362 [BTN_GP + 0] = MDBTN_A,
363 [BTN_GP + 1] = MDBTN_B,
364 [BTN_GP + 2] = MDBTN_C,
365 [BTN_GP + 3] = MDBTN_X,
366 [BTN_GP + 4] = MDBTN_Y,
367 [BTN_GP + 5] = MDBTN_Z,
368 [BTN_GP + 6] = MDBTN_START,
369 [BTN_GP + 7] = MDBTN_MODE,
370 [BTN_GP + 9] = MDBTN_START,
372 [KEY_HOME] = MDBTN_A,
373 [KEY_PAGEDOWN] = MDBTN_B,
375 [KEY_LEFTALT] = MDBTN_START,
378 static const uint16_t bind_to_mask[256] = {
391 ['0'] = 0, // to unbind a key
394 static struct player_state {
400 uint32_t kc_map[KEY_CNT];
405 } abs[2]; // more abs on TODO (problems like noisy analogs)
410 #define printf_v(l_, fmt_, ...) do { \
411 if (verbose >= (l_)) \
412 fprintf(stderr, fmt_, ##__VA_ARGS__); \
415 static int do_evdev_input(struct evdev_dev *dev)
417 struct player_state *player;
418 struct input_event ev;
419 uint32_t mask_clear = 0;
420 uint32_t mask_set = 0;
424 ret = read(dev->fd, &ev, sizeof(ev));
425 if (ret != sizeof(ev)) {
426 fprintf(stderr, "%tu, p%u: evdev read %d/%zd: ",
427 dev - devs, dev->player, ret, sizeof(ev));
436 if (dev->player >= ARRAY_SIZE(players)) {
437 fprintf(stderr, "bad player: %u\n", dev->player);
440 player = &players[dev->player];
441 old_state = player->state;
443 if (ev.type == EV_ABS) {
446 if (ev.code >= ARRAY_SIZE(dev->abs)) {
447 printf_v(2, "abs id %u is too large\n", ev.code);
450 printf_v(1, "%tu p%u: abs %u: %4d %4d %4d (%d)\n",
451 dev - devs, dev->player, ev.code,
452 dev->abs[ev.code].min, ev.value,
453 dev->abs[ev.code].max, dev->abs[ev.code].zone);
455 l = (ev.code & 1) ? MDBTN_UP : MDBTN_LEFT;
456 h = (ev.code & 1) ? MDBTN_DOWN : MDBTN_RIGHT;
458 if (ev.value < dev->abs[ev.code].min + dev->abs[ev.code].zone)
460 else if (ev.value > dev->abs[ev.code].max - dev->abs[ev.code].zone)
463 else if (ev.type == EV_KEY) {
464 if (ev.value != 0 && ev.value != 1)
467 if ((uint32_t)ev.code >= ARRAY_SIZE(dev->kc_map)) {
468 fprintf(stderr, "evdev read bad key: %u\n", ev.code);
472 if (ev.value) // press?
473 mask_set = dev->kc_map[ev.code];
475 mask_clear = dev->kc_map[ev.code];
481 printf_v(1, "%tu p%u: c %03x, s %03x\n",
482 dev - devs, dev->player, mask_clear, mask_set);
484 player->state &= ~mask_clear;
485 player->state |= mask_set;
487 player->dirty |= old_state != player->state;
488 return player->dirty;
491 static int open_evdev(struct evdev_dev *dev, char *str_in)
493 uint32_t event_support = 0;
494 uint32_t abs_support = 0;
495 struct input_absinfo absi;
496 const char *name = str_in;
497 char *p, *s, *binds = NULL;
501 p = strchr(str_in, ',');
508 i = strtol(name, &p, 0);
509 if (p != NULL && *p == 0) {
510 snprintf(buf, sizeof(buf), "/dev/input/event%d", i);
514 fd = open(name, O_RDONLY);
516 fprintf(stderr, "open %s: ", name);
520 ret = ioctl(fd, EVIOCGBIT(0, sizeof(event_support)),
524 if (!(event_support & ((1 << EV_KEY) | (1 << EV_ABS)))) {
525 fprintf(stderr, "%s doesn't have keys or abs\n", name);
532 if (event_support & (1 << EV_ABS)) {
533 ret = ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_support)),
537 for (i = 0; i < ARRAY_SIZE(dev->abs); i++) {
538 if (!(abs_support & (1 << i)))
540 ret = ioctl(fd, EVIOCGABS(i), &absi);
545 dev->abs[i].min = absi.minimum;
546 dev->abs[i].max = absi.maximum;
547 dev->abs[i].zone = (absi.maximum - absi.minimum) / 3;
551 memcpy(dev->kc_map, evdev_md_default_map, sizeof(dev->kc_map));
553 unsigned int kc, end = 0;
558 for (; *p != 0 && *p != ','; p++)
564 if (strncmp(s, "j=", 2) == 0) {
568 else if (strncmp(s, "g=", 2) == 0) {
573 ret = sscanf(s, "%u=", &kc);
574 if (ret != 1 || (s = strchr(s, '=')) == NULL) {
575 fprintf(stderr, "parse failed: '%s'\n", s);
581 for (; *s != 0 && kc < sizeof(dev->kc_map); s++, kc++) {
582 uint32_t mask = bind_to_mask[(uint8_t)*s];
583 if (mask == 0 && *s != '0') {
584 fprintf(stderr, "%s: '%c' is not a valid MD btn\n", name, *s);
587 dev->kc_map[kc] = mask;
596 static void do_stdin_input(uint32_t *mode, int *changed)
601 ret = read(STDIN_FILENO, &c, 1);
603 perror("read stdin");
609 printf("3btn mode\n");
610 *mode = OP_MODE_3BTN;
614 printf("6btn mode\n");
615 *mode = OP_MODE_6BTN;
619 printf("teamplayer mode\n");
620 *mode = OP_MODE_TEAMPLAYER;
626 static int submit_urb(int fd, struct usbdevfs_urb *urb, int ep,
627 void *buf, size_t buf_size)
629 memset(urb, 0, sizeof(*urb));
630 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
633 urb->buffer_length = buf_size;
635 return ioctl(fd, USBDEVFS_SUBMITURB, urb);
645 static void usage(const char *argv0)
647 fprintf(stderr, "usage:\n%s <-e player /dev/input/node[,binds]>*\n"
648 " [-m <mode>] [-v]\n\n"
649 " binds: <keycode=mdbtns>[,keycode=mdbtns]*\n"
650 " keycode: first keycode (int), can be j,g for joy,gamepad btn0\n"
651 " mdbtns: sequence of chars from: udlrabcsxyzm0\n"
652 " (u=up, d=down, ..., 0=unbind)\n"
653 " mode: int 0-2: 3btn 6btn teamplayer\n", argv0);
657 static void bad_arg(char *argv[], int a)
659 fprintf(stderr, "bad arg %d: '%s'\n", a, argv[a]);
663 int main(int argc, char *argv[])
665 struct teensy_dev dev;
666 struct usbdevfs_urb urb[URB_CNT];
667 struct usbdevfs_urb *reaped_urb;
670 int pending_urbs = 0;
673 int mode_changed = 0;
674 char buf_dbg[64 + 1];
675 struct tp_pkt pkt_in;
676 struct tp_pkt pkt_out;
677 struct timeval *timeout = NULL;
679 uint32_t mode = OP_MODE_3BTN;
683 for (i = 1; i < argc; i++) {
684 if (argv[i][0] == '-') {
685 switch (argv[i][1] | (argv[i][2] << 8)) {
687 if (argv[++i] == NULL)
689 player = strtoul(argv[i], NULL, 0);
690 if (player >= ARRAY_SIZE(players))
693 if (argv[++i] == NULL)
695 if (dev_cnt >= ARRAY_SIZE(devs)) {
696 fprintf(stderr, "too many evdevs\n");
699 ret = open_evdev(&devs[dev_cnt], argv[i]);
702 devs[dev_cnt].player = player;
706 if (argv[++i] == NULL)
708 mode = strtoul(argv[i], NULL, 0);
723 signal(SIGINT, signal_handler);
727 while (!g_exit || (pending_urbs & (1 << URB_DATA_OUT)))
730 ret = find_device(&dev, 0x16C0, 0x0486);
736 printf("waiting for device...\n");
746 /* we wait first, then send commands, but if teensy
747 * is started already, it won't send anything back */
753 if (!(pending_urbs & (1 << URB_DATA_IN))) {
754 memset(&pkt_in, 0, sizeof(pkt_in));
755 ret = submit_urb(dev.fd, &urb[URB_DATA_IN], dev.ifaces[0].ep_in,
756 &pkt_in, sizeof(pkt_in));
758 perror("USBDEVFS_SUBMITURB URB_DATA_IN");
762 pending_urbs |= 1 << URB_DATA_IN;
764 if (!(pending_urbs & (1 << URB_DBG_IN))) {
765 ret = submit_urb(dev.fd, &urb[URB_DBG_IN], dev.ifaces[1].ep_in,
766 buf_dbg, sizeof(buf_dbg) - 1);
768 perror("USBDEVFS_SUBMITURB URB_DBG_IN");
772 pending_urbs |= 1 << URB_DBG_IN;
776 FD_SET(STDIN_FILENO, &rfds);
777 for (i = 0; i < dev_cnt; i++)
778 if (devs[i].fd != -1)
779 FD_SET(devs[i].fd, &rfds);
782 FD_SET(dev.fd, &wfds);
784 ret = select(dev.fd + 1, &rfds, &wfds, NULL, timeout);
791 /* something form stdin? */
792 if (FD_ISSET(STDIN_FILENO, &rfds))
793 do_stdin_input(&mode, &mode_changed);
795 /* something from input devices? */
797 for (i = 0; i < dev_cnt; i++) {
798 if (devs[i].fd != -1 && FD_ISSET(devs[i].fd, &rfds)) {
799 do_evdev_input(&devs[i]);
804 /* collect any other input changes before starting
805 * the slow USB transfer to teensy */
806 tout.tv_sec = tout.tv_usec = 0;
811 /* something from USB? */
812 if (FD_ISSET(dev.fd, &wfds))
814 unsigned int which_urb;
817 ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
821 perror("USBDEVFS_REAPURB");
824 which_urb = reaped_urb - urb;
825 if (which_urb < ARRAY_SIZE(urb))
826 pending_urbs &= ~(1 << which_urb);
828 fprintf(stderr, "reaped unknown urb: %p #%u",
829 reaped_urb, which_urb);
832 if (reaped_urb != NULL && reaped_urb->status != 0) {
833 errno = -reaped_urb->status;
834 fprintf(stderr, "urb #%u: ", which_urb);
836 if (reaped_urb->status == -EILSEQ) {
837 /* this is usually a sign of disconnect.. */
842 else if (reaped_urb == &urb[URB_DATA_IN])
844 /* some request from teensy */
845 printf("rx data?\n");
847 else if (reaped_urb == &urb[URB_DATA_OUT])
850 else if (reaped_urb == &urb[URB_DBG_IN])
853 buf_dbg[reaped_urb->actual_length] = 0;
854 printf("%s", buf_dbg);
856 // continue receiving debug before sending out stuff
863 fprintf(stderr, "reaped unknown urb? %p #%zu\n",
864 reaped_urb, reaped_urb - urb);
868 /* something to send? */
869 if (pending_urbs & (1 << URB_DATA_OUT))
870 // can't do that yet - out urb still busy
874 memset(&pkt_out, 0, sizeof(pkt_out));
875 pkt_out.type = PKT_UPD_MODE;
878 ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
879 &pkt_out, sizeof(pkt_out));
881 perror("USBDEVFS_SUBMITURB PKT_STREAM_ENABLE");
884 pending_urbs |= 1 << URB_DATA_OUT;
889 /* send buttons if there were any changes */
890 memset(&pkt_out, 0, sizeof(pkt_out));
891 for (i = 0; i < ARRAY_SIZE(players); i++) {
892 if (players[i].dirty)
893 pkt_out.changed_players |= 1 << i;
894 players[i].dirty = 0;
896 pkt_out.bnts[i] = players[i].state;
898 if (pkt_out.changed_players != 0) {
899 pkt_out.type = PKT_UPD_BTNS;
901 ret = submit_urb(dev.fd, &urb[URB_DATA_OUT], dev.ifaces[0].ep_out,
902 &pkt_out, sizeof(pkt_out));
904 perror("USBDEVFS_SUBMITURB PKT_FIXED_STATE");
907 pending_urbs |= 1 << URB_DATA_OUT;
921 /* deal with pending URBs */
922 if (pending_urbs & (1 << URB_DATA_IN))
923 ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DATA_IN]);
924 if (pending_urbs & (1 << URB_DBG_IN))
925 ioctl(dev.fd, USBDEVFS_DISCARDURB, &urb[URB_DBG_IN]);
926 for (i = 0; i < URB_CNT; i++) {
927 if (pending_urbs & (1 << i)) {
928 ret = ioctl(dev.fd, USBDEVFS_REAPURB, &reaped_urb);
930 perror("USBDEVFS_REAPURB");
940 // vim: ts=2:sw=2:expandtab