1. 程式人生 > >Linux下使用遊戲手柄

Linux下使用遊戲手柄

大多數情況下,Linux系統都帶有手柄驅動模組joydev,當我們插上裝置的時候可以通過以下指令檢視是否檢測到該裝置

ls /dev/    或者    ls /dev/input/

如果有出現 js0 的裝置,則證明裝置能正常使用


如果沒有 js0 裝置,可以通過以下指令安裝驅動

sudo modprobe joydev

如果提示沒有找到該模組則是核心中沒有新增該驅動,需手動載入驅動進核心。

正常使用手柄後我們可以使用 joystick 軟體來進行測試,使用以下指令進行安裝

sudo apt-get install joystick

安裝完後,啟動軟體進行測試

jstest /dev/js0    或者    jstest /dev/input/js0

以上是使用軟體進行遊戲手柄的測試,在更多時候我們是需要其輸出相關資訊,下面介紹使用程式將遊戲手柄的資料輸出:

因為Linux中的list.h不能直接用,所以我們把它單獨提出來,建立一個listop.c檔案和listop.h檔案

/*listop.c*/
#include "listop.h"   
  
  
static  void __check_head(struct list_head* head)  
{  
    if ((head->next == 0) && (head->prev == 0)) {  
        INIT_LIST_HEAD(head);  
    }  
}  
  
/* 
 * Insert a new entry between two known consecutive entries. 
 * 
 * This is only for internal list manipulation where we know 
 * the prev/next entries already! 
 */  
static  void __list_add(struct list_head* new,  
                        struct list_head* prev,  
                        struct list_head* next)  
{  
  
    next->prev = new;  
    new->next = next;  
    new->prev = prev;  
    prev->next = new;  
  
}  
  
  
/* 
 * Delete a list entry by making the prev/next entries 
 * point to each other. 
 * 
 * This is only for internal list manipulation where we know 
 * the prev/next entries already! 
 */  
static  void __list_del(struct list_head* prev,  
                        struct list_head* next)  
{  
  
    next->prev = prev;  
    prev->next = next;  
}  
  
  
  
/** 
 * list_add - add a new entry 
 * @new: new entry to be added 
 * @head: list head to add it after 
 * 
 * Insert a new entry after the specified head. 
 * This is good for implementing stacks. 
 */  
void list_add(struct list_head* new, struct list_head* head)  
{  
    __check_head(head);  
    __list_add(new, head, head->next);  
}  
  
/** 
 * list_add_tail - add a new entry 
 * @new: new entry to be added 
 * @head: list head to add it before 
 * 
 * Insert a new entry before the specified head. 
 * This is useful for implementing queues. 
 */  
void list_add_tail(struct list_head* new, struct list_head* head)  
{  
    __check_head(head);  
    __list_add(new, head->prev, head);  
}  
  
  
/** 
 * list_del - deletes entry from list. 
 * @entry: the element to delete from the list. 
 * Note: list_empty on entry does not return true after this, the entry is in an undefined state. 
 */  
void list_del(struct list_head* entry)  
{  
    __list_del(entry->prev, entry->next);  
}  
  
/** 
 * list_del_init - deletes entry from list and reinitialize it. 
 * @entry: the element to delete from the list. 
 */  
void list_del_init(struct list_head* entry)  
{  
    __list_del(entry->prev, entry->next);  
    INIT_LIST_HEAD(entry);  
}  
  
/** 
 * list_move - delete from one list and add as another's head 
 * @list: the entry to move 
 * @head: the head that will precede our entry 
 */  
void list_move(struct list_head* list, struct list_head* head)  
{  
    __check_head(head);  
    __list_del(list->prev, list->next);  
    list_add(list, head);  
}  
  
/** 
 * list_move_tail - delete from one list and add as another's tail 
 * @list: the entry to move 
 * @head: the head that will follow our entry 
 */  
