GPSd with Ruby

GPSd

GPSd is a Linux daemon that can read and parse data from various GPS recievers, and it provides a standard interface for obtaining said data. GPSd provides JSON data over a socket connection in an easy to consume stream. In this example, I'm going to read the data with cool.io and parse it with Ruby bindings to yajl. Cool.io brings events like Node.js to Ruby with the simplicity of Sinatra. Yajl, on the other hand, is a streaming JSON parser that's fast and reliable.

First, install the required gems:

$ (sudo) gem install yajl-ruby
$ (sudo) gem install cool.io

Code:

require 'rubygems'
require 'cool.io'
require 'yajl'

ADDR = '127.0.0.1'
PORT = 2947

print = lambda { |data| puts data.inspect }
parser = Yajl::Parser.new
parser.on_parse_complete = print

cool.io.connect ADDR, PORT do
    on_connect do
        puts "Connected"
        write "?WATCH={\"enable\":true,\"json\":true}"
    end

    on_read do |data|
        parser << data
    end
end

puts "Running"
cool.io.run

blog comments powered by Disqus