Controller

Attributes:

Functions:

Events:

Plugins:

class Controller()

The Controller class is your main interface to the Leap Motion Controller.

Create an instance of this Controller class to access frames of tracking data and configuration information. Frame data can be polled at any time using the frame() function. Call frame() or frame(0) to get the most recent frame. Set the history parameter to a positive integer to access previous frames. A controller stores up to 60 frames in its frame history.

When creating a Controller object, you may optionally pass in an options object to set various controller properties.

var controller = new Leap.Controller({
  host: '127.0.0.1',
  port: 6437,
  frameEventName: 'animationFrame',
  useAllPlugins: true
});

The Leap Motion Controller class extends the Node.js EventEmitter <http://nodejs.org/api/events.html> class.

Arguments:
  • options (Object) –

    An object containing the option values for this Controller:

    • host — The host name or IP address of the WebSocket server providing Leap Motion tracking data. Usually, this is the local host address: 127.0.0.1.
    • port — The port on which the WebSocket server is listening. By default, this is port 6437.
    • enableGestures — Set to true to enable gesture recognition. Omit or set to false if your application does not use gestures.
    • background — Set to true to enable this application to receive frames when not the foreground application.
    • optimizeHMD — Set to true to when mounting the Leap Motion hardware to a head-mounted display.
    • frameEventName — The type of update loop to use for processing frame data.
      • animationFrame uses the browser animation loop (generally 60 fps).
      • deviceFrame runs at the Leap Motion controller frame rate (20 to 200 fps depending on the user’s settings and available computing power).
    • useAllPlugins - False by default.
      Tells the controller to use all plugins included on the page. For more information, see https://github.com/leapmotion/leapjs/wiki/plugins.
    • loopWhileDisconnected — Defaults to true, which means the animation frame loop runs at all times. If you set this to false, the animation loop does only runs when the Controller() object is connected to the Leap Motion service and only when a new frame of data is available. Setting loopWhileDisconnected to false can minimize your app’s use of computing resources, but may irregularly slow down or stop any animations driven by the frame loop. Added in LeapJS version 0.4.3.
Controller.frameEventName
Type:string – either "animationFrame" or "deviceFrame"

Reports the type of update loop requested when this Controller was created. Changing this value for an existing Controller object has undefined behavior. Set the type of frame loop to use in the Controller object constructor function.

var loopType = controller.frameEventName;
Controller.connect()

Connects this Controller object to the Leap Motion WebSocket server. If the connection succeeds, the controller can begin supplying tracking data. Use the frame() or on() functions to access tracking data.

You can register callbacks with the on() function to receive notification when the connection succeeds.

<div id="frameID"></div>

var controller = new Leap.Controller();
var frameDisplay = document.getElementById('frameID');

this.controller.on('connect', function(){
   setInterval(function(){
      var frame = controller.frame();
      frameDisplay.innerHTML = '<p>Frame: ' + frame.id + ' is ' + (frame.valid ? 'valid.</p>' : 'invalid.</p>');
   }, 500);
});

controller.connect();
Returns:Controller()

Leap Motion 1.0 and LeapJS 0.3.0

Controller.connected()

Reports whether this Controller is currently connected to the Leap Motion service.

Returns:true or false

Leap Motion 1.2 and LeapJS 0.5.0

Controller.disconnect()

Disconnects from the WebSocket server. Call connect() to reconnect this controller object.

controller.disconnect();
Returns:Controller()
Controller.frame([history])

Returns a frame of tracking data from the Leap.

Use the optional history parameter to specify which frame to retrieve. Call frame() or frame(0) to access the most recent frame; call frame(1) to access the previous frame, and so on. If you use a history value greater than the number of stored frames, then the controller returns an invalid frame. When using the animationFrame loop, only one Frame object is stored per loop iteration. Any device frames occuring between iterations are discarded.

var controller = Leap.loop({enableGestures:true}, function(frame){
    var currentFrame = frame;
    var previousFrame = controller.frame(1);
    var tenFramesBack = controller.frame(10);
});
Arguments:
  • history (int) – The age of the frame to return, counting backwards from the most recent frame (0) into the past and up to the maximum age. The number of frames stored in the history buffer is an implementation detail that may change in the future. Do not rely on the current value (200).
Returns:

Frame() – The specified frame; or, if no history parameter is specified, the newest frame. If a frame is not available at the specified history position, an invalid Frame is returned.

Leap Motion 1.0 and LeapJS 0.3.0

Controller.inBrowser()

Reports whether the the code is executing an a browser context.

controller.inBrowser();
Returns:True, if running in a browser; false, if running in the Node platform.

Leap Motion 1.0.8 and LeapJS 0.3.0

Controller.on(eventName, callback)

Adds a callback function for one of the events dispatched by this Controller object. Defined in the Node.js EventEmitter. See emitter.on <http://nodejs.org/api/events.html#events_emitter_on_event_listener> for additional information. You can use the other EventEmitter classes, as well, but they are not described here.