void list_move_tail(struct list_head* list,  
                    struct list_head* head)  
{  
    __check_head(head);  
    __list_del(list->prev, list->next);  
    list_add_tail(list, head);  
}  
  
  
/** 
 * list_splice - join two lists 
 * @list: the new list to add. 
 * @head: the place to add it in the first list. 
 */  
void list_splice(struct list_head* list, struct list_head* head)  
{  
    struct list_head* first = list;  
    struct list_head* last  = list->prev;  
    struct list_head* at    = head->next;  
  
    first->prev = head;  
    head->next  = first;  
  
    last->next = at;  
    at->prev   = last;  
}  
  
struct list_head* list_dequeue( struct list_head* list ) {  
    struct list_head* next, *prev, *result = ((void*)0);  
  
    prev = list;  
    next = prev->next;  
  
    if ( next != prev ) {  
        result = next;  
        next = next->next;  
        next->prev = prev;  
        prev->next = next;  
        result->prev = result->next = result;  
    }  
  
    return result;  
}  
/*listop.h*/
#ifndef LISTOP_H   
#define LISTOP_H   
 

#ifdef __cplusplus
extern "C"
#endif

 
struct list_head {  
    struct list_head *next, *prev;  
};  
  
typedef struct list_head list_t;  
  
#define LIST_HEAD_INIT(name) { &(name), &(name) }   
  
#define LIST_HEAD(name)		struct list_head name = LIST_HEAD_INIT(name)  
  
#define INIT_LIST_HEAD(ptr) do {  (ptr)->next = (ptr); (ptr)->prev = (ptr); } while (0)  
  
/** 
 * list_add - add a new entry 
 * @new: new entry to be added 
 * @head: list head to add it after 
 * 
 * Insert a new entry after the specified head. 
 * This is good for implementing stacks. 
 */  
void list_add(struct list_head *new, struct list_head *head);  
  
/** 
 * list_add_tail - add a new entry 
 * @new: new entry to be added 
 * @head: list head to add it before 
 * 
 * Insert a new entry before the specified head. 
 * This is useful for implementing queues. 
 */  
void list_add_tail(struct list_head *new, struct list_head *head);  
  
  
/** 
 * list_del - deletes entry from list. 
 * @entry: the element to delete from the list. 
 * Note: list_empty on entry does not return true after this, the entry is in an undefined state. 
 */  
void list_del(struct list_head *entry);  
  
/** 
 * list_del_init - deletes entry from list and reinitialize it. 
 * @entry: the element to delete from the list. 
 */  
void list_del_init(struct list_head *entry);  
  
  
/** 
 * list_move - delete from one list and add as another's head 
 * @list: the entry to move 
 * @head: the head that will precede our entry 
 */  
void list_move(struct list_head *list, struct list_head *head);  
  
  
/** 
 * list_move_tail - delete from one list and add as another's tail 
 * @list: the entry to move 
 * @head: the head that will follow our entry 
 */  
void list_move_tail(struct list_head *list,  
                  struct list_head *head);  
  
/** 
 * list_splice - join two lists 
 * @list: the new list to add. 
 * @head: the place to add it in the first list. 
 */  
void list_splice(struct list_head *list, struct list_head *head);  
  
/** 
 * list_empty - tests whether a list is empty 
 * @head: the list to test. 
 */  
static int list_empty(struct list_head *head)  
{  
    return head->next == head;  
}  
  
/** 
 * list_dequeue - dequeue the head of the list if there are more than one entry 
 * @list: the list to dequeue 
 */  
struct list_head * list_dequeue( struct list_head *list );  
  
/** 
 * list_entry - get the struct for this entry 
 * @ptr:    the &struct list_head pointer. 
 * @type:   the type of the struct this is embedded in. 
 * @member: the name of the list_struct within the struct. 
 */  
#define list_entry(ptr, type, member)	((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))  
  
/** 
 * list_for_each    -   iterate over a list 
 * @pos:    the &struct list_head to use as a loop counter. 
 * @head:   the head for your list. 
 */  
#define list_for_each(pos, head)	for (pos = (head)->next; pos != (head); pos = pos->next)  
              
