joystick_linux.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /*************************************************************************/
  2. /* joystick_linux.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. //author: Andreas Haas <hondres, [email protected]>
  30. #ifdef JOYDEV_ENABLED
  31. #include "joystick_linux.h"
  32. #include <linux/input.h>
  33. #include <unistd.h>
  34. #include <fcntl.h>
  35. #include <errno.h>
  36. #ifdef UDEV_ENABLED
  37. #include <libudev.h>
  38. #endif
  39. #define LONG_BITS (sizeof(long) * 8)
  40. #define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
  41. #define NBITS(x) ((((x)-1)/LONG_BITS)+1)
  42. static const char* ignore_str = "/dev/input/js";
  43. joystick_linux::Joystick::Joystick() {
  44. fd = -1;
  45. dpad = 0;
  46. devpath = "";
  47. for (int i = 0; i < MAX_ABS; i++) {
  48. abs_info[i] = NULL;
  49. }
  50. }
  51. joystick_linux::Joystick::~Joystick() {
  52. for (int i = 0; i < MAX_ABS; i++) {
  53. if (abs_info[i]) {
  54. memdelete(abs_info[i]);
  55. }
  56. }
  57. }
  58. void joystick_linux::Joystick::reset() {
  59. dpad = 0;
  60. fd = -1;
  61. InputDefault::JoyAxis jx;
  62. jx.min = -1;
  63. jx.value = 0.0f;
  64. for (int i=0; i < MAX_ABS; i++) {
  65. abs_map[i] = -1;
  66. curr_axis[i] = jx;
  67. }
  68. }
  69. joystick_linux::joystick_linux(InputDefault *in)
  70. {
  71. exit_udev = false;
  72. input = in;
  73. joy_mutex = Mutex::create();
  74. joy_thread = Thread::create(joy_thread_func, this);
  75. }
  76. joystick_linux::~joystick_linux() {
  77. exit_udev = true;
  78. Thread::wait_to_finish(joy_thread);
  79. close_joystick();
  80. }
  81. void joystick_linux::joy_thread_func(void *p_user) {
  82. if (p_user) {
  83. joystick_linux* joy = (joystick_linux*) p_user;
  84. joy->run_joystick_thread();
  85. }
  86. return;
  87. }
  88. void joystick_linux::run_joystick_thread() {
  89. #ifdef UDEV_ENABLED
  90. udev *_udev = udev_new();
  91. ERR_FAIL_COND(!_udev);
  92. enumerate_joysticks(_udev);
  93. monitor_joysticks(_udev);
  94. udev_unref(_udev);
  95. #else
  96. monitor_joysticks();
  97. #endif
  98. }
  99. #ifdef UDEV_ENABLED
  100. void joystick_linux::enumerate_joysticks(udev *p_udev) {
  101. udev_enumerate *enumerate;
  102. udev_list_entry *devices, *dev_list_entry;
  103. udev_device *dev;
  104. enumerate = udev_enumerate_new(p_udev);
  105. udev_enumerate_add_match_subsystem(enumerate,"input");
  106. udev_enumerate_add_match_property(enumerate, "ID_INPUT_JOYSTICK", "1");
  107. udev_enumerate_scan_devices(enumerate);
  108. devices = udev_enumerate_get_list_entry(enumerate);
  109. udev_list_entry_foreach(dev_list_entry, devices) {
  110. const char* path = udev_list_entry_get_name(dev_list_entry);
  111. dev = udev_device_new_from_syspath(p_udev, path);
  112. const char* devnode = udev_device_get_devnode(dev);
  113. if (devnode) {
  114. String devnode_str = devnode;
  115. if (devnode_str.find(ignore_str) == -1) {
  116. joy_mutex->lock();
  117. open_joystick(devnode);
  118. joy_mutex->unlock();
  119. }
  120. }
  121. udev_device_unref(dev);
  122. }
  123. udev_enumerate_unref(enumerate);
  124. }
  125. void joystick_linux::monitor_joysticks(udev *p_udev) {
  126. udev_device *dev = NULL;
  127. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  128. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
  129. udev_monitor_enable_receiving(mon);
  130. int fd = udev_monitor_get_fd(mon);
  131. while (!exit_udev) {
  132. fd_set fds;
  133. struct timeval tv;
  134. int ret;
  135. FD_ZERO(&fds);
  136. FD_SET(fd, &fds);
  137. tv.tv_sec = 0;
  138. tv.tv_usec = 0;
  139. ret = select(fd+1, &fds, NULL, NULL, &tv);
  140. /* Check if our file descriptor has received data. */
  141. if (ret > 0 && FD_ISSET(fd, &fds)) {
  142. /* Make the call to receive the device.
  143. select() ensured that this will not block. */
  144. dev = udev_monitor_receive_device(mon);
  145. if (dev && udev_device_get_devnode(dev) != 0) {
  146. joy_mutex->lock();
  147. String action = udev_device_get_action(dev);
  148. const char* devnode = udev_device_get_devnode(dev);
  149. if (devnode) {
  150. String devnode_str = devnode;
  151. if (devnode_str.find(ignore_str) == -1) {
  152. if (action == "add")
  153. open_joystick(devnode);
  154. else if (String(action) == "remove")
  155. close_joystick(get_joy_from_path(devnode));
  156. }
  157. }
  158. udev_device_unref(dev);
  159. joy_mutex->unlock();
  160. }
  161. }
  162. usleep(50000);
  163. }
  164. //printf("exit udev\n");
  165. udev_monitor_unref(mon);
  166. }
  167. #endif
  168. void joystick_linux::monitor_joysticks() {
  169. while (!exit_udev) {
  170. joy_mutex->lock();
  171. for (int i = 0; i < 32; i++) {
  172. char fname[64];
  173. sprintf(fname, "/dev/input/event%d", i);
  174. if (attached_devices.find(fname) == -1) {
  175. open_joystick(fname);
  176. }
  177. }
  178. joy_mutex->unlock();
  179. usleep(1000000); // 1s
  180. }
  181. }
  182. int joystick_linux::get_free_joy_slot() const {
  183. for (int i = 0; i < JOYSTICKS_MAX; i++) {
  184. if (joysticks[i].fd == -1) return i;
  185. }
  186. return -1;
  187. }
  188. int joystick_linux::get_joy_from_path(String p_path) const {
  189. for (int i = 0; i < JOYSTICKS_MAX; i++) {
  190. if (joysticks[i].devpath == p_path) {
  191. return i;
  192. }
  193. }
  194. return -2;
  195. }
  196. void joystick_linux::close_joystick(int p_id) {
  197. if (p_id == -1) {
  198. for (int i=0; i<JOYSTICKS_MAX; i++) {
  199. close_joystick(i);
  200. };
  201. return;
  202. }
  203. else if (p_id < 0) return;
  204. Joystick &joy = joysticks[p_id];
  205. if (joy.fd != -1) {
  206. close(joy.fd);
  207. joy.fd = -1;
  208. attached_devices.remove(attached_devices.find(joy.devpath));
  209. input->joy_connection_changed(p_id, false, "");
  210. };
  211. };
  212. static String _hex_str(uint8_t p_byte) {
  213. static const char* dict = "0123456789abcdef";
  214. char ret[3];
  215. ret[2] = 0;
  216. ret[0] = dict[p_byte>>4];
  217. ret[1] = dict[p_byte & 0xF];
  218. return ret;
  219. };
  220. void joystick_linux::setup_joystick_properties(int p_id) {
  221. Joystick* joy = &joysticks[p_id];
  222. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  223. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  224. int num_buttons = 0;
  225. int num_axes = 0;
  226. if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  227. (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  228. return;
  229. }
  230. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  231. if (test_bit(i, keybit)) {
  232. joy->key_map[i] = num_buttons++;
  233. }
  234. }
  235. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  236. if (test_bit(i, keybit)) {
  237. joy->key_map[i] = num_buttons++;
  238. }
  239. }
  240. for (int i = 0; i < ABS_MISC; ++i) {
  241. /* Skip hats */
  242. if (i == ABS_HAT0X) {
  243. i = ABS_HAT3Y;
  244. continue;
  245. }
  246. if (test_bit(i, absbit)) {
  247. joy->abs_map[i] = num_axes++;
  248. joy->abs_info[i] = memnew(input_absinfo);
  249. if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) {
  250. memdelete(joy->abs_info[i]);
  251. joy->abs_info[i] = NULL;
  252. }
  253. }
  254. }
  255. }
  256. void joystick_linux::open_joystick(const char *p_path) {
  257. int joy_num = get_free_joy_slot();
  258. int fd = open(p_path, O_RDONLY | O_NONBLOCK);
  259. if (fd != -1 && joy_num != -1) {
  260. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  261. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  262. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  263. // add to attached devices so we don't try to open it again
  264. attached_devices.push_back(String(p_path));
  265. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  266. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  267. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  268. close(fd);
  269. return;
  270. }
  271. //check if the device supports basic gamepad events, prevents certain keyboards from
  272. //being detected as joysticks
  273. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
  274. (test_bit(ABS_X, absbit) || test_bit(ABS_Y, absbit) || test_bit(ABS_HAT0X, absbit) ||
  275. test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) &&
  276. (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) ||
  277. test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit)))) {
  278. close(fd);
  279. return;
  280. }
  281. char uid[128];
  282. char namebuf[128];
  283. String name = "";
  284. input_id inpid;
  285. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  286. name = namebuf;
  287. }
  288. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  289. close(fd);
  290. return;
  291. }
  292. joysticks[joy_num].reset();
  293. Joystick &joy = joysticks[joy_num];
  294. joy.fd = fd;
  295. joy.devpath = String(p_path);
  296. setup_joystick_properties(joy_num);
  297. sprintf(uid, "%04x%04x", __bswap_16(inpid.bustype), 0);
  298. if (inpid.vendor && inpid.product && inpid.version) {
  299. uint16_t vendor = __bswap_16(inpid.vendor);
  300. uint16_t product = __bswap_16(inpid.product);
  301. uint16_t version = __bswap_16(inpid.version);
  302. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor,0,product,0,version,0);
  303. input->joy_connection_changed(joy_num, true, name, uid);
  304. }
  305. else {
  306. String uidname = uid;
  307. int uidlen = MIN(name.length(), 11);
  308. for (int i=0; i<uidlen; i++) {
  309. uidname = uidname + _hex_str(name[i]);
  310. }
  311. uidname += "00";
  312. input->joy_connection_changed(joy_num, true, name, uidname);
  313. }
  314. }
  315. }
  316. InputDefault::JoyAxis joystick_linux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  317. int min = p_abs->minimum;
  318. int max = p_abs->maximum;
  319. InputDefault::JoyAxis jx;
  320. if (min < 0) {
  321. jx.min = -1;
  322. if (p_value < 0) {
  323. jx.value = (float) -p_value / min;
  324. }
  325. jx.value = (float) p_value / max;
  326. }
  327. if (min == 0) {
  328. jx.min = 0;
  329. jx.value = 0.0f + (float) p_value / max;
  330. }
  331. return jx;
  332. }
  333. uint32_t joystick_linux::process_joysticks(uint32_t p_event_id) {
  334. if (joy_mutex->try_lock() != OK) {
  335. return p_event_id;
  336. }
  337. for (int i=0; i<JOYSTICKS_MAX; i++) {
  338. if (joysticks[i].fd == -1) continue;
  339. input_event events[32];
  340. Joystick* joy = &joysticks[i];
  341. int len;
  342. while ((len = read(joy->fd, events, (sizeof events))) > 0) {
  343. len /= sizeof(events[0]);
  344. for (int j = 0; j < len; j++) {
  345. input_event &ev = events[j];
  346. // ev may be tainted and out of MAX_KEY range, which will cause
  347. // joy->key_map[ev.code] to crash
  348. if( ev.code < 0 || ev.code >= MAX_KEY )
  349. return p_event_id;
  350. switch (ev.type) {
  351. case EV_KEY:
  352. p_event_id = input->joy_button(p_event_id, i, joy->key_map[ev.code], ev.value);
  353. break;
  354. case EV_ABS:
  355. switch (ev.code) {
  356. case ABS_HAT0X:
  357. if (ev.value != 0) {
  358. if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_LEFT;
  359. else joy->dpad |= InputDefault::HAT_MASK_RIGHT;
  360. }
  361. else joy->dpad &= ~(InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_RIGHT);
  362. p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
  363. break;
  364. case ABS_HAT0Y:
  365. if (ev.value != 0) {
  366. if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_UP;
  367. else joy->dpad |= InputDefault::HAT_MASK_DOWN;
  368. }
  369. else joy->dpad &= ~(InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_DOWN);
  370. p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
  371. break;
  372. default:
  373. if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
  374. InputDefault::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
  375. joy->curr_axis[joy->abs_map[ev.code]] = value;
  376. }
  377. break;
  378. }
  379. break;
  380. }
  381. }
  382. }
  383. for (int j = 0; j < MAX_ABS; j++) {
  384. int index = joy->abs_map[j];
  385. if (index != -1) {
  386. p_event_id = input->joy_axis(p_event_id, i, index, joy->curr_axis[index]);
  387. }
  388. }
  389. if (len == 0 || (len < 0 && errno != EAGAIN)) {
  390. close_joystick(i);
  391. };
  392. }
  393. joy_mutex->unlock();
  394. return p_event_id;
  395. }
  396. #endif