Arguments:
  • eventName (string) –

    One of the following:

  • callback (function) –

    A function to be called whenever the named event occurs. Callbacks for the protocol, frame, and gesture events take arguments, the others do not.

    var controller = new Leap.Controller();
    controller.connect();
    
    controller.on('frame', onFrame);
    function onFrame(frame)
    {
        console.log("Frame event for frame " + frame.id);
    }
    
Returns:

Controller()

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.setBackground(state)

Informs the Leap Motion WebSocket server that your application always wants to receive frames of tracking data when it is in the background and not being actively used. Note that setting this option to true could lead to unintended input to your application while the user interacts with other applications. Most applications should not receive frames in the background.

Note that your application does not receive frames if another Leap-enabled application is in the foreground, even when the background frames policy is in effect. The policy only matters when a non-Leap-enabled app has the operating system input focus.

controller.setBackground(true); //enable
controller.setBackground(false); //disable
Arguments:
  • state (boolean) – True to receive frames at all times; otherwise, false (the default).
Returns:

Controller()

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.setOptimizeHMD(state)

Informs the Leap Motion WebSocket server that your application expects the controller to be attached to a head-mounted display.

In the optimize for HMD mode, the Leap Motion software expects to view hands from the top rather than the bottom. When ambiguity exists whether the palm of a hand is facing toward or away from the Leap Motion sensors, setting this mode makes it more likely that the software will initialize the hand model so that it is facing away from the sensors.

Arguments:
  • state (boolean) – True to enable the optimize for HMD mode; otherwise, false (the default).
Returns:

Controller()

Leap Motion 2.1.5 and LeapJS 0.6.2

Controller.streaming()

Reports whether this Controller is currently recieving tracking data from the Leap Motion service.

Returns:true or false

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.blur

Dispatched when the browser page loses focus. Typically, this occurs when the user changes tabs in a single browser window, but not, for example, when the user switches to a different browser window or another application.

var controller = new Leap.Controller();
controller.connect();