/** 
 * list_for_each_safe   -   iterate over a list safe against removal of list entry 
 * @pos:    the &struct list_head to use as a loop counter. 
 * @n:      another &struct list_head to use as temporary storage 
 * @head:   the head for your list. 
 */  
#define list_for_each_safe(pos, n, head)	for (pos = (head)->next, n = pos->next; pos != (head);  pos = n, n = pos->next)  
  
/** 
 * list_for_each_prev   -   iterate over a list in reverse order 
 * @pos:    the &struct list_head to use as a loop counter. 
 * @head:   the head for your list. 
 */  
#define list_for_each_prev(pos, head)	for (pos = (head)->prev; pos != (head); pos = pos->prev)  
              
/** 
 * list_for_each_entry  -   iterate over list of given type 
 * @pos:    the type * to use as a loop counter. 
 * @head:   the head for your list. 
 * @member: the name of the list_struct within the struct. 
 */  
#define list_for_each_entry(pos, head, member)              for (pos = list_entry((head)->next, typeof(*pos), member);   &pos->member != (head);    pos = list_entry(pos->member.next, typeof(*pos), member))  
  
#endif  

以下是執行程式

/*joystick.c*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <linux/joystick.h>
#include "listop.h"
#include "Recv.h"



#if 1
#define LOG_DBG(fmt, ...)  fprintf(stdout, fmt, ##__VA_ARGS__)
#else
#define LOG_DBG(fmt, ...)
#endif

#define LOG_ERR(fmt, ...)  fprintf(stderr, fmt, ##__VA_ARGS__)


typedef struct _joy_stick_ctx {
    struct list_head list;
    int i4_js_fd;
    unsigned int i4_op_block;
} JOYSTICK_CTX_T;

LIST_HEAD(_t_js_ctx_head);
/*==>  struct list_head _t_js_ctx_head = {&_t_js_ctx_head, &_t_js_ctx_head};*/

int joystick_open(char* cp_js_dev_name, int i4_block)
{
    int i4_open_flags = O_RDONLY;
    JOYSTICK_CTX_T*  pt_joystick_ctx = NULL;

    if (!cp_js_dev_name) {
        LOG_ERR("[%s] js device name is NULL\n", __func__);
        return -1;
    }

    pt_joystick_ctx = (JOYSTICK_CTX_T*)calloc(sizeof(JOYSTICK_CTX_T), 1);
    if (!pt_joystick_ctx) {
        LOG_ERR("[%s] no memory!!\n", __func__);
        return -1;
    }

    pt_joystick_ctx->i4_op_block = i4_block ? 1 : 0;

    if (pt_joystick_ctx->i4_op_block == 0) {
        i4_open_flags |= O_NONBLOCK;
    }

    pt_joystick_ctx->i4_js_fd = open(cp_js_dev_name, i4_open_flags);
    if (pt_joystick_ctx->i4_js_fd < 0) {
        LOG_ERR("[%s] open device %s error\n", __func__, cp_js_dev_name);
        free(pt_joystick_ctx);
        return -1;
    }

    list_add_tail(&pt_joystick_ctx->list, &_t_js_ctx_head);

    return pt_joystick_ctx->i4_js_fd;
}

int joystick_close(int i4_fd)
{
    struct list_head* pt_entry;
    struct list_head* pt_next;
    JOYSTICK_CTX_T* pt_node;

    if (list_empty(&_t_js_ctx_head)) {
        LOG_ERR("[%s] device not opened\n", __func__);
        return -1;
    }

    list_for_each_safe(pt_entry, pt_next, &_t_js_ctx_head) {
        pt_node = list_entry(pt_entry, JOYSTICK_CTX_T, list);
        if (pt_node->i4_js_fd == i4_fd) {
            list_del_init(&pt_node->list);
            free(pt_node);
            return close(i4_fd);
        }
    }

    LOG_ERR("[%s] i4_fd=%d invalid\n", __func__, i4_fd);
    return -1;
}

