Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Created September 20, 2016 04:58
Show Gist options
  • Save Tosainu/a0c10561a42b960619e0bfa10a57d484 to your computer and use it in GitHub Desktop.
Save Tosainu/a0c10561a42b960619e0bfa10a57d484 to your computer and use it in GitHub Desktop.
#include <iomanip>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
extern "C" {
#include <fcntl.h>
#include <linux/joystick.h>
#include <sys/ioctl.h>
#include <unistd.h>
}
class joystick {
public:
joystick(boost::asio::io_service& io_service, int fd) : joystick_(io_service, fd) {
boost::asio::async_read(
joystick_, buffer_, boost::asio::transfer_exactly(sizeof(js_event)),
boost::bind(&joystick::handle_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
~joystick() {
joystick_.close();
}
private:
void handle_read(const boost::system::error_code& error, std::size_t bytes_transferred) {
if (error) {
std::cerr << "error: " << error.message() << std::endl;
return;
}
if (bytes_transferred == sizeof(js_event)) {
auto jse = boost::asio::buffer_cast<const js_event*>(buffer_.data());
switch (jse->type & ~JS_EVENT_INIT) {
case JS_EVENT_BUTTON:
std::cout << "button: ";
break;
case JS_EVENT_AXIS:
std::cout << " axis: ";
break;
}
std::cout << std::setw(2) << static_cast<int>(jse->number) << ", value: " << jse->value
<< std::endl;
}
buffer_.consume(bytes_transferred);
boost::asio::async_read(
joystick_, buffer_, boost::asio::transfer_exactly(sizeof(js_event)),
boost::bind(&joystick::handle_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
boost::asio::posix::stream_descriptor joystick_;
boost::asio::streambuf buffer_;
};
auto main(int argc, char** argv) -> int {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <device>" << std::endl;
return -1;
}
const auto fd = open(argv[1], O_RDONLY);
if (fd < 0) {
std::cerr << "Cannot open " << argv[1] << ": " << strerror(errno) << std::endl;
return -1;
}
{
char name[255];
int axes, buttons;
ioctl(fd, JSIOCGNAME(255), name);
ioctl(fd, JSIOCGAXES, &axes);
ioctl(fd, JSIOCGBUTTONS, &buttons);
std::cout << name << ": " << axes << " axes/" << buttons << " buttons" << std::endl;
}
boost::asio::io_service io_service;
joystick j(io_service, fd);
io_service.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment