Permalink
Browse files

Add joystick driver

  • Loading branch information...
0 parents commit cf2ca11c374895de9e39161d3ceee706194389ff @creationix committed Feb 1, 2012
Showing with 67 additions and 0 deletions.
  1. +14 −0 joyclient.lua
  2. +53 −0 joystick.lua
14 joyclient.lua
@@ -0,0 +1,14 @@
+local Joystick = require('./joystick')
+
+if not process.argv[1] then
+ print("Please pass in joystick number as first argument")
+ process.exit(1)
+end
+local js = Joystick:new(process.argv[1])
+js:on('button', p);
+js:on('axis', p);
+js:on('error', function (err)
+ debug("Error", err)
+end)
+
+
53 joystick.lua
@@ -0,0 +1,53 @@
+local Bit = require('bit')
+local FS = require('fs')
+local Emitter = require('emitter')
+local Buffer = require('buffer')
+
+-- http://www.mjmwired.net/kernel/Documentation/input/joystick-api.txt
+function parse(buffer)
+ local event = {
+ time = buffer:readUInt32LE(1),
+ number = buffer:readUInt8(8),
+ value = buffer:readUInt16LE(5),
+ }
+ local type = buffer:readUInt8(7)
+ if Bit.band(type, 0x80) > 0 then event.init = true end
+ if Bit.band(type, 0x01) > 0 then event.type = "button" end
+ if Bit.band(type, 0x02) > 0 then event.type = "axis" end
+ return event
+end
+
+-- Expose as a nice Lua API
+local Joystick = Emitter:extend()
+
+function Joystick.prototype:initialize(id)
+ self:wrap("on_open")
+ self:wrap("on_read")
+ self.id = id
+ FS.open("/dev/input/js" .. id, "r", "0644", self.on_open)
+end
+
+function Joystick.prototype:on_open(fd)
+ self.fd = fd
+ self:start_read()
+end
+
+function Joystick.prototype:start_read()
+ FS.read(self.fd, nil, 8, self.on_read)
+end
+
+function Joystick.prototype:on_read(chunk)
+ local event = parse(Buffer:new(chunk))
+ event.id = self.id
+ self:emit(event.type, event)
+ if self.fd then self:start_read() end
+end
+
+function Joystick.prototype:close(callback)
+ local fd = self.fd
+ self.fd = nil
+ FS.close(fd, callback)
+end
+
+return Joystick
+

0 comments on commit cf2ca11

Please sign in to comment.