int joystick_read_one_event(int i4_fd, struct js_event* tp_jse)
{
    int i4_rd_bytes;

    /*do not check i4_fd again*/

    i4_rd_bytes = read(i4_fd, tp_jse, sizeof(struct js_event));

    if (i4_rd_bytes == -1) {
        if (errno == EAGAIN) { /*when no block, it is not error*/
            return 0;
        }
        else {
            return -1;
        }
    }

    return i4_rd_bytes;
}

int joystick_read_ready(int i4_fd)
{
    int i4_block = 2;
    struct list_head* pt_entry;
    JOYSTICK_CTX_T* pt_node;

    if (list_empty(&_t_js_ctx_head)) {
        LOG_ERR("[%s] device not opened\n", __func__);
        return -1;
    }

    list_for_each(pt_entry, &_t_js_ctx_head) {
        pt_node = list_entry(pt_entry, JOYSTICK_CTX_T, list);
        if (pt_node->i4_js_fd == i4_fd) {
            i4_block = pt_node->i4_op_block;
            break;
        }
    }

    if (i4_block == 2) {
        LOG_ERR("[%s] i4_fd=%d invalid\n", __func__, i4_fd);
        return 0;
    }
    else if (i4_block == 1) {
        fd_set readfd;
        int i4_ret = 0;
        struct timeval timeout = {0, 0};
        FD_ZERO(&readfd);
        FD_SET(i4_fd, &readfd);

        i4_ret = select(i4_fd + 1, &readfd, NULL, NULL, &timeout);

        if (i4_ret > 0 && FD_ISSET(i4_fd, &readfd)) {
            return 1;
        }
        else {
            return 0;
        }

    }

    return 1; /*noblock read, aways ready*/
}


void debug_list(void)
{
        char s_char[128];
        int i = 0;


    if (! list_empty(&_t_js_ctx_head)) {
        struct list_head* pt_entry;
        JOYSTICK_CTX_T* pt_node;

        list_for_each(pt_entry, &_t_js_ctx_head) {
            pt_node = list_entry(pt_entry, JOYSTICK_CTX_T, list);
            LOG_DBG("fd:%d--block:%d\n", pt_node->i4_js_fd, pt_node->i4_op_block);
        }
    }
    else {
        LOG_DBG("-----------> EMPTY NOW\n");
    }
}

#if 1
typedef struct _axes_t {
    int x;
    int y;
} AXES_T;




