How to read without blocking

The following code works:

const O_RDONLY = 0
const O_NONBLOCK = 2048

function open_joystick(filename = "/dev/input/js0")
    if  Sys.islinux()
        if ispath(filename)
            jfd = ccall(:open, Cint, (Cstring, Cint), filename, O_RDONLY|O_NONBLOCK)
            device = JSDevice(filename, jfd, 0, 0)
            device.axis_count = axis_count(device) 
            device.button_count = button_count(device)
            return device
        else
            println("ERROR: The device $filename does not exist!")
            return nothing
        end
    else
        error("Currently Joystick.jl supports only Linux!")
        nothing
    end
end
function read_event(js::JSDevice)
    event = Vector{UInt8}(undef, sizeof(JSEvent))
    res = ccall(:read, Cssize_t, (Cint, Ptr{Cuchar}, Csize_t), js.fd, event, sizeof(JSEvent))
    if res == -1    
        return nothing
    end
    reinterpret(JSEvent, event)[]
end

Complete code: GitHub - ufechner7/Joysticks.jl: Joystick interface for Julia

Thank you very much! :slight_smile:

1 Like