Languages

Snippet to read Input.Event struct's from /dev/input/event* using IOChannel's

Your rating: None Average: 4 (2 votes)
/*
 * To compile: valac --pkg=linux --pkg=posix inputeventreader.vala
 *
 * Description:
 *   This example uses of the GLib's main loop and IOChannel's
 *   to listen for Input.Event's on one or more /dev/input/event*
 *   devices, and outputs the values to standard output.
 *
 * Copyright 2010, Robert Thomson.
 *
 * Released under the MIT License
 */
using Linux;
using Posix;
 
class InputEventReader {
 
    // Read a single input event from the channel, and print out the values.
    private static bool gio_in(IOChannel gio, IOCondition condition) {
        if((condition & IOCondition.HUP) == IOCondition.HUP) {
            print("Read end of channel closed.\n");
            return false;
        }
        else if((condition & IOCondition.IN) == IOCondition.IN) {
            Input.Event ev = Input.Event();
            size_t bytes_read = Posix.read(gio.unix_get_fd(), (void *)(&ev), sizeof(Input.Event));
            if(bytes_read >= sizeof(Input.Event)) {
                print("%d,%d,%d\n", ev.type, ev.code, ev.value);
            }
        }
        return true;
    }
 
    // Given one or more /dev/input/event* devices on the command line,
    // add a listener for each one.
    public static int main(string[] args) {
        if(args.length <= 1) {
            print("Syntax: %s /dev/input/eventX [/dev/input/eventY] [...]\n", args[0]);
            return 1;
        }
        int count = 0;
        foreach(string arg in args[1:args.length]) {
            try {
                var iochannel = new IOChannel.file(arg, "r");
                if(!(iochannel.add_watch(IOCondition.IN | IOCondition.HUP, gio_in) != 0)) {
                    print("Cannot add watch on IOChannel: %s!\n", arg);
                    continue;
                }
                print("Reading events on %s\n", arg);
                count += 1;
            } catch(GLib.FileError e) {
                print("Cannot open input device: %s\n", arg);
                continue;
            }
        }
        if(count == 0) {
            print("No valid input devices. Aborting.\n");
            return 1;
        }
        var loop = new MainLoop(null, false);
        loop.run();
        return 0;
    }
}