joystick_linux.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. #ifdef UDEV_ENABLED
  43. static const char* ignore_str = "/dev/input/js";
  44. #endif
  45. joystick_linux::Joystick::Joystick() {
  46. fd = -1;
  47. dpad = 0;
  48. devpath = "";
  49. for (int i = 0; i < MAX_ABS; i++) {
  50. abs_info[i] = NULL;
  51. }
  52. }
  53. joystick_linux::Joystick::~Joystick() {
  54. for (int i = 0; i < MAX_ABS; i++) {
  55. if (abs_info[i]) {
  56. memdelete(abs_info[i]);
  57. }
  58. }
  59. }
  60. void joystick_linux::Joystick::reset() {
  61. dpad = 0;
  62. fd = -1;
  63. InputDefault::JoyAxis jx;
  64. jx.min = -1;
  65. jx.value = 0.0f;
  66. for (int i=0; i < MAX_ABS; i++) {
  67. abs_map[i] = -1;
  68. curr_axis[i] = jx;
  69. }
  70. }
  71. joystick_linux::joystick_linux(InputDefault *in)
  72. {
  73. exit_udev = false;
  74. input = in;
  75. joy_mutex = Mutex::create();
  76. joy_thread = Thread::create(joy_thread_func, this);
  77. }
  78. joystick_linux::~joystick_linux() {
  79. exit_udev = true;
  80. Thread::wait_to_finish(joy_thread);
  81. memdelete(joy_thread);
  82. memdelete(joy_mutex);
  83. close_joystick();
  84. }
  85. void joystick_linux::joy_thread_func(void *p_user) {
  86. if (p_user) {
  87. joystick_linux* joy = (joystick_linux*) p_user;
  88. joy->run_joystick_thread();
  89. }
  90. return;
  91. }
  92. void joystick_linux::run_joystick_thread() {
  93. #ifdef UDEV_ENABLED
  94. udev *_udev = udev_new();
  95. ERR_FAIL_COND(!_udev);
  96. enumerate_joysticks(_udev);
  97. monitor_joysticks(_udev);
  98. udev_unref(_udev);
  99. #else
  100. monitor_joysticks();
  101. #endif
  102. }
  103. #ifdef UDEV_ENABLED
  104. void joystick_linux::enumerate_joysticks(udev *p_udev) {
  105. udev_enumerate *enumerate;
  106. udev_list_entry *devices, *dev_list_entry;
  107. udev_device *dev;
  108. enumerate = udev_enumerate_new(p_udev);
  109. udev_enumerate_add_match_subsystem(enumerate,"input");
  110. udev_enumerate_add_match_property(enumerate, "ID_INPUT_JOYSTICK", "1");
  111. udev_enumerate_scan_devices(enumerate);
  112. devices = udev_enumerate_get_list_entry(enumerate);
  113. udev_list_entry_foreach(dev_list_entry, devices) {
  114. const char* path = udev_list_entry_get_name(dev_list_entry);
  115. dev = udev_device_new_from_syspath(p_udev, path);
  116. const char* devnode = udev_device_get_devnode(dev);
  117. if (devnode) {
  118. String devnode_str = devnode;
  119. if (devnode_str.find(ignore_str) == -1) {
  120. joy_mutex->lock();
  121. open_joystick(devnode);
  122. joy_mutex->unlock();
  123. }
  124. }
  125. udev_device_unref(dev);
  126. }
  127. udev_enumerate_unref(enumerate);
  128. }
  129. void joystick_linux::monitor_joysticks(udev *p_udev) {
  130. udev_device *dev = NULL;
  131. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  132. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
  133. udev_monitor_enable_receiving(mon);
  134. int fd = udev_monitor_get_fd(mon);
  135. while (!exit_udev) {
  136. fd_set fds;
  137. struct timeval tv;
  138. int ret;
  139. FD_ZERO(&fds);
  140. FD_SET(fd, &fds);
  141. tv.tv_sec = 0;
  142. tv.tv_usec = 0;
  143. ret = select(fd+1, &fds, NULL, NULL, &tv);
  144. /* Check if our file descriptor has received data. */
  145. if (ret > 0 && FD_ISSET(fd, &fds)) {
  146. /* Make the call to receive the device.
  147. select() ensured that this will not block. */
  148. dev = udev_monitor_receive_device(mon);
  149. if (dev && udev_device_get_devnode(dev) != 0) {
  150. joy_mutex->lock();
  151. String action = udev_device_get_action(dev);
  152. const char* devnode = udev_device_get_devnode(dev);
  153. if (devnode) {
  154. String devnode_str = devnode;
  155. if (devnode_str.find(ignore_str) == -1) {
  156. if (action == "add")
  157. open_joystick(devnode);
  158. else if (String(action) == "remove")
  159. close_joystick(get_joy_from_path(devnode));
  160. }
  161. }
  162. udev_device_unref(dev);
  163. joy_mutex->unlock();
  164. }
  165. }
  166. usleep(50000);
  167. }
  168. udev_monitor_unref(mon);
  169. }
  170. #endif
  171. void joystick_linux::monitor_joysticks() {
  172. while (!exit_udev) {
  173. joy_mutex->lock();
  174. for (int i = 0; i < 32; i++) {
  175. char fname[64];
  176. sprintf(fname, "/dev/input/event%d", i);
  177. if (attached_devices.find(fname) == -1) {
  178. open_joystick(fname);
  179. }
  180. }
  181. joy_mutex->unlock();
  182. usleep(1000000); // 1s
  183. }
  184. }
  185. int joystick_linux::get_free_joy_slot() const {
  186. for (int i = 0; i < JOYSTICKS_MAX; i++) {
  187. if (joysticks[i].fd == -1) return i;
  188. }
  189. return -1;
  190. }
  191. int joystick_linux::get_joy_from_path(String p_path) const {
  192. for (int i = 0; i < JOYSTICKS_MAX; i++) {
  193. if (joysticks[i].devpath == p_path) {
  194. return i;
  195. }
  196. }
  197. return -2;
  198. }
  199. void joystick_linux::close_joystick(int p_id) {
  200. if (p_id == -1) {
  201. for (int i=0; i<JOYSTICKS_MAX; i++) {
  202. close_joystick(i);
  203. };
  204. return;
  205. }
  206. else if (p_id < 0) return;
  207. Joystick &joy = joysticks[p_id];
  208. if (joy.fd != -1) {
  209. close(joy.fd);
  210. joy.fd = -1;
  211. attached_devices.remove(attached_devices.find(joy.devpath));
  212. input->joy_connection_changed(p_id, false, "");
  213. };
  214. };
  215. static String _hex_str(uint8_t p_byte) {
  216. static const char* dict = "0123456789abcdef";
  217. char ret[3];
  218. ret[2] = 0;
  219. ret[0] = dict[p_byte>>4];
  220. ret[1] = dict[p_byte & 0xF];
  221. return ret;
  222. };
  223. void joystick_linux::setup_joystick_properties(int p_id) {
  224. Joystick* joy = &joysticks[p_id];
  225. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  226. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  227. int num_buttons = 0;
  228. int num_axes = 0;
  229. if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  230. (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  231. return;
  232. }
  233. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  234. if (test_bit(i, keybit)) {
  235. joy->key_map[i] = num_buttons++;
  236. }
  237. }
  238. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  239. if (test_bit(i, keybit)) {
  240. joy->key_map[i] = num_buttons++;
  241. }
  242. }
  243. for (int i = 0; i < ABS_MISC; ++i) {
  244. /* Skip hats */
  245. if (i == ABS_HAT0X) {
  246. i = ABS_HAT3Y;
  247. continue;
  248. }
  249. if (test_bit(i, absbit)) {
  250. joy->abs_map[i] = num_axes++;
  251. joy->abs_info[i] = memnew(input_absinfo);
  252. if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) {
  253. memdelete(joy->abs_info[i]);
  254. joy->abs_info[i] = NULL;
  255. }
  256. }
  257. }
  258. joy->force_feedback = false;
  259. joy->ff_effect_timestamp = 0;
  260. unsigned long ffbit[NBITS(FF_CNT)];
  261. if (ioctl(joy->fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
  262. if (test_bit(FF_RUMBLE, ffbit)) {
  263. joy->force_feedback = true;
  264. }
  265. }
  266. }
  267. void joystick_linux::open_joystick(const char *p_path) {
  268. int joy_num = get_free_joy_slot();
  269. int fd = open(p_path, O_RDWR | O_NONBLOCK);
  270. if (fd != -1 && joy_num != -1) {
  271. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  272. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  273. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  274. // add to attached devices so we don't try to open it again
  275. attached_devices.push_back(String(p_path));
  276. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  277. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  278. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  279. close(fd);
  280. return;
  281. }
  282. //check if the device supports basic gamepad events, prevents certain keyboards from
  283. //being detected as joysticks
  284. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
  285. (test_bit(ABS_X, absbit) || test_bit(ABS_Y, absbit) || test_bit(ABS_HAT0X, absbit) ||
  286. test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) &&
  287. (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) ||
  288. test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit)))) {
  289. close(fd);
  290. return;
  291. }
  292. char uid[128];
  293. char namebuf[128];
  294. String name = "";
  295. input_id inpid;
  296. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  297. name = namebuf;
  298. }
  299. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  300. close(fd);
  301. return;
  302. }
  303. joysticks[joy_num].reset();
  304. Joystick &joy = joysticks[joy_num];
  305. joy.fd = fd;
  306. joy.devpath = String(p_path);
  307. setup_joystick_properties(joy_num);
  308. sprintf(uid, "%04x%04x", __bswap_16(inpid.bustype), 0);
  309. if (inpid.vendor && inpid.product && inpid.version) {
  310. uint16_t vendor = __bswap_16(inpid.vendor);
  311. uint16_t product = __bswap_16(inpid.product);
  312. uint16_t version = __bswap_16(inpid.version);
  313. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor,0,product,0,version,0);
  314. input->joy_connection_changed(joy_num, true, name, uid);
  315. }
  316. else {
  317. String uidname = uid;
  318. int uidlen = MIN(name.length(), 11);
  319. for (int i=0; i<uidlen; i++) {
  320. uidname = uidname + _hex_str(name[i]);
  321. }
  322. uidname += "00";
  323. input->joy_connection_changed(joy_num, true, name, uidname);
  324. }
  325. }
  326. }
  327. void joystick_linux::joystick_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp)
  328. {
  329. Joystick& joy = joysticks[p_id];
  330. if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  331. return;
  332. }
  333. if (joy.ff_effect_id != -1) {
  334. joystick_vibration_stop(p_id, p_timestamp);
  335. }
  336. struct ff_effect effect;
  337. effect.type = FF_RUMBLE;
  338. effect.id = -1;
  339. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  340. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  341. effect.replay.length = floor(p_duration * 1000);
  342. effect.replay.delay = 0;
  343. if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) {
  344. return;
  345. }
  346. struct input_event play;
  347. play.type = EV_FF;
  348. play.code = effect.id;
  349. play.value = 1;
  350. write(joy.fd, (const void*)&play, sizeof(play));
  351. joy.ff_effect_id = effect.id;
  352. joy.ff_effect_timestamp = p_timestamp;
  353. }
  354. void joystick_linux::joystick_vibration_stop(int p_id, uint64_t p_timestamp)
  355. {
  356. Joystick& joy = joysticks[p_id];
  357. if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
  358. return;
  359. }
  360. if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) {
  361. return;
  362. }
  363. joy.ff_effect_id = -1;
  364. joy.ff_effect_timestamp = p_timestamp;
  365. }
  366. InputDefault::JoyAxis joystick_linux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  367. int min = p_abs->minimum;
  368. int max = p_abs->maximum;
  369. InputDefault::JoyAxis jx;
  370. if (min < 0) {
  371. jx.min = -1;
  372. if (p_value < 0) {
  373. jx.value = (float) -p_value / min;
  374. }
  375. jx.value = (float) p_value / max;
  376. }
  377. if (min == 0) {
  378. jx.min = 0;
  379. jx.value = 0.0f + (float) p_value / max;
  380. }
  381. return jx;
  382. }
  383. uint32_t joystick_linux::process_joysticks(uint32_t p_event_id) {
  384. if (joy_mutex->try_lock() != OK) {
  385. return p_event_id;
  386. }
  387. for (int i=0; i<JOYSTICKS_MAX; i++) {
  388. if (joysticks[i].fd == -1) continue;
  389. input_event events[32];
  390. Joystick* joy = &joysticks[i];
  391. int len;
  392. while ((len = read(joy->fd, events, (sizeof events))) > 0) {
  393. len /= sizeof(events[0]);
  394. for (int j = 0; j < len; j++) {
  395. input_event &ev = events[j];
  396. // ev may be tainted and out of MAX_KEY range, which will cause
  397. // joy->key_map[ev.code] to crash
  398. if( ev.code < 0 || ev.code >= MAX_KEY )
  399. return p_event_id;
  400. switch (ev.type) {
  401. case EV_KEY:
  402. p_event_id = input->joy_button(p_event_id, i, joy->key_map[ev.code], ev.value);
  403. break;
  404. case EV_ABS:
  405. switch (ev.code) {
  406. case ABS_HAT0X:
  407. if (ev.value != 0) {
  408. if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_LEFT;
  409. else joy->dpad |= InputDefault::HAT_MASK_RIGHT;
  410. }
  411. else joy->dpad &= ~(InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_RIGHT);
  412. p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
  413. break;
  414. case ABS_HAT0Y:
  415. if (ev.value != 0) {
  416. if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_UP;
  417. else joy->dpad |= InputDefault::HAT_MASK_DOWN;
  418. }
  419. else joy->dpad &= ~(InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_DOWN);
  420. p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
  421. break;
  422. default:
  423. if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
  424. InputDefault::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
  425. joy->curr_axis[joy->abs_map[ev.code]] = value;
  426. }
  427. break;
  428. }
  429. break;
  430. }
  431. }
  432. }
  433. for (int j = 0; j < MAX_ABS; j++) {
  434. int index = joy->abs_map[j];
  435. if (index != -1) {
  436. p_event_id = input->joy_axis(p_event_id, i, index, joy->curr_axis[index]);
  437. }
  438. }
  439. if (len == 0 || (len < 0 && errno != EAGAIN)) {
  440. close_joystick(i);
  441. };
  442. if (joy->force_feedback) {
  443. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  444. if (timestamp > joy->ff_effect_timestamp) {
  445. Vector2 strength = input->get_joy_vibration_strength(i);
  446. float duration = input->get_joy_vibration_duration(i);
  447. if (strength.x == 0 && strength.y == 0) {
  448. joystick_vibration_stop(i, timestamp);
  449. } else {
  450. joystick_vibration_start(i, strength.x, strength.y, duration, timestamp);
  451. }
  452. }
  453. }
  454. }
  455. joy_mutex->unlock();
  456. return p_event_id;
  457. }
  458. #endif