controller.on('blur', onBlur);
function onBlur()
{
    console.log("Blur event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.connect

Dispatched when this controller establishes a connection to the Leap Motion WebSocket server. This event does not mean that tracking data is available as Leap Motion tracking may be paused by the user, or the device itself unplugged.

var controller = new Leap.Controller();
controller.connect();


controller.on('connect', onConnect);
function onConnect()
{
    console.log("Connect event");
}
Returns:Controller()

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.deviceAttached

Dispatched when the Leap Motion device is plugged in or turned on.

All device events include a device info object with the following information:

name type values
attached boolean true or false
streaming boolean true or false
id string the device hardware ID
type string

One of:

  • peripheral
  • keyboard
  • laptop
  • unknown
  • unrecognized
var controller = new Leap.Controller();
controller.connect();

controller.on('deviceAttached', onAttached);
function onAttached()
{
    console.log("Device attached event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.deviceConnected

Dispatched when the Leap Motion device is plugged in and when tracking is unpaused by the user.

Note that this event is not dispatched if the controller is already plugged in when your application starts.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceConnected', onDeviceConnected);
function onDeviceConnected(evt)
{
    console.log("Device Connect event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.deviceDisconnected

Dispatched when the Leap Motion device is unplugged and when tracking is paused by the user.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceDisconnected', onDeviceDisconnect);
function onDeviceDisconnect()
{
    console.log("Device disconnect event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.deviceRemoved

Dispatched when the Leap Motion device is unplugged or turned off.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceRemoved', onRemoved);
function onRemoved()
{
    console.log("Device removed event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.deviceStopped

Dispatched when the Leap Motion device stops providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceStopped', onStopped);
function onStopped()
{
    console.log("Device stopped streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.deviceStreaming

Dispatched when the Leap Motion device starts providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceStreaming', onStreaming);
function onStreaming()
{
    console.log("Device started streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.disconnect

Dispatched when this Controller object disconnects from the Leap Motion WebSocket server.

var controller = new Leap.Controller();
controller.connect();

controller.on('disconnect', onDisconnect);
function onDisconnect()
{
    console.log("Disconnect event");
}
Returns:Controller()

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.focus

Dispatched when the browser tab gains focus.

var controller = new Leap.Controller();
controller.connect();

controller.on('focus', onFocus);
function onFocus()
{
    console.log("Focus event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.frame

Dispatched once per update cycle.

If the frameEventName is animationFrame, then the browser animation loop is in use and this event is dispatched typically 60 times per second. Since the animation loop timing does not match that of the Leap Motion device, you may get the same Leap.Frame object more than once or skip frames.

If the frameEventName is deviceFrame, then this event is dispatched as each frame of Leap Motion data is received. The device frame rate can vary quite a bit depending on the user’s settings and the available computing power.

Set the type of frame loop to use in the Controller object constructor function.

The current Frame object is passed to your callback function.

var controller = new Leap.Controller();
controller.connect();

controller.on('frame', onFrame);
function onFrame(frame)
{
    console.log("Frame event for frame " + frame.id);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.gesture

Notice Gestures are deprecated in version 3.0 and may not behave the same as they did in earlier versions.

Dispatched for each gesture update in a frame.

The associated Gesture and the current Frame objects are passed to your callback function.

When the Controller is using the animationFrame loop, which is the default``, any gestures generated in device frames produced between iterations of the animationFrame loop are collected and dispatched at the next iteration. This means that the Frame object passed to your gesture listener function will not always be the frame in which the gesture was recorded. The position and other physical attributes of the hands and fingers making the gesture may have changed slightly between frames. In some cases, a Hand or Pointable object with the same IDs as those referenced by the Gesture object may not be present at all in the current frame.

var controller = new Leap.Controller({enableGestures:true});
controller.connect();

controller.on('gesture', onGesture);
function onGesture(gesture,frame)
{
    console.log(gesture.type + " with ID " + gesture.id + " in frame " + frame.id);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.frameEnd

Dispatched when the frame of data has been fully constructed.

Use this callback for code that should run after the frame is available.

LeapJS 0.6.4

Controller.Event.protocol

Dispatched when the WebSocket server and client have negotiated a protocol.

A Protocol object is passed to your callback function. Use the version or versionLong attributes of this object to determine which protocol is in use, which may be lower than the requested protocol if the user is running an older version of the Leap Motion software.

var controller = new Leap.Controller();
controller.connect();

controller.on('protocol', onProtocol);
function onProtocol(protocol)
{
    console.log("Protocol event: " + protocol.version);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

Controller.Event.streamingStarted

Dispatched when the Leap Motion service/daemon starts providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('streamingStarted', onServiceStreaming);
function onServiceStreaming()
{
    console.log("Service started streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.Event.streamingStopped

Dispatched when the Leap Motion service/daemon stops providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('streamingStopped', onServiceStopped);
function onServiceStopped()
{
    console.log("Service stopped streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

Controller.plugin(pluginName, factory)

Registers a plugin, making is accessible to controller.use() later on.

Valid keys for the object returned by the factory include frame, hand, finger, and pointable. The value of each key can be either a function or an object. If given a function, that function will be called once for every instance of the object, with that instance injected as an argument. This allows decoration of objects with additional data:

Leap.Controller.plugin('testPlugin', function(options){
 return {
   frame: function(frame){
     frame.foo = 'bar';
   }
 }
});

When hand is used, the callback is called for every hand object in frame.hands. Note that hand objects are recreated with every new frame; any data saved on a hand does not persist across frames.

Leap.Controller.plugin('testPlugin', function(){
 return {
   hand: function(hand){
     console.log('testPlugin running on hand ' + hand.id);
   }
 }
});

A factory can return an object to add custom functionality to Frames, Hands, or Pointables. The methods defined by this returned object are added directly to the prototype of the specified class. The Finger and Tool classes cannot be used here, Pointable must be used instead. Use this technique for calculations that may not be necessary on every frame. Memoization is also encouraged, for cases where the method may be called many times per frame by the application.

// This plug-in allows hand.usefulData() to be called later.
Leap.Controller.plugin('testPlugin', function(){
 return {
   hand: {
     usefulData: function(){
       console.log('usefulData on hand', this.id);
       // memoize the results onto the hand, preventing repeat work:
       this.x || (this.x = someExpensiveCalculation());
       return this.x;
     }
   }
 }
});

Note that the factory pattern gives encapsulation for every plugin instance.

Leap.Controller.plugin('testPlugin', function(options){
 options || (options = {});
 options.center || (options.center = [0,0,0]);

 privatePrintingMethod = function(){
   console.log('privatePrintingMethod - options', options);
 }

 return {
   pointable: {
     publicPrintingMethod: function(){
       privatePrintingMethod();
     }
   }
 }
});
Arguments:
  • pluginName (string) – The name string identifying a plugin.
  • factory (function) – A factory method which will return an instance of a plugin. The factory itself receives an optional hash of options, passed in via controller.use().

Leap Motion 1.0 and LeapJS 0.4.0

Controller.use(pluginNameOrFactory[, options])

Begin using a registered plugin. The plugin’s functionality will be added to all frames returned by the Controller object and any other specified objects within the frame.

  • The order of plugin execution inside the loop matches the order in which use is called by the application.
  • The plugin is run for animationFrames only.
<script src="http://js.leapmotion.com/leap-plugins-0.1.4.js"></script>
<script>
var controller = new Leap.Controller();
controller.use('handEntry');
controller.connect();
</script>
Arguments:
  • pluginNameOrFactory (string) – The registered name string of the plugin. A plugin factory is also accepted directly, for use in node environments.
  • options (hash) – Options to be passed to the plugin’s factory.
Returns:

Controller()

Leap Motion 1.0 and LeapJS 0.4.0

Controller.stopUsing(pluginName)

Stop using a used plugin. Removes any of the plugin’s pipeline methods (those called on every frame) and removes any methods added to extend class prototypes.

controller.stopUsing('handEntry');
Arguments:
  • pluginName (string) – The registered name string of the plugin.
Returns:

Controller()

Leap Motion 1.0 and LeapJS 0.4.0