joystick_linux.cpp 15 KB

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