00001 #include <GameController.H>
00002
00003 #include <sys/select.h>
00004 #include <sys/ioctl.h>
00005 #include <sys/types.h>
00006 #include <sys/stat.h>
00007 #include <fcntl.h>
00008 #include <linux/joystick.h>
00009 #include <Logger.H>
00010
00011 using namespace WURDE;
00012 using namespace std;
00013
00014
00015 GameController::GameController(const string &device) :m_axis_data(NULL), m_button_data(0) {
00016
00017 if ((m_fd = open(device.c_str(), O_RDONLY)) < 0) {
00018 g_logdebug << "Could not open joystick device: " << device << endl;
00019 return;
00020 }
00021
00022
00023 char buffer[256];
00024 ioctl(m_fd, JSIOCGNAME(256), buffer);
00025 m_name = buffer;
00026
00027
00028 unsigned char n;
00029 ioctl(m_fd, JSIOCGAXES, &n);
00030 m_axes = n;
00031 m_axis_data = new int[m_axes];
00032
00033
00034 ioctl(m_fd, JSIOCGBUTTONS, &n);
00035 m_buttons = n;
00036 m_button_data.resize(n);
00037
00038
00039 ioctl(m_fd, JSIOCGVERSION, &m_driver_version);
00040 assert((m_driver_version >> 16) >= 2);
00041
00042 g_logdebug << "Joystick found: " << m_name << " " << m_axes << " axes, " << m_buttons << " buttons" << endl;
00043 g_logdebug << "driver version: " << (m_driver_version >> 16) << "." << ((m_driver_version > 8) & 0xff) << "." << (m_driver_version & 0xff) << endl;
00044
00045
00046 pthread_create(&m_read_thread, NULL, GameController::readThread, this);
00047 }
00048
00049
00050 GameController::~GameController() {
00051 close(m_fd);
00052
00053 if (m_axis_data != NULL)
00054 delete [] m_axis_data;
00055 }
00056
00057 void GameController::setAxisMap(int num,string name){
00058 if(num>0&&num<m_axes){
00059 axisMap[name]=num;
00060 }
00061 }
00062
00063 void GameController::setButtonMap(int num,string name){
00064 if(num>0&&num<m_buttons){
00065 buttonMap[name]=num;
00066 }
00067 }
00068
00069
00070
00071 void *GameController::readThread(void *ptr) {
00072
00073 GameController *joystick = static_cast<GameController *>(ptr);
00074
00075 struct js_event data;
00076
00077 while (true) {
00078
00079 fd_set read_set;
00080 FD_ZERO(&read_set);
00081 FD_SET(joystick->m_fd, &read_set);
00082
00083
00084 if (select(joystick->m_fd + 1, &read_set, NULL, NULL, NULL) < 0) {
00085 g_logdebug << " Error in select: " << joystick->name() << endl;
00086 } else if (FD_ISSET(joystick->m_fd, &read_set)) {
00087 if (read(joystick->m_fd, &data, sizeof(struct js_event)) != sizeof(struct js_event)) {
00088 g_logdebug << "Error reading from device: " << joystick->name() << endl;
00089 } else {
00090 if (data.type & JS_EVENT_BUTTON) {
00091 assert(data.number < joystick->m_buttons);
00092
00093 joystick->m_button_data[data.number] = (data.value == 1);
00094 } else if (data.type & JS_EVENT_AXIS) {
00095 assert(data.number < joystick->m_axes);
00096
00097 joystick->m_axis_data[data.number] = data.value;
00098 } else {
00099 g_logdebug << "Unknown event type " << data.type << " from joystick " << joystick->name() << endl;
00100 }
00101 }
00102 }
00103 }
00104 }
00105