Debian Codegraph @

src/joystick.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: 2009 Ingo Ruhnke <[email protected]>
2 // SPDX-FileCopyrightText: 2025 Raphael Rosch <[email protected]>
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include <assert.h>
6 #include <math.h>
7 #include <algorithm>
8 #include <iostream>
9 #include <stdexcept>
10 #include <stdint.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <sstream>
18 #include <unistd.h>
19 #include <linux/joystick.h>
20 #include <glibmm.h>
21
22 #include "evdev_helper.hpp"
23 #include "joystick.hpp"
24 #include "main.hpp"
25
26 std::string get_js_dev_id_from_filename(const std::string& filename)
27 {
28 size_t pos = filename.find_last_of('/');
29 if (pos == std::string::npos)
30 {
31 return filename; // No '/' found, return whole string
32 }
33 return filename.substr(pos + 1);
34 }
35
36 Joystick::Joystick(const std::string& filename_, const std::string& js_id_)
37 : filename(filename_),
38 js_id(js_id_)
39 {
40 fd = get_new_joystick_fd(); // throws on failure
41
42 uint8_t num_axis = 0;
43 uint8_t num_button = 0;
44 ioctl(fd, JSIOCGAXES, &num_axis);
45 ioctl(fd, JSIOCGBUTTONS, &num_button);
46 axis_count = num_axis;
47 button_count = num_button;
48
49 // Get Name
50 char name_c_str[1024];
51 if (ioctl(fd, JSIOCGNAME(sizeof(name_c_str)), name_c_str) < 0)
52 {
53 std::ostringstream str;
54 str << filename << ": " << strerror(errno);
55 throw std::runtime_error(str.str());
56 }
57
58 orig_name = name_c_str;
59 try {
60 name = Glib::convert_with_fallback(name_c_str, "UTF-8", "ISO-8859-1");
61 } catch(Glib::ConvertError& err) {
62 std::cout << err.what() << std::endl;
63 name = name_c_str;
64 }
65
66 axis_state.resize(axis_count);
67
68 auto tmp_usb_id_pair = get_usb_id_pair_from_udev(js_id);
69 if (!tmp_usb_id_pair.first.empty() && !tmp_usb_id_pair.second.empty()) {
70 vendor_id = tmp_usb_id_pair.first;
71 product_id = tmp_usb_id_pair.second;
72 usb_id = vendor_id + ":" + product_id;
73 js_cfg = get_config_for_usb_id(usb_id);
74 js_type = get_js_type_from_config(js_cfg);
75 }
76 connect_js();
77 orig_calibration_data = get_calibration();
78 }
79
80 Joystick::~Joystick()
81 {
82 connection.disconnect();
83 if (fd >= 0)
84 {
85 close(fd);
86 fd = -1;
87 }
88 }
89
90 int
91 Joystick::get_new_joystick_fd()
92 {
93 int tmp_fd = open(filename.c_str(), O_RDONLY);
94 if (tmp_fd < 0)
95 {
96 std::ostringstream str;
97 str << filename << ": " << strerror(errno);
98 throw std::runtime_error(str.str());
99 }
100 return tmp_fd;
101 }
102
103 void
104 Joystick::connect_js()
105 {
106 connection = Glib::signal_io().connect(sigc::mem_fun(this, &Joystick::on_in), fd,
107 Glib::IO_IN | Glib::IO_HUP | Glib::IO_ERR);
108 }
109
110 bool
111 Joystick::try_adopt_device(const std::string& path, const std::string& new_js_id)
112 {
113 int tmp_fd = open(path.c_str(), O_RDONLY);
114 if (tmp_fd < 0)
115 return false;
116
117 char name_c_str[1024];
118 if (ioctl(tmp_fd, JSIOCGNAME(sizeof(name_c_str)), name_c_str) < 0)
119 {
120 close(tmp_fd);
121 return false;
122 }
123 if (orig_name != name_c_str)
124 {
125 close(tmp_fd);
126 return false;
127 }
128
129 auto tmp_usb_id_pair = get_usb_id_pair_from_udev(new_js_id);
130 std::string tmp_usb_id = tmp_usb_id_pair.first + ":" + tmp_usb_id_pair.second;
131 if (!usb_id.empty() && tmp_usb_id != usb_id)
132 {
133 close(tmp_fd);
134 return false;
135 }
136
137 if (fd >= 0)
138 close(fd);
139 connection.disconnect();
140
141 fd = tmp_fd;
142 filename = path;
143 js_id = new_js_id;
144 connect_js();
145 return true;
146 }
147
148 bool
149 Joystick::reconnected()
150 {
151 // Prefer the original node, then scan js0..js31 for the same identity
152 // (name + USB id) so replug order changes can still recover.
153 if (m_verbose)
154 std::cout << "attempting joystick reconnect... " << std::endl;
155
156 if (try_adopt_device(filename, js_id))
157 {
158 if (m_verbose)
159 std::cout << "reconnected on " << filename << std::endl;
160 return true;
161 }
162
163 for (int i = 0; i < 32; ++i)
164 {
165 std::string id = "js" + std::to_string(i);
166 std::string path = "/dev/input/" + id;
167 if (path == filename)
168 continue;
169 if (!Glib::file_test(path, Glib::FILE_TEST_EXISTS))
170 continue;
171 if (try_adopt_device(path, id))
172 {
173 if (m_verbose)
174 std::cout << "reconnected on " << path << " (was rescanned)" << std::endl;
175 return true;
176 }
177 }
178
179 if (m_verbose)
180 std::cout << "reconnect failed for " << orig_name << std::endl;
181 return false;
182 }
183
184
185 std::pair<std::string, std::string>
186 Joystick::get_usb_id_pair_from_udev(const std::string& sysname)
187 {
188 struct udev* udev = udev_new();
189 if (!udev)
190 {
191 std::cout << "udev: Cannot create udev" << std::endl;
192 return {};
193 }
194
195 struct udev_device* input_dev =
196 udev_device_new_from_subsystem_sysname(udev, "input", sysname.c_str());
197 if (!input_dev)
198 {
199 std::cout << filename << ": udev: Unable to find input device " << js_id << std::endl;
200 udev_unref(udev);
201 return {};
202 }
203
204 // Borrowed reference; do not unref
205 struct udev_device* dev =
206 udev_device_get_parent_with_subsystem_devtype(input_dev, "usb", "usb_device");
207 if (!dev)
208 {
209 std::cout << filename << ": udev: Unable to find parent USB device" << std::endl;
210 udev_device_unref(input_dev);
211 udev_unref(udev);
212 return {};
213 }
214
215 const char* vid = udev_device_get_sysattr_value(dev, "idVendor");
216 const char* pid = udev_device_get_sysattr_value(dev, "idProduct");
217 std::string tmp_vendor_id = vid ? vid : "";
218 std::string tmp_product_id = pid ? pid : "";
219
220 udev_device_unref(input_dev);
221 udev_unref(udev);
222 return {tmp_vendor_id, tmp_product_id};
223 }
224
225 bool
226 Joystick::on_in(Glib::IOCondition cond)
227 {
228 if (cond & Glib::IO_IN)
229 {
230 update();
231 }
232
233 if (cond & Glib::IO_HUP)
234 {
235 std::cout << filename << ": joystick got disconnected" << std::endl;
236 connection.disconnect();
237 }
238
239 if (cond & Glib::IO_ERR)
240 {
241 std::cout << filename << ": error while reading from joystick" << std::endl;
242 connection.disconnect();
243 }
244
245 return true;
246 }
247
248 void
249 Joystick::update()
250 {
251 struct js_event event;
252
253 ssize_t len = read(fd, &event, sizeof(event));
254
255 if (len < 0)
256 {
257 std::ostringstream str;
258 str << filename << ": " << strerror(errno);
259 throw std::runtime_error(str.str());
260 }
261 else if (len == sizeof(event))
262 { // ok
263 if (event.type & JS_EVENT_AXIS)
264 {
265 //std::cout << "Axis: " << (int)event.number << " -> " << (int)event.value << std::endl;
266 axis_state[event.number] = event.value;
267 axis_move(event.number, event.value);
268 }
269 else if (event.type & JS_EVENT_BUTTON)
270 {
271 //std::cout << "Button: " << (int)event.number << " -> " << (int)event.value << std::endl;
272 button_press(event.number, event.value);
273 }
274 }
275 else
276 {
277 throw std::runtime_error("Joystick::update(): unknown read error");
278 }
279 }
280
281 std::vector<JoystickDescription>
282 Joystick::get_joysticks()
283 {
284 std::vector<JoystickDescription> joysticks;
285
286 for(int i = 0; i < 32; ++i)
287 {
288 try
289 {
290 std::string js_id = std::string("js") + std::to_string(i);
291 std::string str = std::string("/dev/input/") + js_id;
292
293 if (Glib::file_test(str, Glib::FILE_TEST_EXISTS))
294 {
295 Joystick joystick(str, js_id);
296
297 joysticks.push_back(JoystickDescription(joystick.get_filename(),
298 joystick.get_name(),
299 joystick.get_js_id(),
300 joystick.get_vendor_id(),
301 joystick.get_product_id(),
302 joystick.get_usb_id(),
303 joystick.get_axis_count(),
304 joystick.get_button_count()));
305 }
306 }
307 catch(std::exception& err)
308 {
309 // ok
310 }
311 }
312
313 return joysticks;
314 }
315
316 Joystick::CalibrationData corr2cal(const struct js_corr& corr_)
317 {
318 struct js_corr corr = corr_;
319
320 Joystick::CalibrationData data;
321
322 if (corr.type)
323 {
324 data.calibrate = true;
325 data.invert = (corr.coef[2] < 0 && corr.coef[3] < 0);
326 data.center_min = corr.coef[0];
327 data.center_max = corr.coef[1];
328
329 if (data.invert)
330 {
331 corr.coef[2] = -corr.coef[2];
332 corr.coef[3] = -corr.coef[3];
333 }
334
335 // Need to use double and rint(), since calculation doesn't end
336 // up on clean integer positions (i.e. 0.9999 can happen)
337 data.range_min = rint(data.center_min - ((32767.0 * 16384) / corr.coef[2]));
338 data.range_max = rint((32767.0 * 16384) / corr.coef[3] + data.center_max);
339 }
340 else
341 {
342 data.calibrate = false;
343 data.invert = false;
344 data.center_min = 0;
345 data.center_max = 0;
346 data.range_min = 0;
347 data.range_max = 0;
348 }
349
350 return data;
351 }
352
353 std::vector<Joystick::CalibrationData>
354 Joystick::get_calibration()
355 {
356 std::vector<struct js_corr> corr(get_axis_count());
357
358 if (ioctl(fd, JSIOCGCORR, &*corr.begin()) < 0)
359 {
360 std::ostringstream str;
361 str << filename << ": " << strerror(errno);
362 throw std::runtime_error(str.str());
363 }
364 else
365 {
366 std::vector<CalibrationData> data;
367 std::transform(corr.begin(), corr.end(), std::back_inserter(data), corr2cal);
368 return data;
369 }
370 }
371
372 struct js_corr cal2corr(const Joystick::CalibrationData& data)
373 {
374 struct js_corr corr;
375
376 if (data.calibrate &&
377 (data.center_min - data.range_min) != 0 &&
378 (data.range_max - data.center_max) != 0)
379 {
380 corr.type = 1;
381 corr.prec = 0;
382 corr.coef[0] = data.center_min;
383 corr.coef[1] = data.center_max;
384
385 corr.coef[2] = (32767 * 16384) / (data.center_min - data.range_min);
386 corr.coef[3] = (32767 * 16384) / (data.range_max - data.center_max);
387
388 if (data.invert)
389 {
390 corr.coef[2] = -corr.coef[2];
391 corr.coef[3] = -corr.coef[3];
392 }
393 }
394 else
395 {
396 corr.type = 0;
397 corr.prec = 0;
398 memset(corr.coef, 0, sizeof(corr.coef));
399 }
400
401 return corr;
402 }
403
404 void
405 Joystick::set_calibration(const std::vector<CalibrationData>& data)
406 {
407 std::vector<struct js_corr> corr;
408
409 std::transform(data.begin(), data.end(), std::back_inserter(corr), cal2corr);
410
411 if (ioctl(fd, JSIOCSCORR, &*corr.begin()) < 0)
412 {
413 std::ostringstream str;
414 str << filename << ": " << strerror(errno);
415 throw std::runtime_error(str.str());
416 }
417 }
418
419 void
420 Joystick::clear_calibration()
421 {
422 std::vector<CalibrationData> data;
423
424 for(int i = 0; i < get_axis_count(); ++i)
425 {
426 CalibrationData cal;
427
428 cal.calibrate = false;
429 cal.invert = false;
430 cal.center_min = 0;
431 cal.center_max = 0;
432 cal.range_min = 0;
433 cal.range_max = 0;
434
435 data.push_back(cal);
436 }
437
438 set_calibration(data);
439 }
440
441 void
442 Joystick::reset_calibration()
443 {
444 set_calibration(orig_calibration_data);
445 }
446
447 std::vector<int>
448 Joystick::get_button_mapping()
449 {
450 uint16_t btnmap[KEY_MAX - BTN_MISC + 1];
451 if (ioctl(fd, JSIOCGBTNMAP, btnmap) < 0)
452 {
453 std::ostringstream str;
454 str << filename << ": " << strerror(errno);
455 throw std::runtime_error(str.str());
456 }
457 else
458 {
459 std::vector<int> mapping;
460 std::copy(btnmap, btnmap + button_count, std::back_inserter(mapping));
461 return mapping;
462 }
463 }
464
465 std::vector<int>
466 Joystick::get_axis_mapping()
467 {
468 uint8_t axismap[ABS_MAX + 1];
469 if (ioctl(fd, JSIOCGAXMAP, axismap) < 0)
470 {
471 std::ostringstream str;
472 str << filename << ": " << strerror(errno);
473 throw std::runtime_error(str.str());
474 }
475 else
476 {
477 std::vector<int> mapping;
478 std::copy(axismap, axismap + axis_count, std::back_inserter(mapping));
479 return mapping;
480 }
481 }
482
483 void
484 Joystick::set_button_mapping(const std::vector<int>& mapping)
485 {
486 assert((int)mapping.size() == button_count);
487
488 uint16_t btnmap[KEY_MAX - BTN_MISC + 1];
489 memset(btnmap, 0, sizeof(btnmap));
490 std::copy(mapping.begin(), mapping.end(), btnmap);
491
492 if (0)
493 for(int i = 0; i < button_count; ++i)
494 {
495 std::cout << i << " -> " << btnmap[i] << std::endl;
496 }
497
498 if (ioctl(fd, JSIOCSBTNMAP, btnmap) < 0)
499 {
500 std::ostringstream str;
501 str << filename << ": " << strerror(errno);
502 throw std::runtime_error(str.str());
503 }
504 }
505
506 int
507 Joystick::get_axis_state(int id)
508 {
509 if (id >= 0 && id < (int)axis_state.size())
510 return axis_state[id];
511 else
512 return 0;
513 }
514
515 void
516 Joystick::set_axis_mapping(const std::vector<int>& mapping)
517 {
518 assert((int)mapping.size() == axis_count);
519
520 uint8_t axismap[ABS_MAX + 1];
521
522 std::copy(mapping.begin(), mapping.end(), axismap);
523
524 if (ioctl(fd, JSIOCSAXMAP, axismap) < 0)
525 {
526 std::ostringstream str;
527 str << filename << ": " << strerror(errno);
528 throw std::runtime_error(str.str());
529 }
530 }
531
532 void
533 Joystick::correct_calibration(const std::vector<int>& mapping_old, const std::vector<int>& mapping_new)
534 {
535 int axes[ABS_MAX + 1]; // axes[name] -> old_idx
536 for(std::vector<int>::const_iterator i = mapping_old.begin(); i != mapping_old.end(); ++i)
537 {
538 axes[*i] = i - mapping_old.begin();
539 }
540
541 std::vector<CalibrationData> callib_old = get_calibration();
542 std::vector<CalibrationData> callib_new;
543 for(std::vector<int>::const_iterator i = mapping_new.begin(); i != mapping_new.end(); ++i)
544 {
545 callib_new.push_back(callib_old[axes[*i]]);
546 }
547
548 set_calibration(callib_new);
549 }
550
551 std::string
552 Joystick::get_evdev() const
553 {
554 // See /usr/share/doc/linux-doc-2.6.28/devices.txt.gz
555 for(int i = 0; i < 32; ++i)
556 {
557 std::ostringstream out;
558 out << "/dev/input/event" << i;
559
560 int evdev_fd;
561 if ((evdev_fd = open(out.str().c_str(), O_RDONLY)) < 0)
562 {
563 // ignore
564 }
565 else
566 {
567 char evdev_name[256];
568 if (ioctl(evdev_fd, EVIOCGNAME(sizeof(evdev_name)), evdev_name) < 0)
569 {
570 std::cout << out.str() << ": " << strerror(errno) << std::endl;
571 }
572 else
573 {
574 if (orig_name == evdev_name)
575 {
576 // Found a device that matches, so return it
577 close(evdev_fd);
578 return out.str();
579 }
580 }
581
582 close(evdev_fd);
583 }
584 }
585
586 throw std::runtime_error("couldn't find evdev for " + filename);
587 }
588
589 std::string
590 Joystick::get_js_type_from_config(const JoystickConfig& js_cfg)
591 {
592 return js_cfg.js_type;
593 }
594
595 #ifdef __TEST__
596
597 // g++ -D__TEST__ joystick.cpp evdev_helper.cpp xml_writer.cpp xml_reader.cpp -o joystick-test `pkg-config --cflags --libs gtkmm-2.4 sigc++-2.0`
598
599 int main(int argc, char** argv)
600 {
601 for(int i = 1; i < argc; ++i)
602 {
603 Joystick joystick(argv[i]);
604
605 std::cout << "Filename: '" << joystick.get_filename() << "'\n";
606 std::cout << "Name: '" << joystick.get_name() << "'\n";
607 std::cout << "js_id: " << joystick.get_js_id() << "\n";
608 std::cout << "Vendor_id: " << joystick.get_vendor_id() << "\n";
609 std::cout << "Product_id: " << joystick.get_product_id() << "\n";
610 std::cout << "usb_id: " << joystick.get_usb_id() << "\n";
611 std::cout << "Axis: " << joystick.get_axis_count() << "\n";
612 std::cout << "Button: " << joystick.get_button_count() << "\n";
613 std::cout << "Evdev: '" << joystick.get_evdev() << "'\n";
614 }
615 return 0;
616 }
617 #endif
618
619 /* EOF */