2 #include <linux/joystick.h>
3 #include <msp/core/systemerror.h>
4 #include <msp/fs/dir.h>
5 #include <msp/io/handle_private.h>
6 #include <msp/strings/format.h>
7 #include "gamecontroller.h"
8 #include "gamecontroller_platform.h"
15 vector<string> GameController::Private::detected_controllers;
17 GameController::GameController(unsigned index):
22 if(index>=Private::detected_controllers.size())
23 throw device_not_available(format("GameController(%d)", index));
25 JsDevice *device = new JsDevice(Private::detected_controllers[index]);
29 priv->dev->signal_data_available.connect(sigc::mem_fun(this, static_cast<void (GameController::*)()>(&GameController::tick)));
30 name = priv->dev->get_name();
34 GameController::~GameController()
40 unsigned GameController::detect()
42 Private::detected_controllers.clear();
44 FS::Path dev_input = "/dev/input";
45 list<string> devices = FS::list_filtered(dev_input, "^js[0-9]+");
47 for(list<string>::const_iterator i=devices.begin(); i!=devices.end(); ++i)
48 // TODO check permissions
49 Private::detected_controllers.push_back((dev_input / *i).str());
52 n_detected_controllers = Private::detected_controllers.size();
54 return Private::detected_controllers.size();
57 void GameController::use_event_dispatcher(IO::EventDispatcher *ed)
60 event_disp->remove(*priv->dev);
63 event_disp->add(*priv->dev);
66 void GameController::tick()
72 if(!first && !IO::poll(*priv->dev, IO::P_INPUT, Time::zero))
76 unsigned len = priv->dev->read(reinterpret_cast<char *>(events), sizeof(events));
78 unsigned count = len/sizeof(js_event);
79 for(unsigned i=0; i<count; ++i)
81 unsigned type = events[i].type&0x7F;
82 bool init = events[i].type&JS_EVENT_INIT;
83 if(type==JS_EVENT_AXIS)
84 set_axis_value(events[i].number, events[i].value/32768.0f, !init);
85 else if(type==JS_EVENT_BUTTON)
86 set_button_state(events[i].number, events[i].value, !init);
89 if(len<sizeof(events))
95 void GameController::tick(const Time::TimeDelta &timeout)
97 if(IO::poll(*priv->dev, IO::P_INPUT, timeout))
102 JsDevice::JsDevice(const string &fn)
105 *handle = open(fn.c_str(), O_RDONLY);
107 throw system_error(format("open(%s)", fn));
108 set_events(IO::P_INPUT);
111 JsDevice::~JsDevice()
116 string JsDevice::get_name() const
118 char buf[128] = { 0 };
119 int ret = ioctl(*handle, JSIOCGNAME(sizeof(buf)), buf);
121 throw system_error("ioctl(JSIOCGNAME)");
125 unsigned JsDevice::do_read(char *buf, unsigned size)
127 return IO::sys_read(handle, buf, size);
130 unsigned JsDevice::do_write(const char *, unsigned)
132 throw IO::invalid_access(IO::M_WRITE);