Last Updated: February 25, 2016
·
782
· brendanjcaffrey

Using Leap Motion With RubyMotion OSX

After a couple hours trying to get the Leap Motion dylib to compile into a RubyMotion app, I gave up and went the WebSocket route, inspired by both leapmotion-ruby and RubyMotionからWebSocketを使う. Here's how I did it.

First off, I added gem 'motion-cocoapods' to my Gemfile and ran bundle install. Then I added this to my Rakefile:

Motion::Project::App.setup do |app|
 app.name = '...'

 app.pods do
 pod 'SocketRocket'
 pod 'JSONKit'
 end
end

After running rake pod:install you should be good to go on dependencies. Now, in the applicationDidFinishLaunching: method of your AppDelegate, add this to set up the WebSocket:

url = NSURL.URLWithString('ws://127.0.0.1:6437')
@socket = SRWebSocket.alloc.initWithURLRequest(NSURLRequest.requestWithURL(url))
@socket.delegate = self
@socket.open

Now add the following SocketRocket delegate methods to your AppDelegate class and you should be good to go:

def webSocketDidOpen(webSocket)
 data = '{"enableGestures":true}'
 @socket.send(data)
end

def webSocket(webSocket, didReceiveMessage:message)
 error_ptr = Pointer.new(:object)
 parsed = message.description.objectFromJSONStringWithParseOptions(JKParseOptionValidFlags, error:error_ptr)

 if parsed.nil?
 error = error_ptr[0]
 puts error.userInfo[NSLocalizedDescriptionKey]
 else
 p parsed
 end
end

def webSocket(webSocket, didFailWithError:error)
 p "Error : #{error.description}"
end

def webSocket(webSocket, didCloseWithCode:code,reason:reason)
 p "Close"
end

The first method there sends a message to the controller to start tracking gestures. If you don't need them, then you can take out those lines.