int main()
{
    int fd, rc;
    char number_of_axes = 0;
    char number_of_btns = 0;

    char c_re[15][30];

    char js_name_str[128];
    unsigned int buttons_state = 0;
    AXES_T* tp_axes = NULL;
    int i, print_init_stat = 0;

        char but_sta = 0;
        char start_state = 0;


    struct js_event jse;

    fd = joystick_open("/dev/input/js0", 1);
    if (fd < 0)
    {
        LOG_ERR("open failed.\n");
        exit(1);
    }

    if( SerialInit() == -1 )
    {
        perror("SerialInit Error!\n");
        return NULL;
    }

    rc = ioctl(fd, JSIOCGAXES, &number_of_axes);
    if (rc != -1)
    {
        LOG_DBG("number_of_axes:%d\n", number_of_axes);
        if (number_of_axes > 0)
        tp_axes = (AXES_T*)calloc(sizeof(AXES_T), 1);
    }

    rc = ioctl(fd, JSIOCGBUTTONS, &number_of_btns);
    if (rc != -1)
    {
        LOG_DBG("number_of_btns:%d\n", number_of_btns);
    }

    if (ioctl(fd, JSIOCGNAME(sizeof(js_name_str)), js_name_str) < 0)
    {
        LOG_DBG(js_name_str, "Unknown", sizeof(js_name_str));
    }

    LOG_DBG("joystick Name: %s\n", js_name_str);


    while(1)
    {
        if (joystick_read_ready(fd))
        {
            rc = joystick_read_one_event(fd, &jse);
            if (rc > 0)
            {
                if ((jse.type & JS_EVENT_INIT) == JS_EVENT_INIT)
                {
                    if ((jse.type & ~JS_EVENT_INIT) == JS_EVENT_BUTTON)
                    {
                        if (jse.value)
                            buttons_state |= (1 << jse.number);
                        else
                            buttons_state &= ~(1 << jse.number);
                    }

                    else if ((jse.type & ~JS_EVENT_INIT) == JS_EVENT_AXIS)
                    {
                        if (tp_axes)
                        {
                            if ((jse.number & 1) == 0)
                                tp_axes[jse.number / 2].x = jse.value;
                            else
                                tp_axes[jse.number / 2].y = jse.value;
                        }
                    }
                }


                else
                {
                    if (print_init_stat == 0) //裝置輸出初始資訊
                    {
                        for (i = 0; i < number_of_btns; i++)
                        {
                            sprintf(c_re[i], "but%d %d;", i, ((buttons_state & (1 << i)) == (1 << i)) ? 0 : 1);
                            LOG_DBG(c_re[i]);	//LOG_DBG("   %d", i);
                            LOG_DBG("joystick init state: button %d is %s.\n", i, ((buttons_state & (1 << i)) == (1 << i)) ? "DOWN" : "UP");
                        }

                        if (tp_axes)
                        for (i = 0; i < number_of_axes; i++) {
                        sprintf(c_re[i+11], "axes%d x=%d y=%d;", i, tp_axes[i].x, tp_axes[i].y);
                        LOG_DBG(c_re[i+11]);		//LOG_DBG("   %d", i+11);
                        LOG_DBG("joystick init state: axes %d is x=%d  y=%d.\n", i, tp_axes[i].x, tp_axes[i].y);
                        }
                                                //ready = 1;
                        print_init_stat = 1;
                    }


                    if (jse.type  == JS_EVENT_BUTTON) //按鍵狀態改變時輸出相關資訊
                    {
                        if (jse.value)
                            buttons_state |= (1 << jse.number);
                        else
                            buttons_state &= ~(1 << jse.number);

                        //LOG_DBG("joystick state: button %d is %s.\n", jse.number, ((buttons_state & (1 << jse.number)) == (1 << jse.number)) ? "DOWN" : "UP");
                        bzero( c_re[jse.number], sizeof(c_re[jse.number]) );
                        but_sta = ((buttons_state & (1 << jse.number)) == (1 << jse.number)) ? 0 : 1;
                        sprintf(c_re[jse.number], "but%d %d;", jse.number, but_sta);
                        LOG_DBG("%s \n", c_re[jse.number]);
                        // jse.number為手柄按鍵序號  but_sta為按鍵當前狀態
                    }

                    else if (jse.type == JS_EVENT_AXIS) //手桿狀態改變時輸出相關資訊
                    {
                        if (tp_axes)
                        {
                            if ((jse.number & 1) == 0)
                                tp_axes[jse.number / 2].x = jse.value;
                            else
                                tp_axes[jse.number / 2].y = jse.value;

                            bzero( c_re[jse.number / 2 +11], sizeof(c_re[jse.number / 2 +11]) );
                            sprintf(c_re[jse.number / 2 +11], "axes%d x=%d y=%d;", jse.number / 2, tp_axes[jse.number / 2].x, tp_axes[jse.number / 2].y);
                            LOG_DBG("%s \n", c_re[jse.number / 2 +11]);
                            //tp_axes[jse.number / 2] jse.number/2為手杆序號  .x .y分別對應手杆當前x軸和y軸的值
                        }

                        else
                        {
                            LOG_DBG("joystick state: axes %d is %s=%d.\n", jse.number / 2, ((jse.number & 1) == 0) ? "x" : "y", jse.value);
                        }
                    }
                }
            }
        }
    }

    joystick_close(fd);

    if (tp_axes) {
        free(tp_axes);
    }

    return 0;
}
#endif